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

package person

import (
	"context"
	"fmt"

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

// UpdateToolName is the name of the update person tool.
const UpdateToolName = "update_person"

// UpdateToolDescription describes the update person tool for LLMs.
const UpdateToolDescription = `Updates an existing person in Lunatask.

Required:
- id: Person UUID or lunatask://person/... deep link

Optional:
- first_name: New first name
- last_name: New last name
- relationship: New relationship strength (family, intimate-friends,
  close-friends, casual-friends, acquaintances, business-contacts, almost-strangers)

Only provided fields are modified; other fields remain unchanged.`

// UpdateInput is the input schema for updating a person.
type UpdateInput struct {
	ID           string  `json:"id"                     jsonschema:"required"`
	FirstName    *string `json:"first_name,omitempty"`
	LastName     *string `json:"last_name,omitempty"`
	Relationship *string `json:"relationship,omitempty"`
}

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

// HandleUpdate updates an existing person.
func (h *Handler) HandleUpdate(
	ctx context.Context,
	_ *mcp.CallToolRequest,
	input UpdateInput,
) (*mcp.CallToolResult, UpdateOutput, error) {
	id, err := parseReference(input.ID)
	if err != nil {
		return shared.ErrorResult(err.Error()), UpdateOutput{}, nil
	}

	builder := h.client.NewPersonUpdate(id)

	if input.FirstName != nil {
		builder.FirstName(*input.FirstName)
	}

	if input.LastName != nil {
		builder.LastName(*input.LastName)
	}

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

		builder.WithRelationshipStrength(rel)
	}

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

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

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

// parseReference extracts UUID from either a raw UUID or a lunatask:// deep link.
func parseReference(ref string) (string, error) {
	_, id, err := lunatask.ParseReference(ref)
	if err != nil {
		return "", fmt.Errorf("invalid ID: %w", err)
	}

	return id, nil
}
