package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"git.threefold.info/herocode/heroagent/pkg/openrpc"
)

func main() {
	// Parse command line flags
	var (
		specDir    = flag.String("dir", "pkg/openrpc/services", "Directory containing OpenRPC specifications")
		specName   = flag.String("spec", "", "Name of the specification to display (optional)")
		methodName = flag.String("method", "", "Name of the method to display (optional)")
	)
	flag.Parse()

	// Create a new OpenRPC Manager
	manager := openrpc.NewORPCManager()

	// Ensure the specification directory exists
	if _, err := os.Stat(*specDir); os.IsNotExist(err) {
		log.Fatalf("Specification directory does not exist: %s", *specDir)
	}

	// Load all specifications from the directory
	log.Printf("Loading specifications from %s...", *specDir)
	if err := manager.LoadSpecs(*specDir); err != nil {
		log.Fatalf("Failed to load specifications: %v", err)
	}

	// List all loaded specifications
	specs := manager.ListSpecs()
	if len(specs) == 0 {
		log.Fatalf("No specifications found in %s", *specDir)
	}

	fmt.Println("Loaded specifications:")
	for _, spec := range specs {
		fmt.Printf("- %s\n", spec)
	}

	// If a specification name is provided, display its methods
	if *specName != "" {
		spec := manager.GetSpec(*specName)
		if spec == nil {
			log.Fatalf("Specification not found: %s", *specName)
		}

		fmt.Printf("\nMethods in %s specification:\n", *specName)
		methods := manager.ListMethods(*specName)
		for _, method := range methods {
			fmt.Printf("- %s\n", method)
		}

		// If a method name is provided, display its details
		if *methodName != "" {
			method := manager.GetMethod(*specName, *methodName)
			if method == nil {
				log.Fatalf("Method not found: %s", *methodName)
			}

			fmt.Printf("\nDetails for method '%s':\n", *methodName)
			fmt.Printf("Description: %s\n", method.Description)
			fmt.Printf("Parameters: %d\n", len(method.Params))

			if len(method.Params) > 0 {
				fmt.Println("Parameter list:")
				for _, param := range method.Params {
					required := ""
					if param.Required {
						required = " (required)"
					}
					fmt.Printf("  - %s%s: %s\n", param.Name, required, param.Description)
				}
			}

			fmt.Printf("Result: %s\n", method.Result.Name)
			fmt.Printf("Examples: %d\n", len(method.Examples))
			fmt.Printf("Errors: %d\n", len(method.Errors))
		}
	}
}
