/**
 * Report Export Content Builder
 * ──────────────────────────────
 * Transforms a structured Analysis object into a flat, export-ready
 * document representation. This is the bridge between the analysis
 * engine and any future export format (PDF, DOCX, Markdown, HTML).
 *
 * The output is a ReportDocument — an ordered array of typed blocks
 * that any exporter can iterate and render without understanding the
 * analysis schema.
 */

import type { Analysis } from "./analysis-schema";

// ─── Export Document Types ──────────────────────────────────────────────────

export interface ReportDocument {
  meta: ReportMeta;
  blocks: ReportBlock[];
}

export interface ReportMeta {
  appBrand: string;
  clientName: string;
  clientDomain: string;
  clientLogoUrl: string | null;
  reportTitle: string;
  reportSubtitle: string;
  reportDate: string;
  generatedBy: string;
  analysisId: string;
  periodLabel: string;
}

export type ReportBlock =
  | { type: "heading"; level: 1 | 2 | 3; text: string }
  | { type: "paragraph"; text: string }
  | { type: "callout"; severity: "info" | "warning" | "critical"; title: string; body: string }
  | { type: "metric_row"; label: string; value: string; change?: string; changeDirection?: "up" | "down" | "flat"; source: string }
  | { type: "finding"; index: number; severity: string; title: string; description: string; evidence?: string; impact?: string; citations?: string }
  | { type: "prediction"; metric: string; current: number; predicted: number; confidence: string; timeframe: string; basis: string; caveat?: string }
  | { type: "recommendation"; index: number; priority: string; title: string; description: string; expectedImpact?: string; citations?: string }
  | { type: "source_row"; label: string; status: string; recordCount?: number }
  | { type: "citation_list"; items: Array<{ label: string; title: string; url: string | null; sourceName: string }> }
  | { type: "divider" }
  | { type: "spacer" }
  | { type: "footer"; text: string };

// ─── Builder ────────────────────────────────────────────────────────────────

export function buildReportDocument(analysis: Analysis): ReportDocument {
  const b = analysis.branding;
  const n = analysis.narrative;

  const meta: ReportMeta = {
    appBrand: b?.appBrand ?? "meSEO",
    clientName: b?.clientName ?? "Client",
    clientDomain: b?.clientDomain ?? "",
    clientLogoUrl: b?.clientLogoUrl ?? null,
    reportTitle: analysis.title,
    reportSubtitle: analysis.subtitle,
    reportDate: b?.reportDate ?? new Date().toISOString().split("T")[0],
    generatedBy: b?.artifactHeaderMeta?.generatedBy ?? "meSEO AI Strategist",
    analysisId: analysis.id,
    periodLabel: analysis.period.label,
  };

  const blocks: ReportBlock[] = [];

  // ── Title
  blocks.push({ type: "heading", level: 1, text: analysis.title });
  blocks.push({ type: "paragraph", text: analysis.subtitle });
  blocks.push({ type: "spacer" });

  // ── Executive Summary
  if (n?.executiveSummary) {
    blocks.push({ type: "heading", level: 2, text: "Executive Summary" });
    for (const p of n.executiveSummary.split("\n").filter(Boolean)) {
      blocks.push({ type: "paragraph", text: p });
    }
    blocks.push({ type: "spacer" });
  }

  // ── Caveats
  if (analysis.caveats.length > 0) {
    blocks.push({ type: "heading", level: 2, text: "Important Notes" });
    for (const c of analysis.caveats) {
      blocks.push({ type: "callout", severity: c.severity, title: c.title, body: c.description });
    }
    blocks.push({ type: "spacer" });
  }

  // ── Key Metrics
  if (analysis.kpis.length > 0) {
    blocks.push({ type: "heading", level: 2, text: "Key Metrics" });
    for (const kpi of analysis.kpis) {
      blocks.push({
        type: "metric_row",
        label: kpi.label,
        value: `${kpi.value}${kpi.unit ?? ""}`,
        change: kpi.change?.label,
        changeDirection: kpi.change?.direction,
        source: kpi.source,
      });
    }
    blocks.push({ type: "spacer" });
  }

  // ── Findings
  if (analysis.findings.length > 0) {
    blocks.push({ type: "heading", level: 2, text: "Findings" });
    analysis.findings.forEach((f, i) => {
      blocks.push({
        type: "finding",
        index: i + 1,
        severity: f.severity,
        title: f.title,
        description: f.description,
        evidence: f.evidence,
        impact: f.impact,
        citations: f.citations && f.citations.length > 0
          ? f.citations.map(c => c.label).join(" ")
          : undefined,
      });
    });
    blocks.push({ type: "spacer" });
  } else {
    blocks.push({ type: "heading", level: 2, text: "Findings" });
    blocks.push({ type: "paragraph", text: "No significant findings for this period. All tracked metrics are within expected ranges." });
    blocks.push({ type: "spacer" });
  }

  // ── Outlook
  if (analysis.predictions.length > 0) {
    blocks.push({ type: "heading", level: 2, text: "Outlook" });
    for (const p of analysis.predictions) {
      blocks.push({
        type: "prediction",
        metric: p.metric,
        current: p.current,
        predicted: p.predicted,
        confidence: p.confidence,
        timeframe: p.timeframe,
        basis: p.basis,
        caveat: p.caveat,
      });
    }
    blocks.push({ type: "spacer" });
  }

  // ── Recommendations
  if (analysis.recommendations.length > 0) {
    blocks.push({ type: "heading", level: 2, text: "Recommendations" });
    analysis.recommendations.forEach((r, i) => {
      blocks.push({
        type: "recommendation",
        index: i + 1,
        priority: r.priority,
        title: r.title,
        description: r.description,
        expectedImpact: r.expectedImpact,
        citations: r.citations && r.citations.length > 0
          ? r.citations.map(c => c.label).join(" ")
          : undefined,
      });
    });
    blocks.push({ type: "spacer" });
  }

  // ── Methodology
  if (n?.methodology) {
    blocks.push({ type: "heading", level: 2, text: "Methodology" });
    blocks.push({ type: "paragraph", text: n.methodology });
    blocks.push({ type: "spacer" });
  }

  // ── Data Sources
  blocks.push({ type: "heading", level: 2, text: "Data Sources" });
  for (const s of analysis.sources) {
    blocks.push({
      type: "source_row",
      label: s.label,
      status: s.status,
      recordCount: s.recordCount,
    });
  }

  // ── External Research Sources
  if (analysis.research && analysis.research.evidence.length > 0) {
    const webEvidence = analysis.research.evidence.filter(e => e.sourceUrl);
    if (webEvidence.length > 0) {
      blocks.push({ type: "heading", level: 2, text: "External Sources" });
      blocks.push({
        type: "citation_list",
        items: webEvidence.map(e => ({
          label: e.citationLabel,
          title: e.title,
          url: e.sourceUrl,
          sourceName: e.sourceName,
        })),
      });
      blocks.push({ type: "spacer" });
    }
  }

  // ── Footer
  blocks.push({ type: "divider" });
  blocks.push({ type: "footer", text: `Generated ${meta.reportDate} by ${meta.generatedBy} · ${meta.clientName} · ${meta.clientDomain}` });

  return { meta, blocks };
}

