package cmd

import (
	"context"
	"fmt"

	"github.com/modelcontextprotocol/go-sdk/mcp"
	"github.com/spf13/cobra"
)

var stdioCmd = &cobra.Command{
	Use:   "stdio",
	Short: "Run a stdio MCP bridge backed by a remote AMCS server",
	RunE: func(cmd *cobra.Command, _ []string) error {
		ctx := cmd.Context()
		remote, err := connectRemote(ctx)
		if err != nil {
			return err
		}
		defer func() { _ = remote.Close() }()

		tools, err := remote.ListTools(ctx, nil)
		if err != nil {
			return fmt.Errorf("load remote tools: %w", err)
		}

		server := mcp.NewServer(&mcp.Implementation{
			Name:    "amcs-cli",
			Title:   "AMCS CLI Bridge",
			Version: "0.0.1",
		}, nil)

		for _, tool := range tools.Tools {
			remoteTool := tool
			server.AddTool(&mcp.Tool{
				Name:         remoteTool.Name,
				Description:  remoteTool.Description,
				InputSchema:  remoteTool.InputSchema,
				OutputSchema: remoteTool.OutputSchema,
				Annotations:  remoteTool.Annotations,
			}, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
				return remote.CallTool(ctx, &mcp.CallToolParams{
					Name:      req.Params.Name,
					Arguments: req.Params.Arguments,
				})
			})
		}

		session, err := server.Connect(ctx, &mcp.StdioTransport{}, nil)
		if err != nil {
			return fmt.Errorf("start stdio bridge: %w", err)
		}
		defer func() { _ = session.Close() }()
		verboseLogf("stdio bridge connected to remote AMCS and ready")
		verboseLogf("waiting for MCP commands on stdin")

		<-ctx.Done()
		return nil
	},
}

func init() {
	rootCmd.AddCommand(stdioCmd)
}
