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

export class SeedancePromptAdapter extends BasePromptAdapter<SeedanceInput> {
  platform = "seedance" as const;

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

  constructSystemPrompt(input: SeedanceInput, variationCount: number): string {
    return `You are a professional Seedance AI video prompt engineer. Your task is to generate ${variationCount} unique, high-quality video generation prompts for Seedance AI.

Rules:
1. Each prompt must be detailed, cinematic, and technically precise
2. Include specific camera movements, lighting, and composition details
3. Use professional cinematography terminology
4. Output MUST be valid JSON matching the schema exactly
5. Generate exactly ${variationCount} variation(s)
6. Each variation should have a distinct creative angle while keeping the core subject
7. Negative prompts should list what to avoid for best quality

Output format (strict JSON):
{
  "variations": [
    {
      "index": 0,
      "textPrompt": "full cinematic prompt here",
      "negativePrompt": "things to avoid",
      "jsonOutput": {
        "subject": "...",
        "cameraMotion": "...",
        "cameraAngle": "...",
        "lighting": "...",
        "colorGrading": "...",
        "style": "...",
        "mood": "...",
        "duration": "...",
        "resolution": "...",
        "fps": "...",
        "technicalNotes": "..."
      },
      "shotList": [
        {
          "shotNumber": 1,
          "shotType": "...",
          "cameraAngle": "...",
          "cameraMovement": "...",
          "subject": "...",
          "action": "...",
          "duration": "...",
          "notes": "..."
        }
      ],
      "script": "Scene description and director notes..."
    }
  ]
}`;
  }

  // Fix #2: variationIndex dihapus — tidak dipakai, satu call untuk semua variasi
  constructUserPrompt(input: SeedanceInput): string {
    const lang = input.language === "id" ? "Indonesian" : "English";
    return `Generate ${input.variations} Seedance video prompt variation(s) for:
    
Subject: ${input.subject}
${input.style ? `Style: ${input.style}` : ""}
${input.mood ? `Mood/Atmosphere: ${input.mood}` : ""}
${input.cameraMotion ? `Camera Motion: ${input.cameraMotion.replace(/_/g, " ")}` : ""}
${input.cameraAngle ? `Camera Angle: ${input.cameraAngle.replace(/_/g, " ")}` : ""}
${input.lighting ? `Lighting: ${input.lighting}` : ""}
${input.colorGrading ? `Color Grading: ${input.colorGrading.replace(/_/g, " ")}` : ""}
${input.duration ? `Duration: ${input.duration}` : ""}
${input.resolution ? `Resolution: ${input.resolution}` : ""}
${input.fps ? `FPS: ${input.fps}` : ""}
${input.sceneDescription ? `Scene Description: ${input.sceneDescription}` : ""}
${input.negativePrompt ? `Avoid: ${input.negativePrompt}` : ""}
Mode: ${input.mode}
Input Language: ${lang}

${input.mode === "advanced" ? "Include detailed technical parameters, multi-shot breakdown, and director's notes." : "Keep prompts accessible but visually compelling."}`;
  }

  transformOutput(rawOutput: string, input: SeedanceInput): 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: SeedanceInput): string {
    const parts = [
      input.subject,
      input.style && `${input.style} style`,
      input.mood && `${input.mood} mood`,
      input.cameraMotion && `${input.cameraMotion.replace(/_/g, " ")} camera`,
      input.cameraAngle && `${input.cameraAngle.replace(/_/g, " ")} angle`,
      input.lighting && `${input.lighting} lighting`,
      input.colorGrading && `${input.colorGrading.replace(/_/g, " ")} color grade`,
      input.duration && `${input.duration} duration`,
      input.resolution && `${input.resolution}`,
      input.fps && `${input.fps}fps`,
      "cinematic quality, professional videography",
    ].filter(Boolean);
    return parts.join(", ");
  }

  generateJsonOutput(input: SeedanceInput): Record<string, unknown> {
    return {
      platform: "seedance",
      subject: input.subject,
      style: input.style ?? "cinematic",
      mood: input.mood ?? "neutral",
      cameraMotion: input.cameraMotion ?? "static",
      cameraAngle: input.cameraAngle ?? "eye_level",
      lighting: input.lighting ?? "natural",
      colorGrading: input.colorGrading ?? "cinematic",
      duration: input.duration ?? "5s",
      resolution: input.resolution ?? "1080p",
      fps: input.fps ?? "24",
      negativePrompt: this.buildNegativePrompt(input),
    };
  }

  protected override getDefaultNegativePrompts(): string[] {
    return [
      "low quality",
      "blurry footage",
      "shaky unstabilized camera",
      "overexposed",
      "underexposed",
      "compression artifacts",
      "lens flare",
      "out of focus",
      "jumpcut",
      "watermark",
    ];
  }
}
