/**
 * Autonomous B2B content strategist — category rotation, educational framing,
 * published-content deduplication, and platform metadata.
 */

import type { GeneratedPost } from "@/types/workflow";
import type { WebsiteIntelligence } from "@/lib/context/website-intelligence";
import type { StoryAct } from "@/lib/context/context-library";

/** Rotating content categories for campaign diversity. */
export const CONTENT_CATEGORIES = [
  "storytelling",
  "industry_insights",
  "product_education",
  "customer_pain_points",
  "automation",
  "security",
  "productivity",
  "compliance",
  "case_study",
  "thought_leadership",
] as const;

export type ContentCategoryId = (typeof CONTENT_CATEGORIES)[number];

const CATEGORY_LABELS: Record<ContentCategoryId, string> = {
  storytelling: "Storytelling",
  industry_insights: "Industry Insights",
  product_education: "Product Education",
  customer_pain_points: "Customer Pain Points",
  automation: "Automation",
  security: "Security",
  productivity: "Productivity",
  compliance: "Compliance",
  case_study: "Case Study",
  thought_leadership: "Thought Leadership",
};

const ACT_CATEGORY_MAP: Record<StoryAct, ContentCategoryId> = {
  challenge: "customer_pain_points",
  recognition: "industry_insights",
  solution: "product_education",
  proof: "case_study",
  path_forward: "thought_leadership",
};

/** Secondary category rotation so posts feel distinct even within the same act. */
const BEAT_SECONDARY: ContentCategoryId[] = [
  "storytelling",
  "automation",
  "security",
  "productivity",
  "compliance",
];

export function contentCategoryLabel(id: ContentCategoryId): string {
  return CATEGORY_LABELS[id];
}

/** Primary + secondary category for a sequence beat. */
export function resolveContentCategoryForBeat(
  beatIndex: number,
  act: StoryAct,
): { primary: ContentCategoryId; secondary: ContentCategoryId; label: string } {
  const primary = ACT_CATEGORY_MAP[act];
  const secondary = BEAT_SECONDARY[beatIndex % BEAT_SECONDARY.length] ?? "storytelling";
  const label =
    primary === secondary
      ? contentCategoryLabel(primary)
      : `${contentCategoryLabel(primary)} + ${contentCategoryLabel(secondary)}`;
  return { primary, secondary, label };
}

export function formatContentCategoryGuide(input: {
  primary: ContentCategoryId;
  secondary: ContentCategoryId;
}): string {
  const guides: Record<ContentCategoryId, string> = {
    storytelling:
      "Lead with a relatable business scenario or timeless narrative adapted to today's market — educate first, sell never in the opening.",
    industry_insights:
      "Share a sharp observation about market shifts, buyer habits, or regulations — position the brand as an informed peer, not a vendor pitch.",
    product_education:
      "Explain how a capability works and why it matters operationally — teach the reader something useful; mention the solution naturally at the end.",
    customer_pain_points:
      "Name a specific friction decision-makers feel daily — validate the struggle before offering direction.",
    automation:
      "Focus on workflow efficiency, reduced manual work, and quiet backend reliability — concrete before/after ops picture.",
    security:
      "Emphasize trust, data protection, audit trails, and risk reduction — no fear-mongering; practical safeguards.",
    productivity:
      "Highlight time saved, faster handoffs, and teams doing more with less noise — measurable ops language.",
    compliance:
      "Regulatory reality, documentation discipline, and audit readiness — speak to healthcare, legal, finance where relevant.",
    case_study:
      "Walk through a plausible workflow outcome (hypothetical if no named client) — problem → change → result; avoid unsupported ROI claims.",
    thought_leadership:
      "Offer a forward-looking perspective on where the industry is heading — invite debate; end with an open question.",
  };

  return [
    `Primary angle: ${guides[input.primary]}`,
    input.primary !== input.secondary
      ? `Secondary lens: ${guides[input.secondary]}`
      : "",
  ]
    .filter(Boolean)
    .join("\n");
}

