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

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

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

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

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

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

Each habit contains:
- id: UUID to use when tracking habit completion
- name: Human-readable habit name
- key: Short alias for CLI usage

Use this resource to discover valid habit IDs before tracking habit activities.`

// Handler handles habit resource requests.
type Handler struct {
	habits []shared.HabitProvider
}

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

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

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

	for _, hab := range h.habits {
		habitsInfo = append(habitsInfo, habitInfo{
			ID:   hab.ID,
			Name: hab.Name,
			Key:  hab.Key,
		})
	}

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

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