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

// Package person provides MCP tools for Lunatask person/relationship operations.
package person

import (
	"context"

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

// CreateToolName is the name of the create person tool.
const CreateToolName = "create_person"

// CreateToolDescription describes the create person tool for LLMs.
const CreateToolDescription = `Creates a new person in Lunatask's relationship tracker.

Required:
- first_name: First name

Optional:
- last_name: Last name
- relationship: Relationship strength (family, intimate-friends, close-friends,
  casual-friends, acquaintances, business-contacts, almost-strangers)
  Default: casual-friends
- source: Origin identifier for integrations
- source_id: Source-specific ID (requires source)

Returns the deep link to the created person.`

// CreateInput is the input schema for creating a person.
type CreateInput struct {
	FirstName    string  `json:"first_name"             jsonschema:"required"`
	LastName     *string `json:"last_name,omitempty"`
	Relationship *string `json:"relationship,omitempty"`
	Source       *string `json:"source,omitempty"`
	SourceID     *string `json:"source_id,omitempty"`
}

// CreateOutput is the output schema for creating a person.
type CreateOutput struct {
	DeepLink string `json:"deep_link"`
}

// Handler handles person-related MCP tool requests.
type Handler struct {
	client *lunatask.Client
}

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

// HandleCreate creates a new person.
func (h *Handler) HandleCreate(
	ctx context.Context,
	_ *mcp.CallToolRequest,
	input CreateInput,
) (*mcp.CallToolResult, CreateOutput, error) {
	lastName := ""
	if input.LastName != nil {
		lastName = *input.LastName
	}

	builder := h.client.NewPerson(input.FirstName, lastName)

	if input.Relationship != nil {
		rel, err := lunatask.ParseRelationshipStrength(*input.Relationship)
		if err != nil {
			return shared.ErrorResult(err.Error()), CreateOutput{}, nil
		}

		builder.WithRelationshipStrength(rel)
	}

	if input.Source != nil && input.SourceID != nil {
		builder.FromSource(*input.Source, *input.SourceID)
	}

	person, err := builder.Create(ctx)
	if err != nil {
		return shared.ErrorResult(err.Error()), CreateOutput{}, nil
	}

	deepLink, _ := lunatask.BuildDeepLink(lunatask.ResourcePerson, person.ID)

	return &mcp.CallToolResult{
		Content: []mcp.Content{&mcp.TextContent{
			Text: "Person created: " + deepLink,
		}},
	}, CreateOutput{DeepLink: deepLink}, nil
}
