import type { BrandProfile, Project } from "@/types/workflow";
import type { WebsiteIntelligence } from "@/lib/context/website-intelligence";

/**
 * Multi-solution catalog — white-label, never hardcode a single product (e.g. e-fax).
 * Detected from scraped services / sequence beat / brand content.
 */
export type SolutionCategory =
  | "fax"
  | "sms"
  | "email"
  | "dnc"
  | "dialer"
  | "call_tracking"
  | "cms"
  | "education_admissions"
  | "generic";

export interface DynamicProductConfiguration {
  solutionCategory: SolutionCategory;
  solutionName: string;
  scrapedFeatures: string[];
  scrapedMetrics: string[];
  primaryValueProp: string;
  humanFrictionHook: string;
  narrativeContrast: string;
  /** Short uppercase headline for creatives — from THIS product, not a static brand slogan. */
  primaryHeadline: string;
  subheadline: string;
  /** Modern infrastructure visual direction (no paper distress / hardware fax). */
  modernVisualDirection: string;
  dashboardCue: string;
  markets: string;
}

function truncate(text: string, max: number): string {
  const t = text.trim();
  if (t.length <= max) return t;
  return `${t.slice(0, max - 1).trim()}…`;
}

function cleanLabel(raw: string): string {
  let t = raw.trim();
  const dash = t.split(/\s[-–—]\s/);
  if (dash.length > 1 && (/market your|revolutioniz|best ever/i.test(t) || t.length > 48)) {
    t = dash[0]!.trim();
  }
  if (/revolutioniz|market your|best ever|next level/i.test(t)) return "";
  return t.slice(0, 64);
}

function haystack(parts: Array<string | undefined | null>): string {
  return parts.filter(Boolean).join(" ").toLowerCase();
}

/** Prefer service language over brand name (e.g. do not force fax just because brand is B2BEFAX). */
export function detectSolutionCategory(input: {
  brand: BrandProfile;
  project: Project;
  website?: WebsiteIntelligence | null;
  sequenceTitle?: string;
  problem?: string;
  brandResponse?: string;
}): SolutionCategory {
  const serviceText = haystack([
    input.sequenceTitle,
    input.website?.primaryService,
    ...(input.website?.services?.map((s) => `${s.label} ${s.detail}`) ?? []),
    ...(input.website?.headings ?? []),
    ...(input.website?.keywords ?? []),
    input.problem,
    input.brandResponse,
  ]);

  const brandText = haystack([
    input.brand.companyName,
    input.brand.tagline,
    input.brand.industry,
    input.project.name,
    input.project.industry,
    input.website?.description,
    input.website?.title,
  ]);

  const combined = `${serviceText} ${brandText}`;

  // Service-first signals (multi-solution portfolio)
  if (/dnc|do.?not.?call|lead.?scrub|deduplicat|data.?clean|list.?scrub|compliance.?scrub/i.test(serviceText)) {
    return "dnc";
  }
  if (/call.?track|dynamic.?number|number.?insert|\bdni\b|attribution.?call/i.test(serviceText)) {
    return "call_tracking";
  }
  if (/dialer|ringpilot|predictive.?dial|power.?dial|auto.?dial|ivr/i.test(serviceText)) {
    return "dialer";
  }
  if (/sms.?broadcast|bulk.?sms|text.?broadcast|\bmms\b/i.test(serviceText)) {
    return "sms";
  }
  if (/email.?broadcast|email.?marketing|bulk.?email|newsletter|inbox.?placement|spf|dkim/i.test(serviceText)) {
    return "email";
  }
  if (
    /admission|enrol(?:l)?ment|student.?recruit|education|university|college|study.?abroad|mbbs|counsell?ing|visa.?guid/i.test(
      serviceText,
    )
  ) {
    return "education_admissions";
  }
  if (/\bcms\b|website.?builder|web.?cms|content.?manage/i.test(serviceText)) {
    return "cms";
  }
  if (/e-?fax|fax.?broadcast|cloud.?fax|\bfax\b/i.test(serviceText)) {
    return "fax";
  }

  // Fallback to brand/site (still avoid locking solely on brand string "b2befax")
  if (/dnc|lead.?scrub|deduplicat/i.test(combined)) return "dnc";
  if (/call.?track|\bdni\b/i.test(combined)) return "call_tracking";
  if (/dialer|ringpilot/i.test(combined)) return "dialer";
  if (/sms.?broadcast|bulk.?sms|\bsms\b/i.test(combined)) return "sms";
  if (/email.?broadcast|bulk.?email|newsletter/i.test(combined)) return "email";
  if (
    /admission|enrol(?:l)?ment|student|education|university|college|study.?abroad|mbbs|counsell?ing/i.test(
      combined,
    )
  ) {
    return "education_admissions";
  }
  if (/e-?fax|fax.?broadcast|\bfax\b/i.test(combined)) return "fax";
  if (/cms|website/i.test(combined)) return "cms";
  return "generic";
}

