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

// Package notebooks provides the MCP resource handler for Lunatask notebooks.
package notebooks

import (
	"context"
	"encoding/json"
	"fmt"

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

// ResourceURI is the URI for the notebooks resource.
const ResourceURI = "lunatask://notebooks"

// ResourceDescription describes the notebooks resource for LLMs.
const ResourceDescription = `Lists all configured Lunatask notebooks.

Each notebook contains:
- id: UUID to use when creating notes in this notebook
- name: Human-readable notebook name
- key: Short alias for CLI usage

Use this resource to discover valid notebook IDs before creating or updating notes.`

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

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

// notebookInfo represents a notebook in the resource response.
type notebookInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Key  string `json:"key"`
}

// HandleRead returns the configured notebooks.
func (h *Handler) HandleRead(
	_ context.Context,
	_ *mcp.ReadResourceRequest,
) (*mcp.ReadResourceResult, error) {
	notebooksInfo := make([]notebookInfo, 0, len(h.notebooks))

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

	data, err := json.MarshalIndent(notebooksInfo, "", "  ")
	if err != nil {
		return nil, fmt.Errorf("marshaling notebooks: %w", err)
	}

	return &mcp.ReadResourceResult{
		Contents: []*mcp.ResourceContents{{
			URI:      ResourceURI,
			MIMEType: "application/json",
			Text:     string(data),
		}},
	}, nil
}
