/**
 * Detect off-brand / hallucinated content in captions and context text.
 */

export interface ContentRelevanceResult {
  valid: boolean;
  criticalIssues: string[];
  warnings: string[];
}

const FORBIDDEN_COMPANY_NAMES = [
  "acme corp",
  "acme corporation",
  "acme inc",
  "example corp",
  "example company",
  "sample corp",
  "demo company",
  "your company",
  "company x",
];

const STALE_PLACEHOLDER_PATTERNS: RegExp[] = [
  /explain the business impact if this problem is ignored/i,
  /how acme corp/i,
  /acme corp clients achieved/i,
  /clients achieved \d+% faster/i,
  /i recently discovered how acme/i,
  /example\.com/i,
];

const METRIC_CLAIM_PATTERN =
  /\b\d{1,3}\s*%\s*(?:faster|reduction|increase|improvement|growth|more|less|higher|lower)\b/i;

const GENERIC_CLIENT_CLAIM =
  /\b(?:our clients?|their clients?|helped (?:their )?clients?|clients achieved)\b/i;

function normalizeCompany(name: string): string {
  return name.trim().toLowerCase().replace(/\s+/g, " ");
}

function findForeignCompanyMentions(text: string, brandCompany: string): string[] {
  const issues: string[] = [];
  const lower = text.toLowerCase();
  const brandNorm = normalizeCompany(brandCompany);
  const brandTokens = brandNorm.split(" ").filter((t) => t.length > 2);

  for (const forbidden of FORBIDDEN_COMPANY_NAMES) {
    if (lower.includes(forbidden)) {
      issues.push(`Contains placeholder company name: "${forbidden}"`);
    }
  }

  const helpedMatch = lower.match(
    /(?:how|why|when)\s+([a-z0-9][a-z0-9\s&.-]{2,40}?)\s+(?:helped|achieved|delivered|enabled)/i,
  );
  if (helpedMatch?.[1]) {
    const subject = helpedMatch[1].trim();
    const subjectNorm = normalizeCompany(subject);
    const isOwnBrand =
      brandNorm.includes(subjectNorm) ||
      subjectNorm.includes(brandNorm) ||
      brandTokens.some((t) => subjectNorm.includes(t));
    if (!isOwnBrand && subject.length > 2 && !subject.includes("teams")) {
      issues.push(`Mentions another company as hero: "${subject.trim()}"`);
    }
  }

  return issues;
}

export function validateContentRelevance(
  text: string,
  companyName: string,
  allowedFacts?: string,
): ContentRelevanceResult {
  const criticalIssues: string[] = [];
  const warnings: string[] = [];
  const trimmed = text.trim();
  if (!trimmed) {
    return { valid: false, criticalIssues: ["Empty content"], warnings: [] };
  }

  const lower = trimmed.toLowerCase();
  const brand = companyName.trim() || "the brand";
  const brandNorm = normalizeCompany(brand);
  const allowedLower = (allowedFacts ?? "").toLowerCase();

  for (const pattern of STALE_PLACEHOLDER_PATTERNS) {
    if (pattern.test(trimmed)) {
      criticalIssues.push(`Stale template placeholder detected`);
    }
  }

  criticalIssues.push(...findForeignCompanyMentions(trimmed, brand));

  const wordCount = trimmed.replace(/#\w+/g, "").split(/\s+/).filter(Boolean).length;
  if (wordCount > 60 && brandNorm.length > 2) {
    const brandMentioned =
      lower.includes(brandNorm) ||
      brandNorm.split(" ").some((t) => t.length > 3 && lower.includes(t));
    if (!brandMentioned) {
      warnings.push(`Caption may not reference ${brand}`);
    }
  }

  const metricMatches = trimmed.match(new RegExp(METRIC_CLAIM_PATTERN.source, "gi")) ?? [];
  for (const metric of metricMatches) {
    if (!allowedLower.includes(metric.toLowerCase())) {
      criticalIssues.push(`Unverified metric claim: "${metric.trim()}"`);
    }
  }

  if (GENERIC_CLIENT_CLAIM.test(trimmed) && !allowedLower.includes("client")) {
    warnings.push("Generic client success claim without supplied proof in context");
  }

  const uniqueCritical = [...new Set(criticalIssues)];
  const uniqueWarnings = [...new Set(warnings)];

  return {
    valid: uniqueCritical.length === 0,
    criticalIssues: uniqueCritical,
    warnings: uniqueWarnings,
  };
}

export function detectStaleSequenceContent(content: string, companyName?: string): string[] {
  const issues: string[] = [];
  const trimmed = content.trim();
  if (!trimmed) return ["Context preview is empty"];

  for (const pattern of STALE_PLACEHOLDER_PATTERNS) {
    if (pattern.test(trimmed)) {
      issues.push("Contains outdated placeholder text — click Regenerate from brand");
    }
  }

  const relevance = validateContentRelevance(trimmed, companyName || "");
  issues.push(...relevance.criticalIssues);

  return [...new Set(issues)];
}

export function buildVideoMarketingContext(input: {
  creativeBrief: string;
  storySections?: { problem?: string; impact?: string; brandResponse?: string };
  caption?: string;
}): string {
  const parts: string[] = [];
  if (input.storySections?.problem?.trim()) {
    parts.push(`Problem: ${input.storySections.problem.trim()}`);
  }
  if (input.storySections?.impact?.trim()) {
    parts.push(`Impact: ${input.storySections.impact.trim()}`);
  }
  if (input.storySections?.brandResponse?.trim()) {
    parts.push(`Brand response: ${input.storySections.brandResponse.trim()}`);
  }
  if (parts.length === 0 && input.creativeBrief.trim()) {
    parts.push(input.creativeBrief.trim().slice(0, 2000));
  } else if (input.creativeBrief.trim()) {
    parts.push(input.creativeBrief.trim().slice(0, 1200));
  }
  if (parts.length === 0 && input.caption?.trim()) {
    parts.push(input.caption.trim().slice(0, 800));
  }
  return parts.join("\n\n");
}
