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 reveal and interpret a specific card in the sequential reading flow.
 * This tool handles the card-by-card interpretation process and tracks reading progress.
 */
@Component
public class RevealCardTool extends AITool {

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

    @Override
    public String getDescription() {
        return "STATE: Use in AWAITING_SITUATION, AWAITING_OBSTACLE, or AWAITING_ADVICE states. " +
               "SEQUENTIAL FLOW: Must follow order: situation → obstacle → advice. " +
               "AWAITING_SITUATION: Call reveal_card('situation') immediately when state entered. " +
               "AWAITING_OBSTACLE: Call reveal_card('obstacle') when user ready for next card or confirms continuation. " +
               "AWAITING_ADVICE: Call reveal_card('advice') when user ready for final card or confirms continuation. " +
               "TRIGGER: Only use AFTER user confirmation to proceed (e.g., 'I'm ready', 'yes', 'continue') - except for situation which should be immediate. " +
               "EFFECT: Advances state machine (situation→AWAITING_OBSTACLE, obstacle→AWAITING_ADVICE, advice→READING_COMPLETE). " +
               "UI RESULT: Triggers the card reveal UI showing the actual card to the user. " +
               "After calling this tool, provide brief transition like 'Let's reveal your [position] card...' followed by full interpretation. " +
               "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();

        // cardPosition - required
        ObjectNode cardPosition = objectMapper.createObjectNode();
        cardPosition.put("type", "string");
        cardPosition.put("description", "The position of the card to reveal and interpret");
        cardPosition.put("enum", objectMapper.createArrayNode()
            .add("situation")
            .add("obstacle")
            .add("advice")
        );
        properties.set("cardPosition", cardPosition);

        // cardInterpretationNote - optional
        ObjectNode cardInterpretationNote = objectMapper.createObjectNode();
        cardInterpretationNote.put("type", "string");
        cardInterpretationNote.put("description", "Brief note about what aspect of this specific card to emphasize");
        properties.set("cardInterpretationNote", cardInterpretationNote);

        schema.set("properties", properties);

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

        // Return success with the parameters for card revelation
        // The actual card interpretation content will be provided by AI after this tool call
        Map<String, Object> resultData = Map.of(
            "action", "revealCard",
            "cardPosition", cardPosition,
            "cardInterpretationNote", cardInterpretationNote != null ? cardInterpretationNote : ""
        );

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

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

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

        // Validate cardPosition
        String position = (String) parameters.get("cardPosition");
        if (position == null || !isValidCardPosition(position)) {
            return false;
        }

        return true;
    }

    private boolean isValidCardPosition(String position) {
        return position.equals("situation") ||
               position.equals("obstacle") ||
               position.equals("advice");
    }
}
