import { GoogleGenAI, Type } from "@google/genai";
import { ProgrammingLanguage } from "../types";

export interface ErrorAnalysis {
  errorType: 'Syntax' | 'Logic' | 'Runtime' | 'Conceptual';
  explanation: {
    what: string;
    why: string;
    where: string;
  };
  steps: {
    step1: string; // Identify mistake
    step2: string; // Explain concept
    step3: string; // Show correct approach
  };
  suggestedFix: string;
  correctLogic: string;
  correctedCode?: string;
  hints: string[]; // [Small clue, More guidance, Full explanation]
}

export async function analyzeError(
  studentCode: string,
  expectedOutput: string,
  actualOutput: string,
  language: ProgrammingLanguage,
  problemDescription: string
): Promise<ErrorAnalysis> {
  const apiKey = process.env.GEMINI_API_KEY;
  if (!apiKey) {
    throw new Error("Gemini API key is missing. Please configure it in the settings.");
  }

  const ai = new GoogleGenAI({ apiKey });

  try {
    const response = await ai.models.generateContent({
      model: "gemini-3-flash-preview",
      contents: `You are an expert AI Coding Tutor for school students (Classes 6-12). 
      Analyze the following incorrect code submission and provide a student-friendly explanation.
      
      Problem Description: ${problemDescription}
      Programming Language: ${language}
      Student Code:
      \`\`\`${language.toLowerCase()}
      ${studentCode}
      \`\`\`
      Expected Output: ${expectedOutput}
      Actual Output: ${actualOutput}
      
      Rules:
      1. Keep it simple and encouraging. No complex jargon.
      2. Identify the error type: Syntax, Logic, Runtime, or Conceptual.
      3. Provide a 3-step learning breakdown.
      4. Generate 3 progressive hints:
         - Hint 1: A very small clue to nudge them.
         - Hint 2: More specific guidance.
         - Hint 3: A full explanation of how to fix it.
      
      Return a JSON object with the following structure:
      {
        "errorType": "Syntax" | "Logic" | "Runtime" | "Conceptual",
        "explanation": {
          "what": "What exactly went wrong in simple terms",
          "why": "Why this is a mistake in this language",
          "where": "Where the mistake is (e.g., 'on the line where you defined the loop')"
        },
        "steps": {
          "step1": "Identify the mistake clearly",
          "step2": "Explain the underlying concept simply",
          "step3": "Show the correct approach without necessarily giving the full code yet"
        },
        "suggestedFix": "A short, actionable instruction to fix the code",
        "correctLogic": "Explain the correct logic that should have been used",
        "correctedCode": "The full corrected code snippet",
        "hints": ["Hint 1", "Hint 2", "Hint 3"]
      }`,
      config: {
        responseMimeType: "application/json",
        responseSchema: {
          type: Type.OBJECT,
          properties: {
            errorType: { type: Type.STRING },
            explanation: {
              type: Type.OBJECT,
              properties: {
                what: { type: Type.STRING },
                why: { type: Type.STRING },
                where: { type: Type.STRING }
              },
              required: ["what", "why", "where"]
            },
            steps: {
              type: Type.OBJECT,
              properties: {
                step1: { type: Type.STRING },
                step2: { type: Type.STRING },
                step3: { type: Type.STRING }
              },
              required: ["step1", "step2", "step3"]
            },
            suggestedFix: { type: Type.STRING },
            correctLogic: { type: Type.STRING },
            correctedCode: { type: Type.STRING },
            hints: {
              type: Type.ARRAY,
              items: { type: Type.STRING }
            }
          },
          required: ["errorType", "explanation", "steps", "suggestedFix", "correctLogic", "correctedCode", "hints"]
        }
      }
    });

    return JSON.parse(response.text) as ErrorAnalysis;
  } catch (error) {
    console.error("Error Analysis failed:", error);
    throw new Error("Failed to analyze the error. Please try again.");
  }
}
