/** Report builder (ANL-004) and white-label client reports (ANL-005) rendered to PDF with pdf-lib. */
import { PDFDocument, StandardFonts, rgb, type PDFFont, type PDFPage } from "pdf-lib";
import { eq } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import type { ReportConfig } from "@/db/schema";
import { formatMoney, formatNumber, randomToken } from "@/lib/util";
import { attribution, campaignPerformance, funnel, kpis, repPerformance, type Filters } from "./analytics";

export const REPORT_SECTIONS = [
  { key: "kpis", label: "Headline KPIs" }, { key: "funnel", label: "Funnel & cost per stage" }, { key: "attribution", label: "Source attribution" },
  { key: "campaigns", label: "Campaign performance" }, { key: "reps", label: "Rep performance" }, { key: "social", label: "Social engagement" },
];

export function reportFilters(cfg: ReportConfig): Filters {
  const to = cfg.to ? new Date(`${cfg.to}T23:59:59Z`) : new Date();
  const from = cfg.from ? new Date(`${cfg.from}T00:00:00Z`) : new Date(to.getTime() - (cfg.days ?? 30) * 86400000);
  return { from, to, ...(cfg.filters ?? {}) };
}

export async function buildReport(ctx: Pick<Ctx, "db" | "workspace">, cfg: ReportConfig) {
  const f = reportFilters(cfg);
  const s = new Set(cfg.sections);
  return {
    period: { from: f.from.toISOString().slice(0, 10), to: f.to.toISOString().slice(0, 10) },
    kpis: s.has("kpis") ? await kpis(ctx, f) : null,
    funnel: s.has("funnel") ? await funnel(ctx, f) : null,
    attribution: s.has("attribution") ? await attribution(ctx, f, cfg.model ?? ctx.workspace.settings?.attributionModel ?? "last_touch") : null,
    campaigns: s.has("campaigns") ? await campaignPerformance(ctx, f) : null,
    reps: s.has("reps") ? await repPerformance(ctx, f) : null,
    social: s.has("social") ? await socialSection(ctx, f) : null,
  };
}

/** Module 11 engagement summary for client reports (SOC-084). */
async function socialSection(ctx: Pick<Ctx, "db" | "workspace">, f: Filters) {
  const { engagementReport } = await import("./social");
  const r = await engagementReport({ ...ctx, user: null, perms: {}, actor: { type: "system", id: null, name: "Report" } } as unknown as Ctx, f.from, f.to, "channel");
  return { total: r.total, channels: r.groups, topObjects: r.topObjects.slice(0, 5) };
}

export async function brandingFor(ctx: Pick<Ctx, "db" | "workspace">, whiteLabel: boolean) {
  const agency = ctx.workspace.agencyId ? await ctx.db.query.agencies.findFirst({ where: eq(schema.agencies.id, ctx.workspace.agencyId) }) : null;
  const b = agency?.branding ?? {};
  return {
    name: whiteLabel ? b.productName || agency?.name || ctx.workspace.name : process.env.NEXT_PUBLIC_PRODUCT_NAME ?? "Tempest Pulse",
    color: b.primaryColor || "#2563EB", logoUrl: whiteLabel ? b.logoUrl : undefined, showPlatform: !whiteLabel && !b.hidePlatformBranding,
  };
}

function hex(c: string) {
  const m = c.replace("#", "").match(/.{2}/g) ?? ["ac", "37", "33"];
  return rgb(parseInt(m[0]!, 16) / 255, parseInt(m[1]!, 16) / 255, parseInt(m[2]!, 16) / 255);
}

/** pdf-lib's standard fonts are WinAnsi — strip characters they cannot encode (Bangla is rendered in the web report). */
const safe = (s: string) => s.replace(/[^\x20-\x7E -ÿ]/g, "?").replace(/৳/g, "Tk ");

