﻿import { parseStoryContextSections } from "@/lib/context/story-context-builder";
import {
  buildContentStrategistSystemDirective,
  formatContentCategoryGuide,
  type ContentCategoryId,
} from "@/lib/generation/content-strategist";

export interface StoryBrief {
  problem: string;
  impact: string;
  brandResponse: string;
  engagementQuestion: string;
  contentCategory: string;
  seoKeywords: string;
  hashtags: string;
  raw: string;
}

/** Parse compact Problem / Impact / hashtags from posting context preview. */
export function parseCompactStoryBrief(contextBlock: string): StoryBrief {
  const parsed = parseStoryContextSections(contextBlock);

  const hashtagLine =
    contextBlock
      .split("\n")
      .map((l) => l.trim())
      .find((l) => l.startsWith("#")) ?? "";

  return {
    problem: parsed.problem.trim(),
    impact: parsed.impact.trim(),
    brandResponse: parsed.brandResponse.trim(),
    engagementQuestion: parsed.engagementQuestion.trim(),
    contentCategory: parsed.contentCategory.trim(),
    seoKeywords: parsed.seoKeywords.trim(),
    hashtags: hashtagLine,
    raw: contextBlock.trim(),
  };
}

function parseCategoryIds(label: string): {
  primary: ContentCategoryId;
  secondary: ContentCategoryId;
} {
  const normalized = label.toLowerCase();
  const ids: ContentCategoryId[] = [];
  if (/storytelling/.test(normalized)) ids.push("storytelling");
  if (/industry insight/.test(normalized)) ids.push("industry_insights");
  if (/product education/.test(normalized)) ids.push("product_education");
  if (/pain point/.test(normalized)) ids.push("customer_pain_points");
  if (/automation/.test(normalized)) ids.push("automation");
  if (/security/.test(normalized)) ids.push("security");
  if (/productivity/.test(normalized)) ids.push("productivity");
  if (/compliance/.test(normalized)) ids.push("compliance");
  if (/case study/.test(normalized)) ids.push("case_study");
  if (/thought leadership/.test(normalized)) ids.push("thought_leadership");

  return {
    primary: ids[0] ?? "customer_pain_points",
    secondary: ids[1] ?? ids[0] ?? "storytelling",
  };
}

/**
 * Cross-platform B2B post caption (LinkedIn / Facebook / Instagram / YouTube).
 * Autonomous content strategist: educate first, rotate categories, never duplicate prior posts.
 */
export function buildStoryCaptionSystemPrompt(input: {
  companyName: string;
  industry: string;
  brandVoice: string;
  tagline?: string;
  platforms?: string[];
  targetMarkets?: string;
}): string {
  const platforms = input.platforms?.length
    ? input.platforms
    : ["linkedin", "facebook", "instagram", "youtube"];

  const strategist = buildContentStrategistSystemDirective({
    companyName: input.companyName,
    industry: input.industry,
    brandVoice: input.brandVoice,
    platforms,
    targetMarkets: input.targetMarkets,
    tagline: input.tagline,
  });

  return [
    strategist,
    "",
    "Parent brand and ACTIVE PRODUCT are separate — never hardcode e-fax/paper distress when the product is DNC, SMS, dialer, email, call tracking, or CMS.",
    "NCERT STORY LAYER (when applicable): human struggle / clutter / compliance fear → quiet backend stability for the ACTIVE product.",
    "REQUIRED ARC: Hook → Today's challenge → Why it matters → How the active product solves it → Credible customer transformation → Trust reason → One CTA → engagement question → hashtags.",
    "ENGAGEMENT: End with ONE open question (use Engagement question from brief when provided). Encourage shares only when the insight genuinely helps peers.",
    "LENGTH: 100–150 words body. Aim 9+/10 decision-maker quality.",
  ].join("\n");
}

