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 begin the card interpretation phase after user has shared their context.
 * This will trigger the UI to show the "Begin Interpretation" button for the conversational reading flow.
 */
@Component
public class StartInterpretationTool extends AITool {

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

    @Override
    public String getDescription() {
        return "STATE: Use ONLY in AWAITING_USER_CONTEXT state. " +
               "TRIGGER: Call this function ONLY when the user shares SPECIFIC, DETAILED context about their situation. " +
               "GOOD examples: 'I have a presentation next week and worried it won't be received well', 'My partner wants to move for their job but I just got promoted'. " +
               "BAD examples (DO NOT call tool): 'work stress', 'some things', 'relationship issues', 'feeling stuck', 'stressed about stuff'. " +
               "If they mention 'some things' or 'stuff' or any vague reference, you MUST ask for specifics first! " +
               "Set readyToInterpret=true ONLY if they gave specific details. Set readyToInterpret=false if context is vague. " +
               "EFFECT: Transitions session from AWAITING_USER_CONTEXT → READY_FOR_INTERPRETATION state. " +
               "UI RESULT: Enables the 'Begin Interpretation' button when ready. " +
               "NEVER mention this tool call in your response text - it happens silently in the background. " +
               "End your response with a loading hint like 'Let me attune to your energy...' to smooth the button appearance.";
    }

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

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

        // userContext - required
        ObjectNode userContext = objectMapper.createObjectNode();
        userContext.put("type", "string");
        userContext.put("description", "The user's question or situation they've shared for the reading");
        properties.set("userContext", userContext);

        // overallTheme - optional
        ObjectNode overallTheme = objectMapper.createObjectNode();
        overallTheme.put("type", "string");
        overallTheme.put("description", "Brief theme or focus area for the overall reading session");
        overallTheme.put("enum", objectMapper.createArrayNode()
            .add("relationships")
            .add("career")
            .add("personal_growth")
            .add("decision_making")
            .add("spiritual_guidance")
            .add("general")
        );
        properties.set("overallTheme", overallTheme);

        // readyToInterpret - required
        ObjectNode readyToInterpret = objectMapper.createObjectNode();
        readyToInterpret.put("type", "boolean");
        readyToInterpret.put("description", "Whether the user has shared enough context to begin interpretation");
        properties.set("readyToInterpret", readyToInterpret);

        schema.set("properties", properties);

        // Required fields
        ArrayNode required = objectMapper.createArrayNode();
        required.add("userContext");
        required.add("readyToInterpret");
        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 userContext = (String) parameters.get("userContext");
        Boolean readyToInterpret = (Boolean) parameters.get("readyToInterpret");
        String overallTheme = (String) parameters.get("overallTheme");

        // Return success with the parameters for enabling the interpretation button
        // The actual UI update will be handled by sending an SSE event
        Map<String, Object> resultData = Map.of(
            "action", "enableInterpretationButton",
            "userContext", userContext,
            "readyToInterpret", readyToInterpret,
            "overallTheme", overallTheme != null ? overallTheme : "general"
        );

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

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

        // Check required fields
        if (!parameters.containsKey("userContext") || !parameters.containsKey("readyToInterpret")) {
            return false;
        }

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

        // Validate overallTheme if provided
        if (parameters.containsKey("overallTheme")) {
            String theme = (String) parameters.get("overallTheme");
            if (theme != null && !isValidOverallTheme(theme)) {
                return false;
            }
        }

        return true;
    }

    private boolean isValidOverallTheme(String theme) {
        return theme.equals("relationships") ||
               theme.equals("career") ||
               theme.equals("personal_growth") ||
               theme.equals("decision_making") ||
               theme.equals("spiritual_guidance") ||
               theme.equals("general");
    }
}
