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

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

import (
	"context"
	"fmt"
	"strings"

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

// ListToolName is the name of the list notebooks tool.
const ListToolName = "list_notebooks"

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

Returns notebook metadata (IDs, names, keys).
Use notebook IDs when creating or updating notes.`

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

// Summary represents a notebook 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 notebooks.
type ListOutput struct {
	Notebooks []Summary `json:"notebooks"`
	Count     int       `json:"count"`
}

// Handler handles notebook tool requests.
type Handler struct {
	notebooks []shared.NotebookProvider
}

// NewHandler creates a new notebook tool handler.
func NewHandler(notebooks []shared.NotebookProvider) *Handler {
	return &Handler{notebooks: notebooks}
}

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

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

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

	text := formatListText(summaries)

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

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

	var text strings.Builder

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

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

	return text.String()
}
