/**
 * B2B caption quality review — senior content strategist rubric.
 * Used for post-generation scoring / logging; prompts stay white-label but
 * default market framing matches e-fax / secure document exchange projects.
 */

export interface CaptionQualityScores {
  problemDefinition: number;
  marketShift: number;
  businessImpact: number;
  brandPositioning: number;
  humanQuality: number;
  hashtagRelevance: number;
  overall: number;
}

export interface CaptionQualityReview {
  scores: CaptionQualityScores;
  overallOutOf10: number;
  executiveSummary: string;
  worksWell: string[];
  needsImprovement: string[];
  repetitiveOrWeak: string[];
  suggestedExamples: string[];
  recommendedHashtags: string[];
  pathToNineOrTen: string[];
  formattedReview: string;
}

const WEAK_HASHTAGS = new Set([
  "changing",
  "buyer",
  "market",
  "service",
  "best",
  "next",
  "business",
  "marketing",
  "growth",
  "success",
]);

const STRONG_HASHTAG_HINTS = [
  "efax",
  "b2bcommunication",
  "businesscommunication",
  "compliance",
  "digitaltransformation",
  "healthcare",
  "legaltech",
  "insurance",
  "finance",
];

const SLOGAN_PATTERNS =
  /revolutioniz|game.?chang|cutting.?edge|best ever|market your (service|business)|next.?level|pioneering/i;

const SCENARIO_HINTS =
  /contract|proposal|compliance (document|file|packet)|wrong inbox|unanswered|delayed|handoff|bottleneck|claims?|audit/i;

const IMPACT_HINTS =
  /missed lead|lost (lead|opportunit)|delayed|compliance risk|trust|slower (sales|revenue|cycle)|inefficien|operational/i;

const SHIFT_HINTS =
  /buyer (habit|behavio|expectation)|regulat|compliance|crowd(ed)?|platform|inbox|email|outreach|preference/i;

function clamp10(n: number): number {
  return Math.max(0, Math.min(10, Math.round(n * 10) / 10));
}

