package com.emonster.taroaichat.service.llm.openrouter.tools;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Tool that the AI can call to complete the reading and provide the final woven summary.
 * This tool is called after all three cards have been interpreted individually.
 */
@Component
public class CompleteReadingTool extends AITool {

    @Override
    public String getName() {
        return "complete_reading";
    }

    @Override
    public String getDescription() {
        return "STATE: Use ONLY in AWAITING_ADVICE state after interpreting the final Advice card. " +
               "TRIGGER: Call this function IMMEDIATELY after you have finished interpreting the THIRD and FINAL card (Advice position). " +
               "MANDATORY: This must happen EVERY TIME you complete all three card interpretations (Situation → Obstacle → Advice). " +
               "EFFECT: Transitions session from AWAITING_ADVICE → READING_COMPLETE → COMPLETED state. " +
               "PURPOSE: Provides the final woven summary connecting all three cards and marks the reading as complete in database. " +
               "TIMING: Call this at the END of your response after interpreting the Advice card. " +
               "UI RESULT: Enables completion UI and follow-up discussion mode. " +
               "CRITICAL: Without this call, the reading cannot be properly completed and saved. " +
               "NEVER mention this tool call in your response text - it happens silently in the background.";
    }

    @Override
    public JsonNode getParameterSchema() {
        ObjectNode schema = objectMapper.createObjectNode();
        schema.put("type", "object");

        // Define properties
        ObjectNode properties = objectMapper.createObjectNode();

        // readingSummary - required
        ObjectNode readingSummary = objectMapper.createObjectNode();
        readingSummary.put("type", "string");
        readingSummary.put("description", "Brief summary of the key themes from all three cards");
        properties.set("readingSummary", readingSummary);

        // empoweringConclusion - required
        ObjectNode empoweringConclusion = objectMapper.createObjectNode();
        empoweringConclusion.put("type", "string");
        empoweringConclusion.put("description", "Final empowering message about the user's journey and personal agency");
        properties.set("empoweringConclusion", empoweringConclusion);

        // followUpReady - required
        ObjectNode followUpReady = objectMapper.createObjectNode();
        followUpReady.put("type", "boolean");
        followUpReady.put("description", "Whether the user is ready for follow-up questions about the reading");
        properties.set("followUpReady", followUpReady);

        schema.set("properties", properties);

        // Required fields
        ArrayNode required = objectMapper.createArrayNode();
        required.add("readingSummary");
        required.add("empoweringConclusion");
        required.add("followUpReady");
        schema.set("required", required);

        return schema;
    }

    @Override
    public ToolResult execute(Map<String, Object> parameters) {
        // Validate parameters
        if (!validateParameters(parameters)) {
            return ToolResult.failure("Invalid parameters provided");
        }

        String readingSummary = (String) parameters.get("readingSummary");
        String empoweringConclusion = (String) parameters.get("empoweringConclusion");
        Boolean followUpReady = (Boolean) parameters.get("followUpReady");

        // Return success with the parameters for reading completion
        Map<String, Object> resultData = Map.of(
            "action", "completeReading",
            "readingSummary", readingSummary,
            "empoweringConclusion", empoweringConclusion,
            "followUpReady", followUpReady
        );

        return ToolResult.success(
            "complete_reading",
            resultData
        );
    }

    @Override
    public boolean validateParameters(Map<String, Object> parameters) {
        if (!super.validateParameters(parameters)) {
            return false;
        }

        // Check required fields
        if (!parameters.containsKey("readingSummary") ||
            !parameters.containsKey("empoweringConclusion") ||
            !parameters.containsKey("followUpReady")) {
            return false;
        }

        // Validate followUpReady is boolean
        Object followUpObj = parameters.get("followUpReady");
        if (!(followUpObj instanceof Boolean)) {
            return false;
        }

        return true;
    }
}