export function buildStoryCaptionUserPrompt(
  brief: StoryBrief,
  input: {
    companyName: string;
    industry: string;
    sequenceTitle?: string;
    tagline?: string;
    publishedAvoidanceBlock?: string;
    contentCategoryGuide?: string;
    targetMarkets?: string;
  },
): string {
  const categories = brief.contentCategory
    ? parseCategoryIds(brief.contentCategory)
    : null;
  const categoryGuide =
    input.contentCategoryGuide ||
    (categories
      ? formatContentCategoryGuide({
          primary: categories.primary,
          secondary: categories.secondary,
        })
      : "");

  const lines = [
    `Write a 9–10/10 educational B2B post for ${input.companyName}.`,
    input.sequenceTitle ? `Sequence beat: ${input.sequenceTitle}` : "",
    input.targetMarkets ? `Target markets: ${input.targetMarkets}` : "",
    "Follow the ACTIVE PRODUCT block when present — never substitute another product category (for example fax, SMS, dialer, CMS, or admissions).",
    "Before writing, identify the product, audience, market situation, pain, common alternative/competitor limitation, business goal, customer transformation, brand position, and CTA from supplied facts.",
    "Lead with insight or scenario — not a product pitch. Include one concrete ops scenario decision-makers recognize.",
    "Show a credible before → after transformation. Discuss common alternatives only when supported; never invent or attack named competitors.",
    "Explain why the audience should trust the solution using verified capabilities, workflow transparency, or supplied proof. Never invent testimonials or metrics.",
    "Every sentence must connect directly to this product, its buyer, its problem, or its transformation. Delete generic marketing sentences.",
    `Name ${input.companyName} once; name the active solution naturally near the close. Ban Revolutionizing… slogans.`,
    "100–150 words. Unique hook and structure — not a repeat of prior posts.",
    "",
    brief.contentCategory ? `## Content category\n${brief.contentCategory}` : "",
    categoryGuide ? `## Category guidance\n${categoryGuide}` : "",
    brief.seoKeywords ? `## SEO focus (weave 2–3 naturally)\n${brief.seoKeywords}` : "",
    "",
    "## Problem",
    brief.problem || "(use creative brief)",
    "",
    "## Impact",
    brief.impact || "(use creative brief)",
    "",
    brief.brandResponse ? `## Brand response\n${brief.brandResponse}` : "",
    "",
    brief.engagementQuestion
      ? `## Engagement question (end the post with this or a close variant)\n${brief.engagementQuestion}`
      : "## Engagement\nEnd with one specific question that invites comments from decision-makers.",
    "",
    brief.hashtags ? `## Preferred hashtags\n${brief.hashtags}` : "",
    "",
    "## Creative brief (rewrite; strip slogans; stay educational)",
    brief.raw.slice(0, 1800),
  ];

  if (input.publishedAvoidanceBlock?.trim()) {
    lines.push("", "## Prior published content (do NOT duplicate)", input.publishedAvoidanceBlock.trim());
  }

  if (input.tagline?.trim() && !/revolutioniz|market your|best ever|game.?chang/i.test(input.tagline)) {
    lines.push("", `Optional clean tagline (once max): ${input.tagline.trim()}`);
  }

  return lines.filter(Boolean).join("\n");
}

/** Image brief — educational visual aligned to story category, not generic ad creative. */
export function buildStoryImageBriefSystemPrompt(input: {
  companyName: string;
  industry: string;
}): string {
  const focus = input.industry.trim() || "the company's real services";
  return [
    "You are a Senior Product Marketing Manager, Brand Strategist, UX Copywriter, and Creative Director creating an educational, trust-building image brief (not a hard-sell ad).",
    `Company: ${input.companyName}. Context industry: ${focus}.`,
    "First establish the exact product, audience, market situation, customer pain, transformation, brand position, and CTA from supplied facts.",
    "Visualize this customer journey: current challenge → business importance → product mechanism → customer transformation → trust signal → next action.",
    "Return ONLY valid JSON: headline, subheadline, visualConcept, keyStat.",
    "headline: 5–12 words UNIQUE to THIS story beat — never reuse one campaign slogan on every post; change with Problem/Impact for this beat.",
    "subheadline: max 14 words — educational hook or friction relief in plain language.",
    "visualConcept: describe the product-specific scene, design direction, visual hierarchy, color psychology, and 3–5 relevant icon motifs in one concise string.",
    "The scene must visualize the same customer problem and transformation as the caption; never choose imagery from a keyword-adjacent industry.",
    "Use a measurable transformation only when a verified metric appears in the supplied context; otherwise show an observable workflow outcome.",
    "Align headline/subhead with the SAME story beat and content category as the caption — not a repeated template layout.",
    "STRICT BAN: physical fax machines, paper distress, frustrated-with-paper stock poses, generic smiling headshots.",
    "Prefer candid professionals reviewing real infrastructure, data, or workflow screens.",
    "keyStat: null unless a real metric appears in the brief — never invent numbers.",
  ].join(" ");
}

export function buildStoryImageBriefUserPrompt(input: {
  companyName: string;
  industry: string;
  sequenceTitle: string;
  problem: string;
  impact: string;
  tagline?: string;
  caption?: string;
  keyTheme?: string;
  brandResponse?: string;
  engagementQuestion?: string;
  contentCategory?: string;
  seoKeywords?: string;
  websiteSummary?: string;
}): string {
  return [
    `Company: ${input.companyName}`,
    `Industry: ${input.industry}`,
    `Story beat: ${input.sequenceTitle}`,
    input.contentCategory ? `Content category: ${input.contentCategory}` : "",
    input.tagline ? `Tagline: ${input.tagline}` : "",
    input.keyTheme ? `Key theme: ${input.keyTheme}` : "",
    input.seoKeywords ? `SEO mood: ${input.seoKeywords}` : "",
    input.engagementQuestion
      ? `Engagement angle (visual mood should support this): ${input.engagementQuestion}`
      : "",
    input.websiteSummary
      ? `\n## Website scrape (accurate services/visuals — use this)\n${input.websiteSummary.slice(0, 1500)}`
      : "",
    "",
    "## Problem",
    input.problem.slice(0, 400),
    "",
    "## Impact",
    input.impact.slice(0, 400),
    input.brandResponse
      ? `\n## Brand response\n${input.brandResponse.slice(0, 400)}`
      : "",
    "",
    input.caption
      ? "## Caption hook (match this educational mood)\n" + input.caption.slice(0, 500)
      : "",
    "",
    "JSON only — unique visualConcept for this category and beat:",
  ]
    .filter(Boolean)
    .join("\n");
}