function catalogDefaults(category: SolutionCategory): Omit<
  DynamicProductConfiguration,
  "scrapedFeatures" | "scrapedMetrics" | "solutionName"
> {
  const markets = "US, UK, and India";
  switch (category) {
    case "dnc":
      return {
        solutionCategory: category,
        primaryValueProp: "Eliminate duplicate outreach and zero compliance-risk anxiety",
        humanFrictionHook: "Chaotic clutter and avoidable arguments over missing or restricted records",
        narrativeContrast:
          "Contrast the hailstorm of unscrubbed, conflicting lead lists with the calm of automated DNC and dedupe guardrails",
        primaryHeadline: "OUTREACH FLOWS FASTER WHEN DATABASE FRICTION IS ELIMINATED",
        subheadline: "Remove lead clutter and avoid compliance anxiety",
        modernVisualDirection:
          "Modern ops workspace with CRM/data dashboard — Duplicates: 0, DNC Scrubber: ACTIVE — soft natural light, calm professionals; NO paper piles, NO physical fax machines, NO distressed paper-handling stock photos",
        dashboardCue: "CRM dashboard showing clean verified records and active scrub status",
        markets,
      };
    case "call_tracking":
      return {
        solutionCategory: category,
        primaryValueProp: "Precise attribution and smarter inbound routing",
        humanFrictionHook: "Lost marketing credit and unanswered call chaos",
        narrativeContrast:
          "Contrast vanity metrics and missed inbound spikes with clear source attribution and controlled routing",
        primaryHeadline: "TRACK EVERY INBOUND CALL. MAXIMIZE MARKETING ROI",
        subheadline: "Dynamic number insertion with real-time call analytics",
        modernVisualDirection:
          "Analysts reviewing a clear call-analytics dashboard with routing metrics; cloud telephony cues only; NO paper fax distress",
        dashboardCue: "Call center analytics with source attribution and connection success",
        markets,
      };
    case "dialer":
      return {
        solutionCategory: category,
        primaryValueProp: "High-volume dialing with controlled connectivity",
        humanFrictionHook: "Idle agents and stalled outreach queues",
        narrativeContrast:
          "Contrast manual dial chaos with quiet FreeSWITCH-class connectivity and paced outreach control",
        primaryHeadline: "SCALE OUTREACH WITHOUT LOSING CONTROL",
        subheadline: "Intelligent dialing for high-volume operations",
        modernVisualDirection:
          "Modern contact-center / ops floor with clean dialer dashboard and cloud infrastructure overlays; NO legacy phone banks as primary hero",
        dashboardCue: "Live dialer metrics, connect rates, and queue health",
        markets,
      };
    case "sms":
      return {
        solutionCategory: category,
        primaryValueProp: "Compliant high-volume messaging with delivery control",
        humanFrictionHook: "Messages ignored, delayed, or blocked",
        narrativeContrast:
          "Contrast noisy, poorly timed blasts with trusted, trackable SMS delivery",
        primaryHeadline: "MESSAGES THAT REACH PEOPLE — NOT FILTERS",
        subheadline: "High-volume SMS with compliance and delivery control",
        modernVisualDirection:
          "Modern workspace with messaging dashboard and delivery success metrics; NO paper fax machines",
        dashboardCue: "SMS campaign console with delivery and reply metrics",
        markets,
      };
    case "email":
      return {
        solutionCategory: category,
        primaryValueProp: "Inbox placement and campaign intelligence at scale",
        humanFrictionHook: "Campaigns dying in spam folders",
        narrativeContrast:
          "Contrast wasted ad spend on spam folders with authenticated, measurable inbox reach",
        primaryHeadline: "LAND DIRECTLY IN THE INBOX. SCALE CONVERSIONS",
        subheadline: "Deliverability, automation, and campaign intelligence",
        modernVisualDirection:
          "Marketing team reviewing email performance dashboard with high deliverability metrics; cloud mail infrastructure cues; NO paper fax distress",
        dashboardCue: "Email marketing dashboard with open rates and delivery status",
        markets,
      };
    case "cms":
      return {
        solutionCategory: category,
        primaryValueProp: "Faster publishing with structured web operations",
        humanFrictionHook: "Stalled updates and fragmented website ownership",
        narrativeContrast:
          "Contrast chaotic site edits with calm, structured publishing control",
        primaryHeadline: "PUBLISH FASTER WITH FEWER HANDOFF DELAYS",
        subheadline: "Modern CMS workflows for enterprise teams",
        modernVisualDirection:
          "Clean CMS / content dashboard on a large monitor in a bright office; NO paper fax imagery",
        dashboardCue: "CMS publishing dashboard with structured pages and status",
        markets,
      };
    case "education_admissions":
      return {
        solutionCategory: category,
        primaryValueProp:
          "A connected admissions journey that captures inquiries and guides students to enrolment",
        humanFrictionHook:
          "Late-night inquiries, anxious parents, and fragmented counsellor follow-up",
        narrativeContrast:
          "Contrast disconnected search, WhatsApp, email, and website inquiries with one transparent student journey from inquiry to enrolment",
        primaryHeadline: "EVERY ADMISSION BEGINS WITH ONE SEARCH",
        subheadline:
          "Build parent trust and guide every genuine inquiry from counselling to enrolment",
        modernVisualDirection:
          "Premium editorial EdTech admissions office at late evening; counsellor handling inquiries from search, WhatsApp, email, and website; transparent student journey dashboard: Inquiry, Counselling, Document Verification, Admission Letter, Visa, Enrolment; Indian parents, online student counselling, international campus, subtle India-to-Uzbekistan connection; NO doctors treating patients, NO hospital scenes, NO medical reports, NO fake analytics",
        dashboardCue:
          "Admissions journey dashboard showing Inquiry → Counselling → Document Verification → Admission Letter → Visa → Enrolment",
        markets: "India and international education markets",
      };
    case "fax":
      return {
        solutionCategory: category,
        primaryValueProp: "Secure, trackable digital document exchange when inboxes fail",
        humanFrictionHook: "Crowded channels delaying critical documents",
        narrativeContrast:
          "Contrast ignored email threads and delayed contracts with secure digital document broadcast and confirmation — modern cloud workflows, never paper distress",
        primaryHeadline: "CRITICAL DOCUMENTS MOVE FASTER WHEN COMMUNICATION IS SIMPLER",
        subheadline: "Secure digital document delivery for regulated industries",
        modernVisualDirection:
          "Calm professionals collaborating at a modern monitor showing secure document delivery / cloud workflow dashboard; subtle cloud infrastructure; STRICT BAN on physical fax machines, paper stacks, printer distress, 2005 stock 'frustrated with paper' poses",
        dashboardCue: "Secure document broadcast dashboard with delivery confirmations",
        markets,
      };
    default:
      return {
        solutionCategory: "generic",
        primaryValueProp: "Reliable communication and operations workflows",
        humanFrictionHook: "Everyday operational friction slowing the team",
        narrativeContrast:
          "Contrast chaotic workflows with quiet backend systems that restore control",
        primaryHeadline: "WORKFLOWS MOVE FASTER WHEN FRICTION IS REMOVED",
        subheadline: "Practical infrastructure for modern B2B operations",
        modernVisualDirection:
          "Modern corporate workspace with clean operational dashboard and cloud infrastructure cues; candid professionals; no legacy hardware distress",
        dashboardCue: "Clean operations dashboard with status and throughput metrics",
        markets,
      };
  }
}