/** SEO keywords inferred from website + brand — cautious, no invented metrics. */
export function deriveSeoKeywords(input: {
  website?: WebsiteIntelligence | null;
  companyName: string;
  industry: string;
  offering: string;
}): string[] {
  const keywords = new Set<string>();

  const add = (raw: string | undefined | null) => {
    const k = raw?.trim().toLowerCase();
    if (!k || k.length < 3 || k.length > 40) return;
    if (/revolutioniz|best ever|game.?chang/i.test(k)) return;
    keywords.add(k);
  };

  add(input.offering);
  add(input.industry);
  add(input.companyName);

  for (const k of input.website?.keywords ?? []) add(k);
  for (const s of input.website?.services ?? []) {
    add(s.label);
  }
  if (input.website?.primaryService) add(input.website.primaryService);

  const verticalTags: Record<string, string[]> = {
    fax: ["secure document exchange", "b2b communication", "compliance documents"],
    email: ["email deliverability", "b2b outreach", "marketing automation"],
    sms: ["sms marketing", "text messaging compliance", "customer engagement"],
  };
  const v = input.website?.vertical;
  if (v && verticalTags[v]) {
    for (const t of verticalTags[v]!) add(t);
  }

  return [...keywords].slice(0, 8);
}

export function formatSeoKeywordsLine(keywords: string[]): string {
  return keywords.length ? keywords.join(", ") : "";
}

