import type { BrandProfile, PostSequenceItem, Project } from "@/types/workflow";
import type { StoryContextSections } from "@/lib/generation/social-image";

export interface DynamicVideoPromptInput {
  brand: BrandProfile;
  project: Project;
  sequenceItem: PostSequenceItem;
  caption: string;
  storySections?: StoryContextSections;
  marketingContext?: string;
  websiteAnalysis?: string;
  durationSeconds?: number;
}

function hookFromCaption(caption: string): string {
  const bold = caption.match(/\*\*([^*]+)\*\*/);
  if (bold?.[1]) return bold[1].trim();
  return (
    caption
      .split("\n")
      .find((l) => l.trim().length > 20)
      ?.trim()
      .slice(0, 80) ?? caption.slice(0, 80)
  );
}

function extractHashtags(caption: string): string {
  return caption.match(/#\w+/g)?.join(" ") ?? "";
}

/** Suggest visual personality from brand/industry string only when provided — never invent category. */
function industryStyleHints(industry: string): string {
  const norm = industry.toLowerCase().trim();
  if (!norm) return "Match automatically from website, brand voice, and marketing content";
  if (/restaurant|food|cafe|hospitality/.test(norm)) return "Warm, appetizing, friendly, lifestyle";
  if (/healthcare|medical|clinic|hospital/.test(norm)) return "Clean, trustworthy, caring, professional";
  if (/retail|ecommerce|e-commerce|shop/.test(norm)) return "Vibrant, product-focused, customer-centric";
  if (/manufacturing|industrial|factory/.test(norm)) return "Industrial, robust, precision, operational";
  if (/finance|bank|insurance/.test(norm)) return "Secure, premium, confident, corporate";
  if (/education|school|university|learning/.test(norm)) return "Inspiring, clear, approachable, educational";
  if (/real estate|property|realtor/.test(norm)) return "Aspirational, spacious, lifestyle, premium";
  if (/fashion|beauty|salon/.test(norm)) return "Stylish, elegant, visual, emotional";
  if (/travel|tourism|hotel/.test(norm)) return "Cinematic, adventurous, immersive, scenic";
  if (/software|saas|tech|technology|it\b|fax|sms|email|communications/.test(norm)) {
    return "Modern, innovative, clean, professional";
  }
  return `Match visual style to "${industry}" using website and brand voice — do not invent unrelated categories`;
}

/**
 * Generic dynamic video system prompt — reusable for any industry.
 * Pipeline: Brand Profile → Website → Marketing Context → Post → Video Prompt
 */
export function buildDynamicVideoPrompt(input: DynamicVideoPromptInput): string {
  const company = input.brand.companyName || input.project.name;
  const industry = input.brand.industry || input.project.industry || "General business";
  const website = input.project.website?.trim() || "";
  const countries = input.project.countries?.length
    ? input.project.countries.join(", ")
    : "Not specified";
  const problem = input.storySections?.problem?.slice(0, 500) ?? "";
  const impact = input.storySections?.impact?.slice(0, 500) ?? "";
  const hashtags = extractHashtags(input.caption);
  const hook = hookFromCaption(input.caption);
  const duration = input.durationSeconds ?? 25;
  const beatTitle =
    input.sequenceItem.title?.replace(/^Post \d+ — /, "") ?? "Campaign story";
  const hasLogo = Boolean(input.brand.logoDataUrl?.trim());
  const styleHints = industryStyleHints(industry);

  const marketingContext =
    input.marketingContext?.trim() ||
    [
      problem ? `Problem:\n${problem}` : "",
      impact ? `Impact:\n${impact}` : "",
      hashtags ? `Keywords:\n${hashtags}` : "",
    ]
      .filter(Boolean)
      .join("\n\n");

  const websiteBlock = website
    ? `Website URL: ${website}\nAnalyze this company's website to understand products, services, audience, and visual identity before choosing scenes.`
    : "Website: Not provided — infer business type from brand profile, industry, and marketing content only.";

  const websiteAnalysisBlock = input.websiteAnalysis?.trim()
    ? `\n## Website Analysis\n${input.websiteAnalysis.trim().slice(0, 2000)}`
    : "";

  return [
    "# AI System Prompt – Dynamic Short Video Generator",
    "",
    "You are a Senior Product Marketing Manager, Brand Strategist, UX Copywriter, YouTube/LinkedIn/Facebook Content Writer, Creative Director, Storyboard Artist, and Motion Graphics Designer.",
    "",
    "Your task is to generate a professional, educational short-form video using Brand Profile, scraped Website Context, Marketing Content, and Project Information.",
    "Educate and build trust first — show practical workflow insight, not a hard-sell ad. Keep scenes punchy and visually distinct from prior posts.",
    "",
    "The video should feel like a professional creative agency ad optimized for social engagement.",
    "",
    "## Objective",
    "",
    `Create a ${duration}-second short-form video suitable for:`,
    "- YouTube Shorts",
    "- Instagram Reels",
    "- Facebook Reels",
    "- LinkedIn Video",
    "- TikTok",
    "",
    "The video should quickly capture attention, communicate the message clearly, and encourage viewers to take action.",
    "",
    "---",
    "",
    "## Inputs Provided",
    "",
    "### Brand Profile",
    `Company Name: ${company}`,
    `Industry: ${industry}`,
    `Tagline: ${input.brand.tagline?.trim() || "Not provided"}`,
    `Brand Voice: ${input.brand.brandVoice?.trim() || "Professional"}`,
    `Timezone: ${input.project.timezone || "UTC"}`,
    `Target Countries: ${countries}`,
    `Company Logo: ${hasLogo ? "Provided — use in branding scenes and CTA" : "Not provided — align visuals with brand personality without inventing a logo"}`,
    "",
    "### Project Information",
    websiteBlock,
    `Project Name: ${input.project.name}`,
    `Project Status: ${input.project.status}`,
    websiteAnalysisBlock,
    "",
    "### AI-Generated Marketing Content",
    `Story beat: ${beatTitle}`,
    `Suggested hook: ${hook}`,
    "",
    input.caption.slice(0, 2500),
    "",
    "### Marketing Context",
    marketingContext || "(Use Problem and Impact from post content above.)",
    "",
    "---",
    "",
    "## Business Understanding (do this first)",
    "",
    "Before generating the storyboard:",
    "- Analyze the website and project information.",
    "- Identify the exact active product and how it works.",
    "- Identify its industry and target audience (buyer and user).",
    "- Determine the current market situation and specific customer pain.",
    "- Identify limitations of common alternatives without inventing named competitor claims.",
    "- Define the business goal and credible customer transformation.",
    "- Establish the brand position and one appropriate call-to-action.",
    "- Understand the brand's tone of voice and visual identity.",
    `- Match the video's visual style to the company's industry and audience.`,
    "",
    "**Do not assume every company is a software or technology business.**",
    "",
    "Generate visuals that naturally fit the company's products, services, and industry.",
    "",
    `Industry style hints (choose automatically): ${styleHints}`,
    "",
    "---",
    "",
    "## Video Style",
    "",
    "Create a modern, professional, high-quality social media advertisement.",
    "",
    "The visual style should match the brand's personality — for example: Corporate, Luxury, Premium, Friendly, Healthcare, Technology, Industrial, Educational, Fashion, Restaurant, Travel, Finance.",
    "",
    "**Choose the style automatically based on the company information. Do not default to SaaS dashboards, glassmorphism, or enterprise UI unless the brand is actually a software company.**",
    "",
    "---",
    "",
    "## Scene Generation",
    "",
    "Generate **8–12 unique scenes**.",
    "",
    "Each scene must represent a different moment in the story.",
    "- Do not repeat the same background or visual.",
    "- Do not create a slideshow.",
    "- Do not simply animate a single image.",
    "- Generate fresh visuals for every scene using the business context.",
    "",
    "---",
    "",
    "## Storytelling Structure",
    "",
    "Build the story using this flow whenever appropriate:",
    "1. Attention-grabbing hook",
    "2. The challenge that exists today",
    "3. Why it matters to the audience and business",
    "4. How the active product solves it",
    "5. The credible customer transformation",
    "6. Why customers should trust the solution (verified facts/process only)",
    "7. One strong next action",
    "",
    "Adapt this flow naturally if another structure better fits the content.",
    "Use metrics only when verified in the supplied website/project context; never invent measurable results.",
    "",
    "---",
    "",
    "## Scene Details (required for every scene)",
    "",
    "For every scene provide:",
    "- Scene Number",
    "- Duration",
    "- Visual Description",
    "- Camera Direction",
    "- Motion Description",
    "- On-screen Text (max 6–8 words) — promotional, not paragraphs",
    "- Voiceover (1–2 short sentences max)",
    "- Transition",
    "- Recommended Sound Effect",
    "",
    "Prefer 5 clear branded scenes over 10+ cluttered ones when duration ≤ 30s.",
    "",
    "Every visual must be derived from the provided context. Use:",
    "- Website understanding",
    "- Industry",
    "- Marketing content",
    "- Brand identity",
    "- Company services",
    "- Product information",
    "- Target audience",
    "- Customer transformation",
    "- Brand position",
    "",
    "Do not generate unrelated visuals. Every scene, voiceover sentence, and on-screen phrase must relate directly to the active product.",
    "- Physical products → product-focused scenes",
    "- Services → visualize those services",
    "- B2B → business-focused scenes",
    "- Consumer → customer-focused scenes",
    "",
    "---",
    "",
    "## Motion",
    "",
    "Every scene must contain movement: character actions, product interactions, environmental movement, interface animations (only if relevant), text animations, camera movement, dynamic transitions.",
    "",
    "**Avoid static scenes.**",
    "",
    "---",
    "",
    "## Branding",
    "",
    hasLogo
      ? "Use the provided company logo in intro/outro and CTA scenes."
      : "No logo provided — do not invent a specific logo mark.",
    "Use brand colors and typography only when inferable from context.",
    "If brand assets are unavailable, generate visuals aligned with brand personality without inventing specific branding.",
    "",
    "---",
    "",
    "## Call to Action",
    "",
    "End with a strong CTA based on provided content only.",
    website ? `- Website: ${website.replace(/^https?:\/\//i, "").replace(/\/$/, "")}` : "",
    "Include phone, email, or QR code **only if present in the marketing content above**.",
    "**Do not invent contact information.**",
    "",
    "---",
    "",
    "## MOST IMPORTANT RULE",
    "",
    "**Do not create an image-to-video animation.**",
    "",
    "Generate a true multi-scene short-form video where **each scene is a newly created visual** derived from the company's website, brand profile, and marketing content.",
    "",
    "The final output must tell a compelling story, with every scene contributing to the narrative while maintaining a consistent visual identity throughout.",
    "",
    "---",
    "",
    "## Output Requirements",
    "",
    "Return a complete production-ready storyboard containing:",
    "- Video title",
    "- Creative concept",
    `- Total duration: ~${duration} seconds`,
    "- Overall visual direction (industry-appropriate, not generic tech)",
    "- Scene-by-scene breakdown (8–12 scenes)",
    "- Visual descriptions",
    "- Camera movements",
    "- Motion guidance",
    "- On-screen text",
    "- Voiceover script",
    "- Music recommendation",
    "- Sound effects",
    "- Transitions",
    "- Final CTA",
    "",
    "## OSS pipeline (optional JSON export for Ollama + FLUX + FFmpeg)",
    "",
    "When machine-readable output is required, also emit a JSON block with:",
    "title, creative_concept, total_duration_seconds, visual_direction, music_style,",
    "scenes[{scene, duration, visual_prompt, voiceover, text, camera, motion, transition, animation, sound_effect}],",
    "cta{text, website?, phone?, email?}.",
    "",
    "Each scene visual_prompt must be unique — 8–12 scenes for ~30s YouTube Short.",
    "",
    "The output must be detailed enough for an AI video platform (Veo, Runway, Kling, Pika, Adobe Firefly Video) to generate a polished professional marketing video with minimal manual editing.",
  ]
    .filter((line) => line !== "")
    .join("\n");
}

/** Compact storyboard summary stored with the post (audit + preview). */
export function buildDynamicVideoStoryboard(
  videoPrompt: string,
  input: {
    brand: BrandProfile;
    sequenceItem: PostSequenceItem;
    storySections?: StoryContextSections;
    durationSeconds?: number;
  },
): string {
  const title = input.sequenceItem.title?.replace(/^Post \d+ — /, "") ?? "Campaign";
  const company = input.brand.companyName || "Brand";
  const industry = input.brand.industry || "General";
  const problem = input.storySections?.problem ?? "";
  const impact = input.storySections?.impact ?? "";
  const duration = input.durationSeconds ?? 25;

  return [
    `# Video Storyboard — ${title}`,
    `Brand: ${company} · Industry: ${industry} · Duration: ~${duration}s · Format: 9:16 vertical`,
    "",
    "Creative direction: Industry-adaptive multi-scene short video (5 branded story screens when FFmpeg pipeline runs).",
    "NOT a single-image slideshow when story slides render successfully.",
    "",
    "Narrative arc:",
    `  1. Hook — ${problem.slice(0, 60) || "attention grabber"}…`,
    `  2. Problem — customer challenge`,
    `  3. Impact — ${impact.slice(0, 60) || "business consequence"}…`,
    "  4. Solution — product/service introduction",
    "  5–10. Benefits & outcomes — unique visuals per scene",
    "  11–12. CTA — logo (if provided), website, action",
    "",
    "--- Full production prompt (send to AI video platform) ---",
    videoPrompt.slice(0, 6000),
  ].join("\n");
}