function solutionDisplayName(
  category: SolutionCategory,
  website?: WebsiteIntelligence | null,
  sequenceTitle?: string,
): string {
  const fromSeq = sequenceTitle?.replace(/^Post \d+\s*[—–-]\s*/i, "").trim();
  if (fromSeq && fromSeq.length >= 4 && fromSeq.length <= 60 && !/crowded|changing|proof/i.test(fromSeq)) {
    return fromSeq;
  }
  const fromSite = cleanLabel(website?.primaryService || website?.services?.[0]?.label || "");
  if (fromSite) return fromSite;

  switch (category) {
    case "dnc":
      return "DNC Lead Cleaning & Scrubber";
    case "call_tracking":
      return "Call Tracking Solution";
    case "dialer":
      return "Enterprise Dialer";
    case "sms":
      return "SMS Broadcasting";
    case "email":
      return "Email Broadcasting";
    case "cms":
      return "Website CMS";
    case "education_admissions":
      return "Digital Admissions Experience";
    case "fax":
      return "Secure Digital Document Exchange";
    default:
      return "Business Communication Platform";
  }
}

function extractMetrics(website?: WebsiteIntelligence | null): string[] {
  const blob = [
    website?.description,
    ...(website?.benefits ?? []),
    ...(website?.services?.map((s) => s.detail) ?? []),
  ]
    .filter(Boolean)
    .join(" ");
  const found = blob.match(/\d[\d,.]*%|\d[\d,.]*\+?\s*(?:k|m|million|contacts|calls|records)?/gi) ?? [];
  return [...new Set(found.map((m) => m.trim()))].slice(0, 4);
}