export async function renderReportPdf(ctx: Pick<Ctx, "db" | "workspace">, title: string, cfg: ReportConfig) {
  const data = await buildReport(ctx, cfg);
  const brand = await brandingFor(ctx, !!cfg.whiteLabel);
  const pdf = await PDFDocument.create();
  const font = await pdf.embedFont(StandardFonts.Helvetica);
  const bold = await pdf.embedFont(StandardFonts.HelveticaBold);
  const accent = hex(brand.color);
  const cur = ctx.workspace.currency;
  const money = (v: number | null | undefined) => (v == null ? "-" : safe(formatMoney(v, cur)).replace("৳", "Tk "));
  let page: PDFPage = pdf.addPage([595, 842]);
  let y = 800;
  const W = 595, M = 48;
  const newPage = () => { page = pdf.addPage([595, 842]); y = 800; };
  const text = (t: string, x: number, size = 10, f: PDFFont = font, color = rgb(0.1, 0.1, 0.12)) => page.drawText(safe(t), { x, y, size, font: f, color });
  const ensure = (h: number) => { if (y - h < 60) newPage(); };

  // header band
  page.drawRectangle({ x: 0, y: 772, width: W, height: 70, color: accent });
  if (brand.logoUrl) {
    try {
      const bytes = new Uint8Array(await (await fetch(brand.logoUrl, { signal: AbortSignal.timeout(5000) })).arrayBuffer());
      const img = brand.logoUrl.toLowerCase().includes(".png") ? await pdf.embedPng(bytes) : await pdf.embedJpg(bytes);
      const s = img.scaleToFit(120, 40);
      page.drawImage(img, { x: W - M - s.width, y: 787, width: s.width, height: s.height });
    } catch { /* logo optional */ }
  }
  y = 812; text(title, M, 18, bold, rgb(1, 1, 1));
  y = 792; text(`${ctx.workspace.name}  |  ${data.period.from} to ${data.period.to}`, M, 10, font, rgb(1, 1, 1));
  y = 740;

  const heading = (h: string) => { ensure(40); y -= 8; text(h, M, 13, bold, accent); y -= 18; };
  const table = (cols: { label: string; w: number; align?: "r" }[], rows: string[][]) => {
    ensure(24);
    let x = M;
    page.drawRectangle({ x: M - 4, y: y - 4, width: W - 2 * M + 8, height: 16, color: rgb(0.96, 0.96, 0.98) });
    for (const c of cols) { text(c.label, c.align === "r" ? x + c.w - bold.widthOfTextAtSize(safe(c.label), 8.5) - 4 : x, 8.5, bold); x += c.w; }
    y -= 16;
    for (const r of rows) {
      ensure(16);
      x = M;
      r.forEach((cell, i) => {
        const c = cols[i]!;
        let s = safe(cell);
        while (font.widthOfTextAtSize(s, 9) > c.w - 6 && s.length > 3) s = s.slice(0, -2);
        text(s, c.align === "r" ? x + c.w - font.widthOfTextAtSize(s, 9) - 4 : x, 9);
        x += c.w;
      });
      y -= 14;
    }
    y -= 6;
  };

  if (data.kpis) {
    heading("Headline KPIs");
    const k = data.kpis;
    const tiles: [string, string][] = [["Contacts", formatNumber(k.contacts)], ["New leads", formatNumber(k.newLeads)], ["Median response", k.medianResponseMin == null ? "-" : `${k.medianResponseMin.toFixed(1)} min`], ["Attributed sales", k.attributionPct == null ? "-" : `${k.attributionPct.toFixed(0)}%`]];
    tiles.forEach(([l, v], i) => {
      const x = M + i * 126;
      page.drawRectangle({ x, y: y - 34, width: 118, height: 46, borderColor: rgb(0.88, 0.88, 0.9), borderWidth: 1 });
      page.drawText(safe(l), { x: x + 8, y: y - 2, size: 8, font, color: rgb(0.4, 0.4, 0.45) });
      page.drawText(safe(v), { x: x + 8, y: y - 24, size: 15, font: bold, color: rgb(0.1, 0.1, 0.12) });
    });
    y -= 56;
  }
  if (data.funnel) {
    heading("Funnel & cost per stage");
    const f = data.funnel;
    table([{ label: "Stage", w: 160 }, { label: "Count", w: 90, align: "r" }, { label: "Cost metric", w: 160 }, { label: "Cost", w: 89, align: "r" }], f.stages.map((s) => [s.label, formatNumber(s.count), s.costLabel, money(s.cost)]));
    text(`Spend ${money(f.spend)}   Revenue ${money(f.revenue)}   ROAS ${f.roas == null ? "-" : f.roas.toFixed(2) + "x"}`, M, 9.5, bold); y -= 18;
  }
  if (data.attribution) {
    heading(`Source attribution (${(cfg.model ?? ctx.workspace.settings?.attributionModel ?? "last_touch").replace(/_/g, " ")})`);
    table([{ label: "Source", w: 200 }, { label: "Leads", w: 90, align: "r" }, { label: "Won (credited)", w: 100, align: "r" }, { label: "Revenue", w: 109, align: "r" }], data.attribution.slice(0, 15).map((r) => [r.key.replace(/_/g, " "), formatNumber(r.leads), String(r.won), money(r.revenue)]));
  }
  if (data.campaigns) {
    heading("Campaign performance");
    table([{ label: "Campaign", w: 170 }, { label: "Spend", w: 70, align: "r" }, { label: "Leads", w: 45, align: "r" }, { label: "CPL", w: 60, align: "r" }, { label: "Cost/QL", w: 65, align: "r" }, { label: "Won", w: 40, align: "r" }, { label: "ROAS", w: 49, align: "r" }],
      data.campaigns.slice(0, 20).map((c) => [c.name, money(c.spend), String(c.leads), money(c.cpl), money(c.cpql), String(c.won), c.roas == null ? "-" : `${c.roas.toFixed(1)}x`]));
  }
  if (data.reps) {
    heading("Rep performance");
    table([{ label: "Rep", w: 150 }, { label: "Leads", w: 55, align: "r" }, { label: "Won", w: 45, align: "r" }, { label: "Conv.", w: 55, align: "r" }, { label: "Median resp.", w: 80, align: "r" }, { label: "Activities", w: 114, align: "r" }],
      data.reps.map((r) => [r.name, String(r.leads), String(r.won), `${r.conversionRate.toFixed(0)}%`, r.medianResponseMin == null ? "-" : `${r.medianResponseMin.toFixed(0)} min`, String(r.activities)]));
  }
  if (data.social) {
    heading("Social engagement");
    const t = data.social.total;
    const secs = (v: number | null) => (v == null ? "-" : v < 3600 ? `${Math.round(v / 60)} min` : `${(v / 3600).toFixed(1)} h`);
    text(`${t.conversations} conversations   Replied ${Math.round(t.repliedPct)}%   Median first response ${secs(t.medianFirstResponseS)}   Leads ${t.leads}`, M, 9.5, bold); y -= 18;
    table([{ label: "Channel", w: 140 }, { label: "Conversations", w: 80, align: "r" }, { label: "Replied", w: 60, align: "r" }, { label: "Median FRT", w: 80, align: "r" }, { label: "Negative", w: 60, align: "r" }, { label: "Leads", w: 79, align: "r" }],
      data.social.channels.map((g) => [g.key.replace(/_/g, " "), String(g.conversations), `${Math.round(g.repliedPct)}%`, secs(g.medianFirstResponseS), String(g.negative), String(g.leads)]));
  }
  // footer on every page
  for (const p of pdf.getPages()) {
    p.drawText(safe(brand.showPlatform ? `Generated by ${brand.name} - Brand Tempest` : brand.name), { x: M, y: 28, size: 8, font, color: rgb(0.55, 0.55, 0.6) });
    p.drawText(`${new Date().toISOString().slice(0, 10)}`, { x: W - M - 50, y: 28, size: 8, font, color: rgb(0.55, 0.55, 0.6) });
  }
  return pdf.save();
}

