package main

import (
	"context"
	"encoding/json"

	"github.com/mark3labs/mcp-go/mcp"
)

type codeArgs struct {
	ID string `json:"id"`
}

func codeTool() mcp.Tool {
	return mcp.NewTool("fn_code",
		mcp.WithDescription("Return only the source code (column `code`) for a function or type. Cheaper than fn_show when the markdown wrapping is not needed."),
		mcp.WithString("id",
			mcp.Required(),
			mcp.Description("Registry ID."),
		),
	)
}

func (d *deps) handleCode(ctx context.Context, _ mcp.CallToolRequest, args codeArgs) (*mcp.CallToolResult, error) {
	if args.ID == "" {
		return mcp.NewToolResultError("id is required"), nil
	}
	if f, err := d.db.GetFunction(args.ID); err == nil {
		out := map[string]any{
			"id":     f.ID,
			"entity": "function",
			"lang":   f.Lang,
			"code":   truncate(f.Code, 50_000),
		}
		b, _ := json.MarshalIndent(out, "", "  ")
		return mcp.NewToolResultText(string(b)), nil
	}
	if t, err := d.db.GetType(args.ID); err == nil {
		out := map[string]any{
			"id":     t.ID,
			"entity": "type",
			"lang":   t.Lang,
			"code":   truncate(t.Code, 50_000),
		}
		b, _ := json.MarshalIndent(out, "", "  ")
		return mcp.NewToolResultText(string(b)), nil
	}
	return mcp.NewToolResultError("id not found: " + args.ID), nil
}