/** Summarize prior published/draft posts so AI avoids duplicate hooks and angles. */
export function buildPublishedContentAvoidanceBlock(
  posts: GeneratedPost[],
  excludePostId?: string,
): string {
  const relevant = posts
    .filter((p) => p.id !== excludePostId)
    .filter(
      (p) =>
        p.status === "published" ||
        Boolean(p.platformPermalinks && Object.keys(p.platformPermalinks).length > 0) ||
        p.status === "approved",
    )
    .slice(0, 12);

  if (!relevant.length) {
    return "No prior published posts for this project — create a fresh hook and structure.";
  }

  const lines = relevant.map((p) => {
    const hook = p.caption
      .replace(/#\w+/g, "")
      .split(/\n/)
      .map((l) => l.trim())
      .find((l) => l.length > 25)
      ?.slice(0, 100);
    const layout = p.bannerLayoutId ? ` layout:${p.bannerLayoutId}` : "";
    return `- Post ${p.sequenceIndex ?? "?"} "${p.title ?? "Untitled"}": ${hook ?? p.caption.slice(0, 80)}…${layout}`;
  });

  return [
    "AVOID DUPLICATING these prior posts — use a different hook, structure, opening line, CTA, and visual perspective:",
    ...lines,
  ].join("\n");
}

/**
 * Core strategy layer shared by caption, banner, image, video, SEO, and
 * publishing stages. Each downstream generator returns only its own asset;
 * this directive keeps every asset anchored to one product understanding.
 */
export function buildContentStrategistSystemDirective(input: {
  companyName: string;
  industry: string;
  brandVoice: string;
  platforms: string[];
  targetMarkets?: string;
  tagline?: string;
}): string {
  const company = input.companyName.trim() || "the active project";
  const industry = input.industry.trim() || "B2B";
  const voice = input.brandVoice.trim() || "Professional";
  const platforms = input.platforms.join(", ");
  const markets = input.targetMarkets?.trim() || "US, UK, India enterprise markets";

  return [
    "You are a Senior Product Marketing Manager, Brand Strategist, UX Copywriter, LinkedIn/Facebook/YouTube Content Writer, and Creative Director.",
    `You operate on behalf of ${company}.`,
    "Begin from the website scrape, brand profile, active product configuration, services, documentation, target markets, and prior-post avoidance block.",
    "",
    "MANDATORY PRODUCT UNDERSTANDING (reason through this before creating any asset):",
    "1. Active product — what it is and how it works.",
    "2. Industry — use the product's actual market, not a keyword-adjacent industry.",
    "3. Target audience — buyer, user, influencer, and their operating context.",
    "4. Current market situation — changes in behavior, channels, regulation, or expectations supported by context.",
    "5. Customer pain points — specific operational and emotional friction.",
    "6. Competitor challenge — describe limitations of common alternatives; never invent or attack named competitors.",
    "7. Business goal — the outcome this campaign should influence.",
    "8. Customer transformation — credible before → after change created by the product.",
    "9. Brand position — why this brand is a relevant guide or solution.",
    "10. Call-to-action — one appropriate next step for this story beat.",
    "If context does not support a claim, omit it or qualify it. Never fabricate customers, metrics, awards, integrations, or competitor facts.",
    "",
    "MANDATORY CUSTOMER-JOURNEY NARRATIVE:",
    "1. What challenge exists today?",
    "2. Why does it matter to this audience and business?",
    "3. How does the active product solve it in practical terms?",
    "4. What credible before → after transformation does the customer experience?",
    "5. Why should customers trust this solution? Use only supplied capabilities, process transparency, proof, or verified facts.",
    "6. What single action should they take next?",
    "Use this as the reasoning spine, not as six repetitive headings. Adapt the emphasis to the current story beat.",
    "",
    "CAMPAIGN ASSET CONTRACT:",
    "- Marketing story: one coherent Problem → Insight → Product role → Transformation narrative.",
    "- LinkedIn/Facebook copy: expert, readable, discussion-oriented, and useful before promotional.",
    "- YouTube copy/video: searchable educational hook, clear progression, concise close.",
    "- Website hero: product-specific outcome headline + supporting value proposition (used by product/banner context).",
    "- Social caption: platform-safe core message with a concrete scenario.",
    "- Banner: unique short headline, short support line, relevant feature highlights, and one CTA.",
    "- Image concept/prompt: the same customer story visualized in the correct industry; no keyword-adjacent imagery.",
    "- Design direction: visual hierarchy, brand colors/color psychology, and product-relevant icons.",
    "- Discoverability: grounded SEO keywords and 4–6 relevant hashtags.",
    "Each pipeline stage must output only the asset it owns; do not dump this internal analysis into the public caption.",
    "",
    "CONTENT PHILOSOPHY:",
    "- Generate original, educational, and engaging content that solves real customer problems.",
    "- Every public sentence must relate directly to the active product, its audience, its problem, or its credible transformation.",
    "- Every paragraph, headline, image concept, and CTA must connect to the project's customer journey and business value.",
    "- Quantify transformation only when the website/project supplies a real metric; otherwise describe an observable operational outcome without numbers.",
    "- Do NOT open with direct advertising or slogan dumps — earn attention with insight first.",
    "- Where appropriate, transform relatable business scenarios (or timeless narrative patterns) into modern B2B stories that naturally show how solutions address practical challenges.",
    "- When information is unavailable, infer cautiously from the website and avoid unsupported claims, fake metrics, or named clients unless provided.",
    "",
    "CATEGORY ROTATION:",
    `Rotate through diverse angles: ${CONTENT_CATEGORIES.map((c) => contentCategoryLabel(c)).join(", ")}.`,
    "Follow the Content category block in the user prompt for this post's primary angle.",
    "",
    "UNIQUENESS (mandatory):",
    "- Every post must differ in structure, hook, messaging, CTA, and perspective from prior published content listed in the user prompt.",
    "- Never duplicate hooks, opening lines, or scenario setups from the avoidance list.",
    "- Vary sentence rhythm and paragraph shape — not the same template every beat.",
    "",
    "PLATFORM OUTPUT:",
    `Write for ${platforms}. Adapt tone per channel while keeping one core insight.`,
    "LinkedIn: expert narrative, scannable paragraphs, decision-maker insight, discussion question.",
    "Facebook: relatable business story, accessible language, community-friendly close.",
    "YouTube: searchable educational framing, clear promise, and direct next step.",
    "Include 4–6 relevant hashtags and weave 2–3 SEO keywords naturally (from SEO focus block when provided).",
    "",
    `Brand: ${company}. Industry: ${industry}. Voice: ${voice}. Markets: ${markets}.`,
    input.tagline && !/revolutioniz|best ever|game.?chang/i.test(input.tagline)
      ? `Tagline (use once max if concrete): ${input.tagline.trim()}`
      : "",
    "",
    "OBJECTIVE: Build trust, educate the audience, strengthen brand authority, and produce publish-ready quality for automated social broadcasting.",
  ]
    .filter(Boolean)
    .join("\n");
}

/** Publishing metadata block appended to generation context (logging / future API). */
export function buildPublishingMetadataBlock(input: {
  contentCategory: string;
  seoKeywords: string[];
  platforms: string[];
  sequenceIndex: number;
  beatTitle: string;
}): string {
  return [
    "## Publishing metadata",
    `Content category: ${input.contentCategory}`,
    `Sequence: Post ${input.sequenceIndex} — ${input.beatTitle}`,
    `SEO keywords: ${formatSeoKeywordsLine(input.seoKeywords)}`,
    `Target platforms: ${input.platforms.join(", ")}`,
    "Intent: educate → engage → soft authority (not hard sell)",
  ].join("\n");
}
