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

export class TikTokUGCPromptAdapter extends BasePromptAdapter<TikTokUGCInput> {
  platform = "tiktok_ugc" as const;

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

  constructSystemPrompt(input: TikTokUGCInput, variationCount: number): string {
    return `You are a viral TikTok content strategist and UGC script writer. Create ${variationCount} high-converting UGC TikTok script(s) and video direction prompt(s).

UGC Best Practices:
- Hook must capture attention in first 3 seconds
- Authentic, relatable tone - not polished/corporate
- Clear problem → solution → CTA structure
- Use TikTok native language and trends
- Include B-roll and action directions

Output format (strict JSON):
{
  "variations": [
    {
      "index": 0,
      "textPrompt": "video direction/setup prompt",
      "negativePrompt": "avoid these mistakes",
      "jsonOutput": {
        "product": "...",
        "targetAudience": "...",
        "hook": "...",
        "problemStatement": "...",
        "solution": "...",
        "socialProof": "...",
        "cta": "...",
        "hashtags": ["..."],
        "duration": "...",
        "persona": "..."
      },
      "script": "Full TikTok script with timing and directions",
      "shotList": [
        {
          "shotNumber": 1,
          "shotType": "close-up",
          "cameraAngle": "eye level",
          "cameraMovement": "static",
          "subject": "...",
          "action": "...",
          "duration": "3s",
          "notes": "Hook delivery - look straight into camera"
        }
      ]
    }
  ]
}`;
  }

  // Fix #2: variationIndex dihapus — tidak dipakai, satu call untuk semua variasi
  constructUserPrompt(input: TikTokUGCInput): string {
    const lang = input.language === "id" ? "Bahasa Indonesia" : "English";
    return `Create ${input.variations} TikTok UGC script(s) in ${lang}:

Product/Topic: ${input.subject}
${input.productName ? `Product Name: ${input.productName}` : ""}
${input.targetAudience ? `Target Audience: ${input.targetAudience}` : ""}
${input.ugcPersona ? `UGC Persona: ${input.ugcPersona.replace(/_/g, " ")}` : ""}
${input.hookType ? `Hook Style: ${input.hookType}` : ""}
${input.painPoint ? `Pain Point: ${input.painPoint}` : ""}
${input.benefit ? `Key Benefit: ${input.benefit}` : ""}
${input.ctaType ? `CTA: ${input.ctaType.replace(/_/g, " ")}` : ""}
${input.videoDuration ? `Video Duration: ${input.videoDuration}` : ""}
${input.trendReference ? `Trend Reference: ${input.trendReference}` : ""}
${input.mood ? `Tone/Energy: ${input.mood}` : ""}

${input.mode === "advanced" ? "Include detailed timing notes, camera directions, B-roll suggestions, and hashtag strategy." : "Keep it natural and authentic."}`;
  }

  transformOutput(rawOutput: string, input: TikTokUGCInput): 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),
      script: rawOutput,
    };
  }

  generateTextPrompt(input: TikTokUGCInput): string {
    return [
      `UGC TikTok for ${input.productName ?? input.subject}`,
      input.ugcPersona && `persona: ${input.ugcPersona.replace(/_/g, " ")}`,
      input.hookType && `${input.hookType} hook`,
      input.videoDuration && `${input.videoDuration} video`,
      input.targetAudience && `targeting ${input.targetAudience}`,
      "authentic UGC style",
      "mobile-first vertical format",
    ].filter(Boolean).join(", ");
  }

  generateJsonOutput(input: TikTokUGCInput): Record<string, unknown> {
    return {
      platform: "tiktok_ugc",
      product: input.productName ?? input.subject,
      targetAudience: input.targetAudience ?? "general",
      hookType: input.hookType ?? "benefit",
      ugcPersona: input.ugcPersona ?? "everyday_user",
      painPoint: input.painPoint,
      benefit: input.benefit,
      ctaType: input.ctaType ?? "link_in_bio",
      videoDuration: input.videoDuration ?? "30s",
      hashtags: ["#ugc", "#ad", "#tiktokshop"],
      negativePrompt: this.buildNegativePrompt(input),
    };
  }

  protected override getDefaultNegativePrompts(): string[] {
    return [
      "overly polished/corporate tone",
      "hard sell language",
      "fake testimonials",
      "misleading claims",
      "low energy delivery",
      "talking to camera without engagement",
      "no clear hook",
    ];
  }
}
