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

package habit

import (
	"context"
	"fmt"
	"strings"

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

// ListToolName is the name of the list habits tool.
const ListToolName = "list_habits"

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

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

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

// Summary represents a habit in the list output.
type Summary struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Key  string `json:"key"`
}

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

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

	for _, habit := range h.habits {
		summaries = append(summaries, Summary{
			ID:   habit.ID,
			Name: habit.Name,
			Key:  habit.Key,
		})
	}

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

	text := formatListText(summaries)

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

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

	var text strings.Builder

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

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

	return text.String()
}