export async function ensureShareToken(ctx: Pick<Ctx, "db">, reportId: string) {
  const r = await ctx.db.query.savedReports.findFirst({ where: eq(schema.savedReports.id, reportId) });
  if (!r) return null;
  if (r.shareToken) return r.shareToken;
  const t = randomToken(18);
  await ctx.db.update(schema.savedReports).set({ shareToken: t }).where(eq(schema.savedReports.id, reportId));
  return t;
}

/** Scheduled delivery: weekly reports go out every Monday, monthly on the 1st (workspace timezone). */
export async function deliverScheduledReports(ctx: Ctx, now = new Date()) {
  const local = new Intl.DateTimeFormat("en-US", { timeZone: ctx.workspace.timezone, weekday: "short", day: "numeric" }).formatToParts(now);
  const weekday = local.find((p) => p.type === "weekday")?.value;
  const day = Number(local.find((p) => p.type === "day")?.value);
  const reports = await ctx.db.select().from(schema.savedReports).where(eq(schema.savedReports.workspaceId, ctx.workspace.id));
  let sent = 0;
  for (const r of reports) {
    const due = (r.schedule === "weekly_mon" && weekday === "Mon") || (r.schedule === "monthly_1" && day === 1);
    if (!due || !r.recipients.length) continue;
    if (r.lastSentAt && now.getTime() - r.lastSentAt.getTime() < 20 * 3600000) continue;
    await sendReportEmail(ctx, r.id);
    sent++;
  }
  return sent;
}

export async function sendReportEmail(ctx: Ctx, reportId: string) {
  const r = await ctx.db.query.savedReports.findFirst({ where: eq(schema.savedReports.id, reportId) });
  if (!r) return;
  const token = await ensureShareToken(ctx, r.id);
  const base = process.env.APP_URL ?? "http://localhost:3000";
  const pdf = await renderReportPdf(ctx, r.name, r.config);
  const { findIntegrations, pushVia } = await import("@/connectors");
  const [email] = await findIntegrations(ctx, ["ses", "sendgrid"]);
  if (!email) throw new Error("No email provider connected for report delivery");
  for (const to of r.recipients) {
    await pushVia(ctx, email, "send", {
      to, subject: `${r.name} — ${new Date().toISOString().slice(0, 10)}`, messageId: `report-${r.id}`,
      html: `<p>Your scheduled report <b>${r.name}</b> is ready.</p><p><a href="${base}/r/${token}">View online</a> · <a href="${base}/api/reports/share/${token}/pdf">Download PDF</a></p>`,
      attachments: [{ content: Buffer.from(pdf).toString("base64"), filename: `${r.name.replace(/[^\w-]+/g, "_")}.pdf`, type: "application/pdf", disposition: "attachment" }],
    });
  }
  await ctx.db.update(schema.savedReports).set({ lastSentAt: new Date() }).where(eq(schema.savedReports.id, r.id));
}
