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 that the AI can call to begin the card interpretation phase
 * after user has shared their context. Follows official Gemini SDK patterns.
 */
@Component
public class GeminiStartInterpretationTool extends GeminiAITool {

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

    @Override
    public String getDescription() {
        return "STATE: Use ONLY in AWAITING_USER_CONTEXT state. " +
                "TRIGGER: Call this function as soon as the user provides ANY topic or context for their situation. " +
                "GOAL: Capture the user's initial thought, even if vague. Tarot works with any level of detail. " +
                "--- PARAMETER LOGIC ---" +
                "Set readyToInterpret=true IF the user provides a specific question OR a situation with some detail (e.g., 'Should I take the new job?', 'My partner wants to move...'). " +
                "Set readyToInterpret=false IF the user provides a vague concept OR a simple greeting (e.g., 'work stress', 'relationships', 'hello', 'what is this?'). " +
                "--- METADATA ---" +
                "EFFECT: Transitions session from AWAITING_USER_CONTEXT → READY_FOR_INTERPRETATION state. " +
                "UI RESULT: Captures context silently. Enables the 'Begin Interpretation' button ONLY when readyToInterpret=true. " +
                "IMPORTANT: Use camelCase for parameter names as defined in the schema (userContext, readyToInterpret, overallTheme). " +
                "NEVER mention this tool call in your response text - it happens silently in the background. ";
    }

    @Override
    public Schema getParameterSchema() {
        return Schema.builder()
            .type(Type.Known.OBJECT)
            .properties(Map.of(
                "userContext", Schema.builder()
                    .type(Type.Known.STRING)
                    .description("The user's question or situation they've shared for the reading")
                    .build(),
                "overallTheme", Schema.builder()
                    .type(Type.Known.STRING)
                    .description("Brief theme or focus area for the overall reading session")
                    .enum_(List.of(
                        "relationships",
                        "career",
                        "personal_growth",
                        "decision_making",
                        "spiritual_guidance",
                        "general"
                    ))
                    .build(),
                "readyToInterpret", Schema.builder()
                    .type(Type.Known.BOOLEAN)
                    .description("Whether the user has shared enough context to begin interpretation")
                    .build()
            ))
            .required(List.of("userContext", "readyToInterpret"))
            .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 userContext = (String) parameters.getOrDefault("userContext", parameters.get("user_context"));
        Boolean readyToInterpret = (Boolean) parameters.getOrDefault("readyToInterpret", parameters.get("ready_to_interpret"));
        String overallTheme = (String) parameters.getOrDefault("overallTheme", parameters.get("overall_theme"));

        LOG.info("Gemini start_interpretation tool called: ready={}, context='{}'",
                readyToInterpret, userContext.substring(0, Math.min(50, userContext.length())));

        // 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 GeminiToolResult.success(
            "start_interpretation 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("userContext") && !parameters.containsKey("user_context")) ||
            (!parameters.containsKey("readyToInterpret") && !parameters.containsKey("ready_to_interpret"))) {
            LOG.warn("Missing required parameters: userContext/user_context or readyToInterpret/ready_to_interpret");
            return false;
        }

        // Validate readyToInterpret is boolean - try both naming conventions
        Object readyObj = parameters.getOrDefault("readyToInterpret", parameters.get("ready_to_interpret"));
        if (!(readyObj instanceof Boolean)) {
            LOG.warn("readyToInterpret parameter must be boolean, got: {}", readyObj.getClass());
            return false;
        }

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

        // Validate overallTheme if provided - try both naming conventions
        if (parameters.containsKey("overallTheme") || parameters.containsKey("overall_theme")) {
            String theme = (String) parameters.getOrDefault("overallTheme", parameters.get("overall_theme"));
            if (theme != null && !isValidOverallTheme(theme)) {
                LOG.warn("Invalid overallTheme: {}", theme);
                return false;
            }
        }

        return true;
    }

    private boolean isValidOverallTheme(String theme) {
        return List.of("relationships", "career", "personal_growth",
                      "decision_making", "spiritual_guidance", "general")
                  .contains(theme);
    }
}
