/**
 * One-off generator: AEGIS CYBER — Executive Briefing (bank leave-behind).
 * Uses the already-installed pdfkit. Run: npx tsx scripts/generate-bank-briefing.ts
 * Output: exports/AEGIS_CYBER_Bank_Briefing.pdf
 *
 * Content is grounded against the codebase (verified 2026-06). Capability tiers:
 *   GREEN  = production-grade (implemented + operating)
 *   AMBER  = real logic, external connection activates at onboarding
 *   RUST   = demonstration simulation (sandbox / regulatory validation)
 */
import fs from "fs";
import path from "path";

const NAVY = "#0B1F3A";
const ACCENT = "#12B5A8";
const INK = "#222B36";
const MUTE = "#6B7280";
const PROD = "#1B9E5A";
const INTEG = "#C77F00";
const SIM = "#B5462F";
const WHITE = "#FFFFFF";

const MARGIN = { top: 118, bottom: 64, left: 56, right: 56 };

async function main() {
  const PDFDocument = (await import("pdfkit")).default;
  const doc: any = new PDFDocument({
    size: "A4",
    margins: MARGIN,
    bufferPages: true,
    autoFirstPage: false,
  });

  const PAGE_W = 595.28;
  const contentWidth = PAGE_W - MARGIN.left - MARGIN.right;
  const RIGHT = MARGIN.left + contentWidth;

  // ---- per-page chrome (header band + footer line/left), drawn on every page ----
  doc.on("pageAdded", () => {
    // header band
    doc.rect(0, 0, PAGE_W, 89).fill(NAVY);
    doc.rect(0, 89, PAGE_W, 3).fill(ACCENT);
    doc.fillColor(WHITE).font("Helvetica-Bold").fontSize(17).text("AEGIS CYBER", MARGIN.left, 30, { lineBreak: false });
    doc.fillColor("#9FE9E2").font("Helvetica").fontSize(9).text("Cognitive Security Layer for African Banking", MARGIN.left, 54, { lineBreak: false });
    doc.fillColor(WHITE).font("Helvetica-Bold").fontSize(9).text("EXECUTIVE BRIEFING", RIGHT - 160, 32, { width: 160, align: "right", lineBreak: false });
    doc.fillColor("#9FE9E2").font("Helvetica").fontSize(8).text("Confidential", RIGHT - 160, 46, { width: 160, align: "right", lineBreak: false });
    // footer line + left label
    const fy = doc.page.height - 46;
    doc.moveTo(MARGIN.left, fy).lineTo(RIGHT, fy).lineWidth(0.75).strokeColor("#D7DCE3").stroke();
    doc.fillColor(MUTE).font("Helvetica").fontSize(8).text("AEGIS CYBER  ·  Prepared for banking partners", MARGIN.left, fy + 6, { lineBreak: false });
    // reset cursor for body flow
    doc.x = MARGIN.left;
    doc.y = MARGIN.top;
  });

  const pageBottom = () => doc.page.height - MARGIN.bottom;
  const ensureSpace = (h: number) => {
    if (doc.y + h > pageBottom()) doc.addPage();
  };

  const sectionTitle = (num: string, title: string) => {
    ensureSpace(50);
    doc.moveDown(0.5);
    const y = doc.y;
    doc.fillColor(ACCENT).font("Helvetica-Bold").fontSize(12).text(num, MARGIN.left, y + 1, { width: 26, lineBreak: false });
    doc.fillColor(NAVY).font("Helvetica-Bold").fontSize(13.5).text(title, MARGIN.left + 26, y, { width: contentWidth - 26, lineBreak: false });
    doc.x = MARGIN.left;
    doc.moveDown(0.55);
    const ly = doc.y;
    doc.moveTo(MARGIN.left, ly).lineTo(RIGHT, ly).lineWidth(1).strokeColor(ACCENT).stroke();
    doc.moveDown(0.55);
  };

  const tierHeading = (label: string, color: string) => {
    ensureSpace(30);
    doc.moveDown(0.25);
    doc.font("Helvetica-Bold").fontSize(8.5);
    const tw = doc.widthOfString(label.toUpperCase());
    const y = doc.y;
    doc.roundedRect(MARGIN.left, y, tw + 16, 16, 4).fill(color);
    doc.fillColor(WHITE).font("Helvetica-Bold").fontSize(8.5).text(label.toUpperCase(), MARGIN.left + 8, y + 4.5, { lineBreak: false });
    doc.x = MARGIN.left;
    doc.y = y + 16;
    doc.moveDown(0.45);
  };

  const para = (text: string, color = INK, size = 9.5) => {
    doc.x = MARGIN.left;
    doc.font("Helvetica").fontSize(size);
    ensureSpace(doc.heightOfString(text, { width: contentWidth, lineGap: 2 }) + 4);
    doc.fillColor(color).text(text, MARGIN.left, doc.y, { width: contentWidth, lineGap: 2 });
    doc.moveDown(0.4);
  };

  const bulletW = contentWidth - 16;
  const bullet = (text: string, color = INK) => {
    doc.font("Helvetica").fontSize(9.5);
    const h = doc.heightOfString(text, { width: bulletW, lineGap: 1.5 });
    ensureSpace(h + 5);
    const y = doc.y;
    doc.fillColor(ACCENT).font("Helvetica-Bold").fontSize(9.5).text("•", MARGIN.left + 2, y, { width: 10, lineBreak: false });
    doc.fillColor(color).font("Helvetica").fontSize(9.5).text(text, MARGIN.left + 16, y, { width: bulletW, lineGap: 1.5 });
    doc.x = MARGIN.left;
    doc.moveDown(0.28);
  };

  const richBullet = (lead: string, rest: string, color = INK) => {
    doc.font("Helvetica").fontSize(9.5);
    const h = doc.heightOfString(lead + " " + rest, { width: bulletW, lineGap: 1.5 });
    ensureSpace(h + 6);
    const y = doc.y;
    doc.fillColor(ACCENT).font("Helvetica-Bold").fontSize(9.5).text("•", MARGIN.left + 2, y, { width: 10, lineBreak: false });
    doc
      .font("Helvetica-Bold").fillColor(NAVY).fontSize(9.5)
      .text(lead + "  ", MARGIN.left + 16, y, { width: bulletW, lineGap: 1.5, continued: true })
      .font("Helvetica").fillColor(color)
      .text(rest, { continued: false });
    doc.x = MARGIN.left;
    doc.moveDown(0.28);
  };

  const qa = (q: string, a: string) => {
    doc.x = MARGIN.left;
    doc.font("Helvetica-Bold").fontSize(9.5);
    const hq = doc.heightOfString("Q.  " + q, { width: contentWidth, lineGap: 1.5 });
    doc.font("Helvetica").fontSize(9.5);
    const ha = doc.heightOfString("A.  " + a, { width: contentWidth, lineGap: 1.5 });
    ensureSpace(hq + ha + 10);
    doc.fillColor(NAVY).font("Helvetica-Bold").fontSize(9.5).text("Q.  " + q, MARGIN.left, doc.y, { width: contentWidth, lineGap: 1.5 });
    doc.fillColor(INK).font("Helvetica").fontSize(9.5).text("A.  " + a, MARGIN.left, doc.y + 1, { width: contentWidth, lineGap: 1.5 });
    doc.moveDown(0.5);
  };

  const legendRow = (color: string, label: string, desc: string) => {
    const y = doc.y;
    doc.circle(MARGIN.left + 5, y + 5, 4).fill(color);
    doc.font("Helvetica-Bold").fontSize(9).fillColor(NAVY).text(label, MARGIN.left + 16, y, { width: 150, lineBreak: false });
    doc.font("Helvetica").fontSize(9).fillColor(INK).text(desc, MARGIN.left + 150, y, { width: contentWidth - 150, lineGap: 1.5 });
    doc.x = MARGIN.left;
    doc.moveDown(0.45);
  };

  // ===================== COVER =====================
  doc.addPage();
  doc.y = 168;
  doc.fillColor(ACCENT).font("Helvetica-Bold").fontSize(10).text("EXECUTIVE BRIEFING  ·  BANKING PARTNERS", MARGIN.left, doc.y, { characterSpacing: 1 });
  doc.moveDown(0.5);
  doc.fillColor(NAVY).font("Helvetica-Bold").fontSize(23).text("Securing African banking with a cognitive security layer", MARGIN.left, doc.y, { width: contentWidth, lineGap: 3 });
  doc.moveDown(0.7);
  doc.fillColor(INK).font("Helvetica").fontSize(11).text(
    "AEGIS CYBER is an agentic-AI cybersecurity and compliance platform built specifically for African banking — starting with Uganda. It unifies real-time threat detection, transaction monitoring, and automated regulatory compliance (DPPA/PDPO 2019 and BoU Cyber Risk Guidelines 2023) in a single multi-tenant platform engineered for local data sovereignty and low-connectivity resilience.",
    MARGIN.left, doc.y, { width: contentWidth, lineGap: 3 }
  );
  doc.moveDown(1.2);
  doc.fillColor(MUTE).font("Helvetica").fontSize(9).text("Prepared June 2026  ·  Live demonstration: aegis-cyber.replit.app", MARGIN.left, doc.y);
  doc.moveDown(1.4);

  // legend box
  const lboxY = doc.y;
  doc.roundedRect(MARGIN.left, lboxY, contentWidth, 116, 6).lineWidth(1).fillAndStroke("#F4F7F8", "#D7DCE3");
  doc.x = MARGIN.left + 16;
  doc.y = lboxY + 14;
  doc.fillColor(NAVY).font("Helvetica-Bold").fontSize(10).text("How to read the capability tags in this document", { width: contentWidth - 32 });
  doc.moveDown(0.5);
  const savedLeft = MARGIN.left;
  (MARGIN as any).left = savedLeft + 16;
  legendRow(PROD, "Production-grade", "implemented and operating today.");
  legendRow(INTEG, "Integration-ready", "real internal logic; the external connection (regulator, telco, identity provider, certified HSM) is activated during onboarding.");
  legendRow(SIM, "Demonstration", "sandbox simulation used for regulatory validation; not yet wired to live operations.");
  (MARGIN as any).left = savedLeft;

  // ===================== 1. WHY CHOOSE AEGIS =====================
  doc.addPage();
  sectionTitle("1", "Why AEGIS CYBER over other platforms");
  para("The core difference: it is built natively for Ugandan and East African banking — not a Western platform retrofitted with a local label.");
  richBullet("Regulation is in the code, not the brochure.", "DPPA/PDPO 2019 (Sections 23, 26, 28, 31) and BoU Cyber Risk Guidelines 2023 are enforced programmatically; a Sovereignty Monitor blocks data leaving Uganda/EAC at the routing layer.");
  richBullet("Built for African operating reality.", "Sovereign Edge nodes (Kampala, Entebbe, Jinja, Mbarara, Gulu, Arua) keep fraud scoring alive during fiber cuts using offline cached-trust processing.");
  richBullet("Meets customers on feature phones.", "A USSD channel with SIM-swap detection (IMSI change + PIN-timing anomalies) targets the region's leading mobile-money fraud vector — something most global platforms ignore.");
  richBullet("Never goes dark.", "AI threat scoring runs on Anthropic Claude, but falls through automatically to a deterministic scoring engine if the AI is unavailable — no fail-open security gap.");
  richBullet("Regulator-grade evidence.", "Every audit record is SHA-256 hash-chained with tamper detection and Merkle-root verification, so you can prove logs were not altered.");
  richBullet("Refuses to fabricate.", "Invented metrics (fake accuracy scores, fake model names) were deliberately removed; explainability outputs are honestly labelled. For a risk team, a system that won't lie to you is itself a differentiator.");
  richBullet("True multi-tenant isolation.", "Three independent layers — per-request tenant context, session-derived identity, and database row-level security — keep each bank's data sealed from every other tenant.");

  // ===================== 2. CAPABILITIES =====================
  doc.addPage();
  sectionTitle("2", "Capabilities");
  para("Grouped by maturity so the platform's real posture is clear. This honesty is deliberate — and defensible under scrutiny.");

  tierHeading("Production-grade core", PROD);
  bullet("KYT (Know Your Transaction) engine — detects large transfers, new or flagged recipients and geo-anomalies, with built-in processing-time instrumentation.");
  bullet("AI threat scoring — Claude-based with a 3-tier fallback to a deterministic floor; tracks latency and error rate.");
  bullet("Multi-tenant isolation — tenant context + session identity + PostgreSQL row-level security (the most heavily verified subsystem).");
  bullet("Field-level encryption — AES-256-GCM for customer PII and credentials (NIST SP 800-38D); fails closed in production if keys are absent.");
  bullet("Tamper-evident audit chain — SHA-256 hash-chaining plus Merkle-root verification.");
  bullet("DSAR engine — access, erasure and portability with a 30-day SLA and a row-level-security-aware purge worker.");
  bullet("Also live: Compliance Hub, breach state machine (72-hour clock), data-retention policy framework, SIEM forwarding (CEF/LEEF/Syslog), live CVE scanning (OSV), backup service, notification gateway, tenant self-service portal, usage-based billing.");

  tierHeading("Real logic, integration-ready", INTEG);
  bullet("SAR auto-filing to the FIA — report generation, persistence and audit are live; the external FIA submission link activates at onboarding.");
  bullet("NITA-U breach notification — templates and 72-hour logic are live; external delivery activates at onboarding.");
  bullet("SSO — SAML / OIDC / Azure AD / Okta structure is present; the live identity-provider handshake is configured during onboarding.");
  bullet("Telco / USSD gateways — built for MTN and Airtel; the live telco connection is pending partner credentials.");

  tierHeading("Demonstration simulations", SIM);
  bullet("DR failover — simulates RTO/RPO timing (Kampala to Entebbe); it does not yet flip live traffic.");
  bullet("HSM enclave — software-defined FIPS 140-3-style operations plus real post-quantum ML-KEM-768 key operations; it is not a physically certified HSM (production integrates a certified device via the crypto-agility layer).");
  bullet("Data-retention execution — minimums and the policy engine are real; the purge step currently reports simulated counts.");

  // ===================== 3. COST EFFECTIVENESS =====================
  doc.addPage();
  sectionTitle("3", "Cost effectiveness");
  para("Commercial pricing is set per engagement. The platform's economics are designed to undercut stitched-together foreign point solutions:");
  richBullet("Usage-based billing.", "Meters by unit (AI inference, deception, KYC) with departmental cost centers and VAT-compliant Ugandan invoicing — banks pay for what they use.");
  richBullet("Tool consolidation.", "Replaces 4–6 separate purchases — transaction monitoring, SIEM forwarding, privacy/DSAR, breach management, regulator reporting and vulnerability scanning — with one platform.");
  richBullet("Multi-tenant SaaS, cloud-deployed.", "No per-bank hardware; low capital outlay on an operating-expense model.");
  richBullet("Downtime avoidance.", "Sovereign Edge sustains fraud scoring through outages, and the deterministic AI fallback removes the need for a redundant backup engine.");
  richBullet("Compliance-penalty avoidance.", "Enforced data residency and DSAR SLAs reduce exposure to PDPO fines and cross-border violations.");
  richBullet("No vendor lock-in.", "Built-in tenant data export and exit drills lower switching risk.");
  doc.moveDown(0.3);
  ensureSpace(40);
  const hy = doc.y;
  doc.roundedRect(MARGIN.left, hy, contentWidth, 34, 6).fillAndStroke("#EAF6F4", ACCENT);
  doc.fillColor(NAVY).font("Helvetica-Bold").fontSize(10).text(
    "Pay-as-you-grow  +  consolidation of 4–6 tools  +  local-residency compliance  =  lower total cost of ownership than foreign point solutions.",
    MARGIN.left + 14, hy + 8, { width: contentWidth - 28, lineGap: 1.5 }
  );
  doc.x = MARGIN.left;
  doc.y = hy + 34;
  doc.moveDown(0.6);

  // ===================== 4. ANTICIPATED QUESTIONS =====================
  doc.addPage();
  sectionTitle("4", "Questions the bank may ask");
  qa("Does our data stay in Uganda?", "Yes — enforced in code (Sovereignty Monitor, DPPA Section 23); routing blocks out-of-country transfers.");
  qa("What if your AI provider fails?", "Automatic fall-through to a deterministic scoring engine; the system never stops scoring.");
  qa("How do we trust the audit trail?", "SHA-256 hash-chaining, per-row content recompute and Merkle-root verification make tampering detectable.");
  qa("Can another bank see our data?", "No — three-layer isolation (tenant context, session identity, row-level security), continuously tested.");
  qa("Do you file SARs to the FIA automatically?", "SAR generation, persistence and audit are live; the FIA submission link activates at onboarding.");
  qa("Is the HSM FIPS-certified?", "It runs FIPS 140-3-style operations and real post-quantum crypto in software today; production deployments integrate a certified hardware HSM.");
  qa("SSO with our Azure AD or Okta?", "Supported by design; the live identity-provider handshake is configured during onboarding.");
  qa("What is your latency?", "The detection paths instrument their own timing; sub-200 ms is the design target — quote a measured figure only once benchmarked on your data.");
  qa("What about disaster recovery?", "Validated today as a timed drill (RTO/RPO Kampala to Entebbe); live failover is on the production roadmap.");
  qa("How is the right to erasure handled?", "A full DSAR workflow with a 30-day SLA and row-level-security-aware erasure.");
  qa("Is this BoU-approved?", "Engineered to the BoU Cyber Risk Guidelines 2023 and aimed at the regulatory sandbox; state the current standing explicitly rather than implying full certification.");
  qa("What about exit and lock-in?", "Tenant data export and exit drills are built in.");

  // ===================== 5. TECH DESIGN =====================
  doc.addPage();
  sectionTitle("5", "Technical design (at a glance)");
  richBullet("Frontend:", "React 18 + TypeScript, Wouter routing, TanStack Query, Tailwind + shadcn/ui, Framer Motion; real-time updates over WebSockets.");
  richBullet("Backend:", "Express 5 + TypeScript; REST + WebSocket server; thin routes over a storage layer.");
  richBullet("Data:", "PostgreSQL + Drizzle ORM; row-level security; Btree-DESC indexes for time-series queries.");
  richBullet("Multi-tenancy:", "Per-request tenant GUC (pinned connection + explicit transaction) + session-derived tenant resolution + RLS USING/WITH CHECK predicates.");
  richBullet("Encryption:", "AES-256-GCM field-level (PII + credentials) with HMAC blind-lookup and scrypt key derivation; post-quantum ML-KEM-768; a boot-time secret guard fails fast on weak or missing secrets.");
  richBullet("AI:", "Anthropic Claude with a deterministic threat-floor fallback.");
  richBullet("Integrity & resilience:", "SHA-256 hash-chained audit + Merkle root; circuit breaker, idempotent APIs, active deception, loop detection, lockdown.");
  richBullet("Auth & hardening:", "Token authentication, bcrypt, Helmet headers, token-based CSRF protection.");
  richBullet("Deployment:", "Cloud VM; single-port Express + Vite; live at aegis-cyber.replit.app.");
  doc.moveDown(0.8);
  para("Prepared as an internal briefing aid. Capability tags reflect the current sandbox build; integration-ready and demonstration items activate during onboarding.", MUTE, 8.5);

  // ---- page numbers (after all content is laid out) ----
  const range = doc.bufferedPageRange();
  for (let i = 0; i < range.count; i++) {
    doc.switchToPage(range.start + i);
    const y = doc.page.height - 40;
    doc.font("Helvetica").fontSize(8).fillColor(MUTE).text(`Page ${i + 1} of ${range.count}`, MARGIN.left, y, { width: contentWidth, align: "right", lineBreak: false });
  }

  const OUT = path.join("exports", "AEGIS_CYBER_Bank_Briefing.pdf");
  const stream = fs.createWriteStream(OUT);
  doc.pipe(stream);
  doc.end();
  await new Promise<void>((resolve, reject) => {
    stream.on("finish", () => resolve());
    stream.on("error", reject);
  });
  const { size } = fs.statSync(OUT);
  console.log(`OK wrote ${OUT} (${size} bytes, ${range.count} pages)`);
}

main().catch((e) => {
  console.error("FAILED:", e);
  process.exit(1);
});
