import { GeminiOmniSchema, type GeminiOmniInput, type PromptVariation } from "@/lib/schemas/universal-prompt.schema";
import { BasePromptAdapter, extractVariations, type AdapterValidationResult } from "./base.adapter";

export class GeminiOmniPromptAdapter extends BasePromptAdapter<GeminiOmniInput> {
  platform = "gemini_omni" as const;

  validateInput(input: unknown): AdapterValidationResult {
    const result = GeminiOmniSchema.safeParse(input);
    if (result.success) return { success: true };
    return {
      success: false,
      errors: result.error.errors.map((e) => `${e.path.join(".")}: ${e.message}`),
    };
  }

  constructSystemPrompt(input: GeminiOmniInput, variationCount: number): string {
    // Fix #4: Tambah shotList schema lengkap agar tab Shot List terisi untuk Gemini
    // Fix #5: Sertakan language instruction di system prompt
    const langInstruction =
      input.language === "id"
        ? "Write all textPrompt and script fields in Bahasa Indonesia."
        : "Write all textPrompt and script fields in English.";

    return `You are an expert Gemini AI prompt engineer specializing in multimodal generation. Create ${variationCount} optimized prompt(s) for Google Gemini Omni Flash.

Rules:
1. Leverage Gemini's multimodal understanding capabilities
2. Be specific about output type (image/video/audio)
3. Use descriptive, layered prompting techniques
4. Include technical quality parameters
5. Output MUST be valid JSON matching the schema exactly
6. Generate exactly ${variationCount} variation(s)
7. Each variation should have a distinct creative angle while keeping the core subject
8. ${langInstruction}

Output format (strict JSON):
{
  "variations": [
    {
      "index": 0,
      "textPrompt": "optimized Gemini prompt",
      "negativePrompt": "exclusions and things to avoid",
      "jsonOutput": {
        "prompt": "...",
        "outputType": "...",
        "quality": "...",
        "aspectRatio": "...",
        "style": "...",
        "mood": "...",
        "technicalParams": {},
        "safetySettings": {}
      },
      "shotList": [
        {
          "shotNumber": 1,
          "shotType": "establishing shot | close-up | medium | wide | macro | etc.",
          "cameraAngle": "eye level | high angle | low angle | bird's eye | etc.",
          "cameraMovement": "static | pan left | pan right | tilt up | zoom in | dolly | etc.",
          "subject": "main subject description",
          "action": "what is happening in this frame/shot",
          "duration": "2s",
          "notes": "generation guidance and composition notes for this frame"
        }
      ],
      "script": "Full generation guidance: scene description, composition notes, mood direction, and technical specs"
    }
  ]
}`;
  }

  // Fix #2: variationIndex dihapus — tidak dipakai, satu call menghasilkan semua variasi
  // Fix #5: Language sudah ditangani di system prompt
  constructUserPrompt(input: GeminiOmniInput): string {
    return `Create ${input.variations} Gemini Omni Flash prompt(s):

Subject/Topic: ${input.subject}
Output Type: ${input.outputType ?? "image"}
Quality: ${input.quality ?? "high"}
${input.aspectRatio ? `Aspect Ratio: ${input.aspectRatio}` : ""}
${input.style ? `Style: ${input.style}` : ""}
${input.mood ? `Mood: ${input.mood}` : ""}
${input.additionalContext ? `Additional Context: ${input.additionalContext}` : ""}
${input.negativePrompt ? `Exclude: ${input.negativePrompt}` : ""}
Safety Level: ${input.safetyLevel ?? "default"}
Mode: ${input.mode}
Language: ${input.language === "id" ? "Bahasa Indonesia" : "English"}`;
  }

  transformOutput(rawOutput: string, input: GeminiOmniInput): PromptVariation {
    const parsed = this.parseJsonSafe(rawOutput);
    const variations = parsed ? extractVariations(parsed) : null;
    if (variations && variations.length > 0) {
      return variations[0];
    }
    return {
      index: 0,
      textPrompt: rawOutput,
      negativePrompt: this.buildNegativePrompt(input),
      jsonOutput: this.generateJsonOutput(input),
    };
  }

  generateTextPrompt(input: GeminiOmniInput): string {
    return [
      input.subject,
      input.style,
      input.mood,
      `${input.quality ?? "high"} quality`,
      input.outputType === "video" ? "video generation" : "photorealistic",
      input.aspectRatio && `${input.aspectRatio} ratio`,
    ]
      .filter(Boolean)
      .join(", ");
  }

  generateJsonOutput(input: GeminiOmniInput): Record<string, unknown> {
    return {
      platform: "gemini_omni",
      prompt: this.generateTextPrompt(input),
      outputType: input.outputType ?? "image",
      quality: input.quality ?? "high",
      aspectRatio: input.aspectRatio ?? "1:1",
      style: input.style ?? "photorealistic",
      mood: input.mood,
      safetyLevel: input.safetyLevel ?? "default",
      negativePrompt: this.buildNegativePrompt(input),
    };
  }

  protected override getDefaultNegativePrompts(): string[] {
    return [
      "low quality",
      "blurry",
      "distorted",
      "watermark",
      "text overlay",
      "artifacts",
      "overexposed",
      "underexposed",
    ];
  }
}