// ─── Markdown Renderer (first export format) ────────────────────────────────

export function renderToMarkdown(doc: ReportDocument): string {
  const lines: string[] = [];

  for (const block of doc.blocks) {
    switch (block.type) {
      case "heading":
        lines.push(`${"#".repeat(block.level)} ${block.text}`);
        lines.push("");
        break;
      case "paragraph":
        lines.push(block.text);
        lines.push("");
        break;
      case "callout":
        lines.push(`> **${block.severity.toUpperCase()}: ${block.title}**`);
        lines.push(`> ${block.body}`);
        lines.push("");
        break;
      case "metric_row":
        lines.push(`- **${block.label}**: ${block.value}${block.change ? ` (${block.change})` : ""} — _${block.source}_`);
        break;
      case "finding":
        lines.push(`${block.index}. **[${block.severity.toUpperCase()}] ${block.title}**${block.citations ? ` ${block.citations}` : ""}`);
        lines.push(`   ${block.description}`);
        if (block.evidence) lines.push(`   _Evidence: ${block.evidence}_`);
        if (block.impact) lines.push(`   _Impact: ${block.impact}_`);
        lines.push("");
        break;
      case "prediction":
        lines.push(`- **${block.metric}**: ${block.predicted.toLocaleString()} projected (current: ${block.current.toLocaleString()}) — ${block.confidence} confidence`);
        lines.push(`  ${block.timeframe} · ${block.basis}`);
        if (block.caveat) lines.push(`  _${block.caveat}_`);
        lines.push("");
        break;
      case "recommendation":
        lines.push(`${block.index}. **[${block.priority.toUpperCase()}] ${block.title}**${block.citations ? ` ${block.citations}` : ""}`);
        lines.push(`   ${block.description}`);
        if (block.expectedImpact) lines.push(`   Expected: ${block.expectedImpact}`);
        lines.push("");
        break;
      case "citation_list":
        for (const item of block.items) {
          lines.push(`- ${item.label} ${item.url ? `[${item.title}](${item.url})` : item.title} — ${item.sourceName}`);
        }
        lines.push("");
        break;
      case "source_row":
        lines.push(`- ${block.label}: ${block.status}${block.recordCount ? ` (${block.recordCount} records)` : ""}`);
        break;
      case "divider":
        lines.push("---");
        lines.push("");
        break;
      case "spacer":
        lines.push("");
        break;
      case "footer":
        lines.push(`_${block.text}_`);
        break;
    }
  }

  return lines.join("\n");
}