/**
 * Build fully parameterized product config for captions, video, and image prompts.
 * Brand stays separate — swap product variables without rewriting brand identity.
 */
export function resolveDynamicProductConfig(input: {
  brand: BrandProfile;
  project: Project;
  website?: WebsiteIntelligence | null;
  sequenceTitle?: string;
  problem?: string;
  impact?: string;
  brandResponse?: string;
}): DynamicProductConfiguration {
  const category = detectSolutionCategory(input);
  const defaults = catalogDefaults(category);
  const solutionName = solutionDisplayName(category, input.website, input.sequenceTitle);

  const scrapedFeatures = (input.website?.services ?? [])
    .map((s) => cleanLabel(s.label) || s.label)
    .filter((l) => l && l.length >= 3)
    .slice(0, 6);

  const features =
    scrapedFeatures.length > 0
      ? scrapedFeatures
      : (input.website?.benefits ?? []).map((b) => truncate(b, 60)).filter(Boolean).slice(0, 4);

  const metrics = extractMetrics(input.website);

  const valueFromImpact = input.impact?.trim()
    ? truncate(input.impact.replace(/^Impact:\s*/i, ""), 120)
    : "";
  const frictionFromProblem = input.problem?.trim()
    ? truncate(input.problem.replace(/^Problem:\s*/i, ""), 120)
    : "";

  // Prefer scraped service name inside headline when distinct
  let primaryHeadline = defaults.primaryHeadline;
  if (features[0] && category === "generic") {
    primaryHeadline = `${features[0]!.toUpperCase()} — CLEARER OPERATIONS. FASTER OUTCOMES.`.slice(0, 72);
  }

  let subheadline = defaults.subheadline;
  if (input.brandResponse?.trim() && !/revolutioniz|market your/i.test(input.brandResponse)) {
    subheadline = truncate(input.brandResponse, 90);
  } else if (valueFromImpact) {
    subheadline = truncate(valueFromImpact, 90);
  }

  return {
    ...defaults,
    solutionName,
    scrapedFeatures: features.length ? features : [solutionName],
    scrapedMetrics: metrics,
    primaryValueProp: valueFromImpact || defaults.primaryValueProp,
    humanFrictionHook: frictionFromProblem || defaults.humanFrictionHook,
    primaryHeadline,
    subheadline,
  };
}

/** Map extended solution catalog onto legacy BrandVertical used by SVG helpers. */
export function solutionToBrandVertical(
  category: SolutionCategory,
): "fax" | "sms" | "email" | "generic" {
  if (category === "fax") return "fax";
  if (category === "sms") return "sms";
  if (category === "email") return "email";
  return "generic";
}

/** Prompt block injected into image/caption generation. */
export function formatProductConfigForPrompt(config: DynamicProductConfiguration): string {
  return [
    "[DYNAMIC_PRODUCT_CONFIGURATION]",
    `- Solution Category: ${config.solutionName} (${config.solutionCategory})`,
    `- Scraped Features: ${config.scrapedFeatures.join("; ") || "—"}`,
    config.scrapedMetrics.length ? `- Scraped Metrics: ${config.scrapedMetrics.join(", ")}` : "",
    `- Primary Value Prop: ${config.primaryValueProp}`,
    `- Key Human Friction Hook: ${config.humanFrictionHook}`,
    `- Narrative Contrast: ${config.narrativeContrast}`,
    `- Primary Headline (use exactly unless a cleaner variant fits): ${config.primaryHeadline}`,
    `- Subheadline: ${config.subheadline}`,
    `- Visual Direction: ${config.modernVisualDirection}`,
    `- Dashboard Cue: ${config.dashboardCue}`,
    `- Markets: ${config.markets}`,
  ]
    .filter(Boolean)
    .join("\n");
}
