// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

// Package area provides MCP tools for area operations.
package area

import (
	"context"
	"fmt"
	"strings"

	"git.secluded.site/lune/internal/mcp/shared"
	"github.com/modelcontextprotocol/go-sdk/mcp"
)

// ListToolName is the name of the list areas tool.
const ListToolName = "list_areas"

// ListToolDescription describes the list areas tool for LLMs.
const ListToolDescription = `Lists configured areas. Fallback for lunatask://areas resource.

Returns area metadata (id, name, key, workflow) from config.
Use the lunatask://areas resource if your client supports MCP resources.`

// ListInput is the input schema for listing areas.
type ListInput struct{}

// Summary represents an area in the list output.
type Summary struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Key      string `json:"key"`
	Workflow string `json:"workflow"`
}

// ListOutput is the output schema for listing areas.
type ListOutput struct {
	Areas []Summary `json:"areas"`
	Count int       `json:"count"`
}

// Handler handles area tool requests.
type Handler struct {
	areas []shared.AreaProvider
}

// NewHandler creates a new area tool handler.
func NewHandler(areas []shared.AreaProvider) *Handler {
	return &Handler{areas: areas}
}

// HandleList lists configured areas.
func (h *Handler) HandleList(
	_ context.Context,
	_ *mcp.CallToolRequest,
	_ ListInput,
) (*mcp.CallToolResult, ListOutput, error) {
	summaries := make([]Summary, 0, len(h.areas))

	for _, area := range h.areas {
		summaries = append(summaries, Summary{
			ID:       area.ID,
			Name:     area.Name,
			Key:      area.Key,
			Workflow: string(area.Workflow),
		})
	}

	output := ListOutput{
		Areas: summaries,
		Count: len(summaries),
	}

	text := formatListText(summaries)

	return &mcp.CallToolResult{
		Content: []mcp.Content{&mcp.TextContent{Text: text}},
	}, output, nil
}

func formatListText(areas []Summary) string {
	if len(areas) == 0 {
		return "No areas configured"
	}

	var text strings.Builder

	text.WriteString(fmt.Sprintf("Found %d area(s):\n", len(areas)))

	for _, a := range areas {
		text.WriteString(fmt.Sprintf("- %s: %s (%s, workflow: %s)\n", a.Key, a.Name, a.ID, a.Workflow))
	}

	return text.String()
}
