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

// Package habit provides MCP tools for Lunatask habit operations.
package habit

import (
	"context"

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

// TrackToolName is the name of the track habit tool.
const TrackToolName = "track_habit"

// TrackToolDescription describes the track habit tool for LLMs.
const TrackToolDescription = `Records that a habit was performed on a specific date.

Required:
- habit_id: Habit UUID (get from lunatask://habits resource)

Optional:
- performed_on: Date performed (YYYY-MM-DD or natural language, default: today)

Use the lunatask://habits resource to discover valid habit IDs.`

// TrackInput is the input schema for tracking a habit.
type TrackInput struct {
	HabitID     string  `json:"habit_id"               jsonschema:"required"`
	PerformedOn *string `json:"performed_on,omitempty"`
}

// TrackOutput is the output schema for tracking a habit.
type TrackOutput struct {
	Success     bool   `json:"success"`
	HabitID     string `json:"habit_id"`
	PerformedOn string `json:"performed_on"`
}

// Handler handles habit-related MCP tool requests.
type Handler struct {
	client *lunatask.Client
	habits []shared.HabitProvider
}

// NewHandler creates a new habit handler.
func NewHandler(accessToken string, habits []shared.HabitProvider) *Handler {
	return &Handler{
		client: lunatask.NewClient(accessToken, lunatask.UserAgent("lune-mcp/1.0")),
		habits: habits,
	}
}

// HandleTrack records a habit activity.
func (h *Handler) HandleTrack(
	ctx context.Context,
	_ *mcp.CallToolRequest,
	input TrackInput,
) (*mcp.CallToolResult, TrackOutput, error) {
	if err := lunatask.ValidateUUID(input.HabitID); err != nil {
		return shared.ErrorResult("invalid habit_id: expected UUID"), TrackOutput{}, nil
	}

	dateStr := ""
	if input.PerformedOn != nil {
		dateStr = *input.PerformedOn
	}

	performedOn, err := dateutil.Parse(dateStr)
	if err != nil {
		return shared.ErrorResult(err.Error()), TrackOutput{}, nil
	}

	req := &lunatask.TrackHabitActivityRequest{
		PerformedOn: performedOn,
	}

	_, err = h.client.TrackHabitActivity(ctx, input.HabitID, req)
	if err != nil {
		return shared.ErrorResult(err.Error()), TrackOutput{}, nil
	}

	return nil, TrackOutput{
		Success:     true,
		HabitID:     input.HabitID,
		PerformedOn: performedOn.Format("2006-01-02"),
	}, nil
}
