package main

import (
	"flag"
	"fmt"

	"github.com/ghodss/yaml"
	"github.com/jhump/protoreflect/desc/protoparse"
	"github.com/jhump/protoreflect/desc/protoparse/ast"
)

func main() {
	path := flag.String("p", "", "the proto file path")
	flag.Parse()
	parser := protoparse.Parser{}
	fd, err := parser.ParseToAST(*path)
	if err != nil {
		panic(fmt.Errorf("parse to AST failed: %s", err))
	}
	result := []*RPC{}
	for _, child := range fd[0].Children() {
		switch child.(type) {
		case *ast.ServiceNode:
			rpc := extractGrpc(child.(*ast.ServiceNode))
			result = append(result, rpc)
		}
	}
	if len(result) > 0 {
		r, _ := yaml.Marshal(result)
		fmt.Println(string(r))
	}
}

type RPC struct {
	Service string   `json:"service"`
	Methods []string `json:"methods"`
}

func extractGrpc(node *ast.ServiceNode) *RPC {
	rpc := RPC{Service: node.Name.RawText()}
	for _, child := range node.Children() {
		switch child.(type) {
		case *ast.RPCNode:
			c := child.(*ast.RPCNode)
			rpc.Methods = append(rpc.Methods, c.Name.RawText())
		}
	}
	return &rpc
}
