/**
 * Verifies dynamic brand image context (website scrape + posting context).
 * Run: npx tsx scripts/verify-brand-images.ts
 */
import {
  detectBrandVertical,
  resolveBrandVisualStyle,
  shouldPreferBrandedTemplate,
} from "../src/lib/generation/brand-visual-style";
import { buildBrandedSocialCardSvg, buildSocialImageContext } from "../src/lib/generation/social-image";
import type { WebsiteIntelligence } from "../src/lib/context/website-intelligence";
import type { BrandProfile, PostSequenceItem, Project } from "../src/types/workflow";

const story = {
  problem: "Paid ads cost more but produce fewer qualified B2B conversations.",
  impact: "Teams see higher response rates when combining social posts with direct outreach.",
  brandResponse: "Our platform delivers compliant, high-attention messages to decision-makers.",
};

function mockWebsite(input: {
  url: string;
  companyName: string;
  tagline: string;
  primaryService: string;
  services: Array<{ label: string; detail: string }>;
  vertical: WebsiteIntelligence["vertical"];
  contactPhone?: string;
  contactEmail?: string;
}): WebsiteIntelligence {
  return {
    url: input.url,
    fetchedAt: new Date().toISOString(),
    ok: true,
    title: input.companyName,
    description: input.tagline,
    tagline: input.tagline,
    companyName: input.companyName,
    primaryService: input.primaryService,
    services: input.services,
    about: input.tagline,
    products: [],
    features: [],
    targetAudience: "",
    industries: [],
    locations: [],
    benefits: input.services.map((s) => s.label.split(/\s+/).slice(0, 3).join(" ").toUpperCase()),
    valuePropositions: [input.tagline],
    differentiators: [],
    websiteClaims: [],
    faqs: [],
    keywords: [],
    themeColor: "#1e3a5f",
    accentColor: "#e87121",
    vertical: input.vertical,
    productVisualHint: input.services.map((s) => s.label).join(", "),
    headings: [input.primaryService],
    logoUrl: null,
    contactPhone: input.contactPhone ?? "missing",
    contactEmail: input.contactEmail ?? "missing",
    address: "missing",
    analysisMarkdown: `Primary service: ${input.primaryService}`,
  };
}

const projects: Array<{
  name: string;
  project: Project;
  brand: BrandProfile;
  website: WebsiteIntelligence;
  expectVertical: string;
}> = [
  {
    name: "B2BEFAX",
    project: {
      id: "1",
      name: "B2BEFAX",
      website: "https://www.b2befax.com",
      industry: "B2B Communications / eFax",
      timezone: "America/New_York",
      countries: ["US"],
      status: "active",
      createdAt: "",
      updatedAt: "",
    },
    brand: {
      companyName: "B2BEFAX",
      tagline: "B2B fax broadcasting for growing businesses",
      industry: "B2B Communications / eFax",
      brandVoice: "Professional",
      logoDataUrl: "data:image/png;base64,abc",
      logoFileName: "logo.png",
      contactPhone: "+1 (800) 555-0199",
      contactEmail: "sales@b2befax.com",
    },
    website: mockWebsite({
      url: "https://www.b2befax.com",
      companyName: "B2BEFAX",
      tagline: "B2B fax broadcasting for growing businesses",
      primaryService: "B2B Fax Broadcasting",
      vertical: "fax",
      contactPhone: "+1 (800) 555-0199",
      contactEmail: "sales@b2befax.com",
      services: [
        { label: "Send & Receive Faxes Online", detail: "Fax documents in a few clicks." },
        { label: "Secure Document Delivery", detail: "Keep communications safe." },
      ],
    }),
    expectVertical: "fax",
  },
  {
    name: "SMS Broadcast",
    project: {
      id: "2",
      name: "SMS Broadcast Pro",
      website: "https://sms.example.com",
      industry: "SMS Marketing",
      timezone: "UTC",
      countries: ["US"],
      status: "active",
      createdAt: "",
      updatedAt: "",
    },
    brand: {
      companyName: "SMS Broadcast Pro",
      tagline: "Bulk SMS campaigns that reach mobile audiences instantly",
      industry: "SMS Marketing",
      brandVoice: "Professional",
      logoDataUrl: "data:image/png;base64,abc",
      logoFileName: "logo.png",
    },
    website: mockWebsite({
      url: "https://sms.example.com",
      companyName: "SMS Broadcast Pro",
      tagline: "Bulk SMS campaigns that reach mobile audiences instantly",
      primaryService: "Bulk SMS Broadcast",
      vertical: "sms",
      services: [
        { label: "Bulk SMS Campaigns", detail: "Reach customers instantly." },
        { label: "Two-Way Messaging", detail: "Engage with replies." },
      ],
    }),
    expectVertical: "sms",
  },
];

const sequenceItem: PostSequenceItem = {
  id: "seq-1",
  title: "Post 1 — Awareness",
  summary: "Introduce the challenge",
  tag: "Awareness",
  content: "Problem and impact content",
};

let failed = 0;

for (const sample of projects) {
  const vertical = detectBrandVertical(sample.brand, sample.project, sample.website);
  const style = resolveBrandVisualStyle(sample.brand, sample.project, story, sample.website);
  const ctx = buildSocialImageContext({
    project: sample.project,
    brand: sample.brand,
    sequenceItem,
    caption: "**Reach buyers faster** with targeted outreach.",
    storySections: {
      currentStory: "",
      keyTheme: "Awareness · Reach",
      ...story,
    },
    website: sample.website,
  });
  const svg = decodeURIComponent(buildBrandedSocialCardSvg(ctx).split(",")[1] ?? "");

  const firstService = style.features[0]?.label ?? "";
  // Card layouts uppercase feature labels, so match case-insensitively.
  const firstServiceNeedle = firstService.replace(/&/g, "&amp;").slice(0, 12);
  const svgUpper = svg.toUpperCase();
  const firstServiceNeedleUpper = firstServiceNeedle.toUpperCase();

  const checks: Array<[string, boolean]> = [
    [`vertical=${sample.expectVertical}`, vertical === sample.expectVertical],
    [`cta subline references service`, style.ctaSubline.length > 0],
    [`website services scrolled`, style.features.length > 0 && Boolean(firstServiceNeedle) && svgUpper.includes(firstServiceNeedleUpper)],
    [`website in footer`, Boolean(style.website) && svg.includes(style.website.split("/")[0]!.slice(0, 12))],
    [`scraped service in style`, style.primaryService.length > 0],
    [`prefers branded template`, shouldPreferBrandedTemplate({ logoDataUrl: sample.brand.logoDataUrl, websiteOk: true, website: style.website, hasServices: style.features.length > 0 })],
    [`no generic CLOUD SaaS`, !svg.includes("CLOUD") && !svg.includes("SaaS")],
  ];

  if (sample.brand.contactPhone) {
    checks.push([`contact phone in footer`, style.contactPhone === sample.brand.contactPhone && svg.includes(sample.brand.contactPhone)]);
  }
  if (sample.brand.contactEmail) {
    checks.push([`contact email in footer`, style.contactEmail === sample.brand.contactEmail && svg.includes(sample.brand.contactEmail)]);
  }

  console.log(`\n=== ${sample.name} ===`);
  for (const [label, ok] of checks) {
    console.log(ok ? `  ✓ ${label}` : `  ✗ FAIL: ${label}`);
    if (!ok) failed++;
  }
}

if (failed > 0) {
  console.error(`\n${failed} check(s) failed.`);
  process.exit(1);
}

console.log("\nDynamic brand image checks passed (website scrape + posting context).");
