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

// Package areas provides the areas MCP resource for listing areas and goals.
package areas

import (
	"context"
	"encoding/json"

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

	"git.sr.ht/~amolith/lunatask-mcp-server/tools/shared"
)

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

// Handler handles area-related MCP resource requests.
type Handler struct {
	areas []shared.AreaProvider
}

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

// AreaInfo represents an area with its goals for JSON serialization.
type AreaInfo struct {
	Key   string     `json:"key"`
	Name  string     `json:"name"`
	ID    string     `json:"id"`
	Goals []GoalInfo `json:"goals,omitempty"`
}

// GoalInfo represents a goal for JSON serialization.
type GoalInfo struct {
	Key  string `json:"key"`
	Name string `json:"name"`
	ID   string `json:"id"`
}

// HandleRead handles the areas resource read request.
func (h *Handler) HandleRead(
	_ context.Context,
	_ *mcp.ReadResourceRequest,
) (*mcp.ReadResourceResult, error) {
	areasInfo := make([]AreaInfo, 0, len(h.areas))

	for _, area := range h.areas {
		areaInfo := AreaInfo{
			Key:   area.GetKey(),
			Name:  area.GetName(),
			ID:    area.GetID(),
			Goals: make([]GoalInfo, 0, len(area.GetGoals())),
		}

		for _, goal := range area.GetGoals() {
			areaInfo.Goals = append(areaInfo.Goals, GoalInfo{
				Key:  goal.GetKey(),
				Name: goal.GetName(),
				ID:   goal.GetID(),
			})
		}

		areasInfo = append(areasInfo, areaInfo)
	}

	data, err := json.MarshalIndent(areasInfo, "", "  ")
	if err != nil {
		return nil, err
	}

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