function extractHashtags(text: string): string[] {
  return (text.match(/#[A-Za-z0-9_]+/g) ?? []).map((h) => h.slice(1));
}

function countMentions(text: string, brand: string): number {
  if (!brand.trim()) return 0;
  const re = new RegExp(brand.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "gi");
  return (text.match(re) ?? []).length;
}

function phraseRepeatPenalty(text: string): string[] {
  const issues: string[] = [];
  const sentences = text
    .replace(/#\w+/g, "")
    .split(/[.!?]\s+/)
    .map((s) => s.trim().toLowerCase())
    .filter((s) => s.length > 40);

  for (let i = 0; i < sentences.length - 1; i++) {
    const a = sentences[i]!;
    const b = sentences[i + 1]!;
    const shared = ["regulations", "platform", "buyer habits", "compliance requirements"].filter(
      (phrase) => a.includes(phrase) && b.includes(phrase),
    );
    if (shared.length) {
      issues.push(`Repeated driver across consecutive sentences: ${shared.join(", ")}`);
    }
  }
  return issues;
}

/**
 * System prompt for LLM-based senior review (optional second pass).
 * Brand-parameterized so any client can use the same rubric.
 */
export function buildCaptionQualityReviewSystemPrompt(input: {
  companyName: string;
  industry?: string;
  primaryOffer?: string;
}): string {
  const company = input.companyName.trim() || "the brand";
  const offer =
    input.primaryOffer?.trim() ||
    "secure, compliant, and reliable business document communication";
  const industry =
    input.industry?.trim() ||
    "healthcare, legal, insurance, finance, manufacturing, and enterprise operations";

  return [
    `You are a senior B2B content strategist and reviewer working for the ${company} project.`,
    `${company} helps organizations market services and exchange critical business documents through ${offer}.`,
    `Target industries include ${industry}, where document delivery, compliance, and response times affect performance.`,
    "",
    "Review the AI-generated social post honestly. Do not inflate scores.",
    "9–10/10 only when the post is authentic, specific, and valuable to decision-makers.",
    "",
    "Weighted criteria:",
    "1) Problem Definition (20%) — real B2B communication / document-exchange challenge; not generic marketing.",
    "2) Market Shift & Industry Reality (20%) — why older strategies fail (buyer habits, regulations, crowded channels).",
    "3) Business Impact (20%) — measurable cost of inaction (lost opportunities, delayed handoffs, compliance risk, trust).",
    "4) Brand Positioning (15%) — brand as trusted partner / practical solution, not a slogan dump.",
    "5) Human Quality & Writing Style (15%) — expert tone, new idea per paragraph, no buzzwords/repetition.",
    "6) Hashtag Relevance (10%) — prefer #EFax #B2BCommunication #BusinessCommunication #Compliance #DigitalTransformation #Healthcare #LegalTech #Insurance and brand tag; penalize weak generic tags.",
    "",
    "Return exactly this structure:",
    "* Overall score: X/10.",
    "* Executive summary.",
    "* What works well.",
    "* What needs improvement.",
    "* Repetitive or weak sections.",
    "* Suggested industry-specific examples.",
    "* Recommended hashtags.",
    "* What changes are required to reach a 9–10/10 rating.",
    "",
    "Sound like an experienced B2B marketing director responsible for this brand.",
  ].join("\n");
}

/** Fast local review used after caption generation (no extra LLM call). */
export function reviewCaptionQuality(input: {
  caption: string;
  companyName: string;
  industry?: string;
}): CaptionQualityReview {
  const text = input.caption.trim();
  const lower = text.toLowerCase();
  const brand = input.companyName.trim() || "the brand";
  const mentions = countMentions(text, brand);
  const hashtags = extractHashtags(text);
  const weakTags = hashtags.filter((h) => WEAK_HASHTAGS.has(h.toLowerCase()));
  const strongHits = hashtags.filter((h) =>
    STRONG_HASHTAG_HINTS.some((s) => h.toLowerCase().includes(s) || s.includes(h.toLowerCase())),
  );
  const repeats = phraseRepeatPenalty(text);
  const hasSlogan = SLOGAN_PATTERNS.test(text);
  const hasScenario = SCENARIO_HINTS.test(text);
  const hasImpact = IMPACT_HINTS.test(text);
  const hasShift = SHIFT_HINTS.test(text);
  const hasIndustry =
    /healthcare|legal|insurance|finance|manufactur|enterprise|hospital|hipaa|claims/i.test(text);

  let problem = 5;
  if (hasShift || /document|efax|e-fax|outreach|communication/i.test(text)) problem += 2;
  if (hasIndustry) problem += 1.5;
  if (hasSlogan) problem -= 2;
  if (repeats.length) problem -= 1.5;

  let market = 5;
  if (hasShift) market += 2.5;
  if (hasScenario) market += 2;
  if (repeats.length) market -= 1;

  let impact = 4.5;
  if (hasImpact) impact += 3;
  if (/doing nothing|cost of|quietly compounds|each quarter/i.test(text)) impact += 1.5;
  if (!hasImpact) impact -= 1;

  let brandScore = 6;
  if (mentions === 1 || mentions === 2) brandScore += 2;
  if (mentions >= 4) brandScore -= 2.5;
  if (mentions === 0) brandScore -= 1.5;
  if (/secure|compliant|reliab|document delivery|audit|business continuity/i.test(text)) {
    brandScore += 1.5;
  }
  if (hasSlogan) brandScore -= 2.5;

  let human = 6.5;
  if (hasScenario) human += 1.5;
  if (hasSlogan) human -= 2;
  if (repeats.length) human -= 1.5;
  const endsWithQuestion = /\?\s*(?:\n\n|\n#|$)/.test(text) || text.trim().endsWith("?");
  if ((text.match(/\?/g) ?? []).length >= 1) human += 0.5;
  if (endsWithQuestion) human += 1;
  const words = text.replace(/#\w+/g, "").split(/\s+/).filter(Boolean).length;
  if (words >= 90 && words <= 170) human += 1;
  if (words > 220) human -= 1;

  let hashtagScore = 4;
  if (hashtags.length >= 4 && hashtags.length <= 7) hashtagScore += 2;
  hashtagScore += Math.min(3, strongHits.length * 0.8);
  hashtagScore -= weakTags.length * 1.5;
  if (hashtags.some((h) => h.toLowerCase() === brand.replace(/\s+/g, "").toLowerCase())) {
    hashtagScore += 1;
  }

  const scores: CaptionQualityScores = {
    problemDefinition: clamp10(problem),
    marketShift: clamp10(market),
    businessImpact: clamp10(impact),
    brandPositioning: clamp10(brandScore),
    humanQuality: clamp10(human),
    hashtagRelevance: clamp10(hashtagScore),
    overall: 0,
  };

  const overall =
    scores.problemDefinition * 0.2 +
    scores.marketShift * 0.2 +
    scores.businessImpact * 0.2 +
    scores.brandPositioning * 0.15 +
    scores.humanQuality * 0.15 +
    scores.hashtagRelevance * 0.1;
  scores.overall = clamp10(overall);

  const worksWell: string[] = [];
  if (scores.problemDefinition >= 7) worksWell.push("Problem is relevant to B2B communication / document exchange.");
  if (scores.marketShift >= 7) worksWell.push("Market shift / industry reality is explained clearly.");
  if (scores.businessImpact >= 7) worksWell.push("Business impact feels tangible (cost of inaction).");
  if (scores.brandPositioning >= 7) {
    worksWell.push(`${brand} is positioned as a practical communication partner, not a slogan.`);
  }
  if (scores.humanQuality >= 7) worksWell.push("Tone reads closer to expert commentary than generic AI copy.");
  if (!worksWell.length) worksWell.push("Structure is present, but insight depth needs more work.");

  const needsImprovement: string[] = [];
  if (scores.problemDefinition < 8) {
    needsImprovement.push("Sharpen the problem for document-reliant industries; cut generic marketing phrasing.");
  }
  if (!hasScenario) {
    needsImprovement.push(
      "Add a concrete scenario (e.g. unanswered contract approval or compliance document in the wrong inbox).",
    );
  }
  if (!endsWithQuestion) {
    needsImprovement.push("End with an open engagement question to invite comments and discussion.");
  }
  if (hasSlogan) needsImprovement.push("Replace slogan language with concrete capabilities (secure delivery, compliance, reliability).");
  if (!hasIndustry) {
    needsImprovement.push("Name specific industries (healthcare, legal, insurance, finance, manufacturing).");
  }
  if (repeats.length) needsImprovement.push(...repeats);
  if (weakTags.length) needsImprovement.push(`Replace weak hashtags: ${weakTags.map((t) => `#${t}`).join(", ")}`);

  const recommendedHashtags = [
    "#EFax",
    "#B2BCommunication",
    "#BusinessCommunication",
    "#Compliance",
    "#DigitalTransformation",
    `#${brand.replace(/\s+/g, "")}`,
  ];

  const suggestedExamples = [
    "When a contract approval sits unanswered or a compliance document reaches the wrong inbox, communication delays quickly become operational risks.",
    "In healthcare or legal ops, a missed handoff can stall care authorizations or case filing timelines within a single business day.",
    "Insurance and finance teams feel the cost as slower claims packets, delayed underwriting files, and rising compliance exposure.",
  ];

  const pathToNineOrTen = [
    "Keep one sharp problem statement — no consecutive restating of regulations/platform rules.",
    "Include one recognisable operational scenario decision-makers have lived.",
    "State concrete consequences (lost opportunities, delayed handoffs, compliance risk).",
    `Introduce ${brand} once with secure/compliant/reliable document exchange value — never slogans.`,
    "Use curated industry hashtags only.",
  ];

  const overallOutOf10 = scores.overall;
  const executiveSummary =
    overallOutOf10 >= 9
      ? `Strong, decision-maker-ready post for ${brand}. Specific, impactful, and appropriately branded.`
      : overallOutOf10 >= 7.5
        ? `Solid professional post for ${brand}, but it still needs sharper specificity and less generic/slogan language to clear 9/10.`
        : `Below target for ${brand}. Strengthen problem clarity, concrete scenarios, measurable impact, and brand positioning.`;

  const formattedReview = [
    `* Overall score: ${overallOutOf10}/10.`,
    `* Executive summary: ${executiveSummary}`,
    `* What works well: ${worksWell.join(" ")}`,
    `* What needs improvement: ${needsImprovement.join(" ") || "None major."}`,
    `* Repetitive or weak sections: ${repeats.length ? repeats.join(" ") : hasSlogan ? "Slogan-heavy phrasing weakens brand value." : "No major repetitive blocks detected."}`,
    `* Suggested industry-specific examples: ${suggestedExamples[0]}`,
    `* Recommended hashtags: ${recommendedHashtags.join(" ")}`,
    `* What changes are required to reach a 9–10/10 rating: ${pathToNineOrTen.join(" ")}`,
    "",
    `Criteria — Problem ${scores.problemDefinition}/10 · Market ${scores.marketShift}/10 · Impact ${scores.businessImpact}/10 · Brand ${scores.brandPositioning}/10 · Human ${scores.humanQuality}/10 · Hashtags ${scores.hashtagRelevance}/10`,
  ].join("\n");

  return {
    scores,
    overallOutOf10,
    executiveSummary,
    worksWell,
    needsImprovement,
    repetitiveOrWeak: repeats,
    suggestedExamples,
    recommendedHashtags,
    pathToNineOrTen,
    formattedReview,
  };
}

/** Map quality /10 → engagement-style 0–100 for GeneratedPost.engagementScore. */
export function qualityScoreToEngagement(overallOutOf10: number): number {
  return Math.max(0, Math.min(98, Math.round(overallOutOf10 * 10)));
}
