// Package mcp provides MCP client and server implementations.
package mcp

import (
	"context"
	"fmt"
	"log/slog"

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

	"github.com/enmanuel/agents/pkg/tools"
)

// MCPServer exposes agent tools as an MCP server.
type MCPServer struct {
	srv    *server.MCPServer
	logger *slog.Logger
}

// NewMCPServer creates an MCP server exposing the given tool specs.
func NewMCPServer(name, version string, specs []tools.ToolSpec, logger *slog.Logger) *MCPServer {
	srv := server.NewMCPServer(name, version)

	for _, spec := range specs {
		spec := spec // capture
		tool := mcp.NewTool(spec.Name,
			mcp.WithDescription(spec.Description),
		)
		srv.AddTool(tool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
			// Placeholder handler — wire real execution here
			return mcp.NewToolResultText(fmt.Sprintf("tool %s called", spec.Name)), nil
		})
	}

	return &MCPServer{srv: srv, logger: logger}
}

// ServeStdio runs the MCP server over stdin/stdout (for Claude Desktop / CLI integration).
func (m *MCPServer) ServeStdio(ctx context.Context) error {
	m.logger.Info("mcp server starting on stdio")
	return server.ServeStdio(m.srv)
}
