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

import com.google.genai.types.Schema;
import com.google.genai.types.Type;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Gemini-native tool for completing a tarot reading session.
 * Follows official Gemini SDK patterns.
 */
@Component
public class GeminiCompleteReadingTool extends GeminiAITool {

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

    @Override
    public String getDescription() {
        return "STATE: Use ONLY in INTERPRETATION_IN_PROGRESS state when all cards have been revealed and interpreted. " +
               "TRIGGER: Call when providing final synthesis, overall reading summary, or when user indicates they're satisfied with the reading. " +
               "TIMING: Should be called after all individual cards have been revealed and discussed. " +
               "SYNTHESIS: Provide a cohesive summary that ties all cards together in context of the user's original question. " +
               "EFFECT: Transitions session from INTERPRETATION_IN_PROGRESS → COMPLETED state. " +
               "UI RESULT: Marks reading as complete, may show completion UI elements. " +
               "IMPORTANT: Use camelCase for parameter names as defined in the schema (overallMessage, keyInsights, etc). " +
               "NEVER mention this tool call in your response text - focus on the reading synthesis. " +
               "End with encouragement and invitation for future readings.";
    }

    @Override
    public Schema getParameterSchema() {
        return Schema.builder()
            .type(Type.Known.OBJECT)
            .properties(Map.of(
                "overallMessage", Schema.builder()
                    .type(Type.Known.STRING)
                    .description("The synthesized overall message from the complete reading")
                    .build(),
                "keyInsights", Schema.builder()
                    .type(Type.Known.ARRAY)
                    .description("Key insights and takeaways from the reading")
                    .items(Schema.builder()
                        .type(Type.Known.STRING)
                        .build())
                    .build(),
                "actionableAdvice", Schema.builder()
                    .type(Type.Known.STRING)
                    .description("Practical advice or next steps for the user based on the reading")
                    .build(),
                "readingSummary", Schema.builder()
                    .type(Type.Known.STRING)
                    .description("Comprehensive summary of the reading's key insights, themes, and guidance - not just card names. Include the main message, key insights, and how the cards work together to address the user's situation. This should be a meaningful narrative summary of the reading.")
                    .build(),
                "empoweringConclusion", Schema.builder()
                    .type(Type.Known.STRING)
                    .description("Empowering closing message for the user (optional)")
                    .build(),
                "followUpReady", Schema.builder()
                    .type(Type.Known.BOOLEAN)
                    .description("Whether the user seems ready for follow-up questions or discussion (optional)")
                    .build()
            ))
            .required(List.of("overallMessage", "keyInsights"))
            .build();
    }

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

        // Try both camelCase and snake_case parameter names
        String overallMessage = (String) parameters.getOrDefault("overallMessage", parameters.get("overall_message"));
        @SuppressWarnings("unchecked")
        List<String> keyInsights = (List<String>) parameters.getOrDefault("keyInsights", parameters.get("key_insights"));
        String actionableAdvice = (String) parameters.getOrDefault("actionableAdvice", parameters.get("actionable_advice"));
        String readingSummary = (String) parameters.getOrDefault("readingSummary", parameters.get("reading_summary"));
        String empoweringConclusion = (String) parameters.getOrDefault("empoweringConclusion", parameters.get("empowering_conclusion"));
        Boolean followUpReady = (Boolean) parameters.getOrDefault("followUpReady", parameters.get("follow_up_ready"));

        LOG.info("=== COMPLETE_READING TOOL DEBUG ===");
        LOG.info("Overall message length: {}", overallMessage != null ? overallMessage.length() : 0);
        LOG.info("Key insights count: {}", keyInsights != null ? keyInsights.size() : 0);
        LOG.info("Reading summary: '{}'", readingSummary);
        LOG.info("Actionable advice: '{}'", actionableAdvice);
        LOG.info("Empowering conclusion: '{}'", empoweringConclusion);
        LOG.info("Follow up ready: {}", followUpReady);
        LOG.info("Raw parameters received: {}", parameters);
        LOG.info("=== END COMPLETE_READING TOOL DEBUG ===");

        // Return success with the reading completion data
        Map<String, Object> resultData = Map.of(
            "action", "completeReading",
            "overallMessage", overallMessage,
            "keyInsights", keyInsights,
            "actionableAdvice", actionableAdvice != null ? actionableAdvice : "",
            "readingSummary", readingSummary != null ? readingSummary : "",
            "empoweringConclusion", empoweringConclusion != null ? empoweringConclusion : "",
            "followUpReady", followUpReady != null ? followUpReady : false
        );

        return GeminiToolResult.success(
            "complete_reading executed successfully",
            resultData
        );
    }

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

        // Check required fields - accept both camelCase and snake_case
        if ((!parameters.containsKey("overallMessage") && !parameters.containsKey("overall_message")) || 
            (!parameters.containsKey("keyInsights") && !parameters.containsKey("key_insights"))) {
            LOG.warn("Missing required parameters: overallMessage/overall_message or keyInsights/key_insights");
            return false;
        }

        // Validate overallMessage is not empty - try both naming conventions
        String overallMessage = (String) parameters.getOrDefault("overallMessage", parameters.get("overall_message"));
        if (overallMessage == null || overallMessage.trim().isEmpty()) {
            LOG.warn("overallMessage parameter cannot be empty");
            return false;
        }

        // Validate keyInsights is a list and not empty - try both naming conventions
        Object keyInsightsObj = parameters.getOrDefault("keyInsights", parameters.get("key_insights"));
        if (!(keyInsightsObj instanceof List)) {
            LOG.warn("keyInsights parameter must be a list, got: {}", keyInsightsObj.getClass());
            return false;
        }

        @SuppressWarnings("unchecked")
        List<String> keyInsights = (List<String>) keyInsightsObj;
        if (keyInsights.isEmpty()) {
            LOG.warn("keyInsights parameter cannot be empty");
            return false;
        }

        return true;
    }
}
