import type { ReportDocumentV2 } from "./personal-report-contract";
import { reportChartExportSvg } from "./report-chart-export";
import { buildLongformOutline, personalReportMarkdownFilename } from "./personal-report-longform-outline";
import { chartAriaLabel, parseReportChartBlock, stripReportChartBlocks, toNorthIndianChart, type ReportChartBlock } from "./report-chart-block";
import type { ReportFactTable } from "./report-fact-table-schema";
import { factCellText, FACT_STATUS_LABELS } from "./report-fact-table-display";
import { projectOrdinaryReportMarkdown } from "./report-public-projection";
export type ReportExportBlock = Readonly<{
id: string;
group: "body" | "chart" | "table";
title: string;
text: string;
chars: number;
}>;
export type ReportExportPreset = "common" | "charts" | "tables";
export function chartBlockText(block: ReportChartBlock): string {
const chart = toNorthIndianChart(block);
return `#### ${chartAriaLabel(block.id)}\n\n${chart.houses.map(house =>
`- 第 ${house.houseNumber} 宫 · ${house.sign}:${house.occupants.join("、") || "—"}`,
).join("\n")}`;
}
function tableCell(value: ReportFactTable["rows"][number]["cells"][number]): string {
return factCellText(value).replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r?\n/g, "
");
}
function tableGrid(table: Pick): string {
if (!table.rows.length) return "";
return [
`| ${table.columns.map(tableCell).join(" | ")} |`,
`| ${table.columns.map(() => "---").join(" | ")} |`,
...table.rows.map(row => `| ${row.cells.map(tableCell).join(" | ")} |`),
].join("\n");
}
/** Same labels, precision, missing values and subtables as ReportFactTables; no provenance paths. */
export function factTableToMarkdown(group: ReportFactTable): string {
return projectOrdinaryReportMarkdown([
`## ${group.title}`,
FACT_STATUS_LABELS[group.claimStatus],
group.note,
tableGrid(group),
...(group.subtables ?? []).flatMap(table => [`### ${table.title}`, table.note, tableGrid(table)]),
].filter(Boolean).join("\n\n"));
}
export function buildReportExportBlocks({ markdown, charts = [], factTables = [] }: {
markdown: string;
charts?: ReportDocumentV2["charts"];
factTables?: readonly ReportFactTable[];
}): ReportExportBlock[] {
const projected = projectOrdinaryReportMarkdown(markdown);
const outline = buildLongformOutline(projected);
const blocks: ReportExportBlock[] = [];
function add(id: string, group: ReportExportBlock["group"], title: string, text: string) {
blocks.push({ id, group, title, text, chars: Array.from(text).length });
}
// sourcePreamble/sourceMarkdown are the outline's lossless counterparts. The reader's
// leadMarkdown also contains lifted summaries: using it here duplicates/reorders prose.
if (outline.sourcePreamble) add("body:lead", "body", "摘要", stripReportChartBlocks(outline.sourcePreamble));
for (const section of outline.sections) {
add(`body:${section.id}`, "body", section.title, stripReportChartBlocks(section.sourceMarkdown));
}
const chartIds = new Set();
for (const match of projected.matchAll(/```jyotish-chart\r?\n([\s\S]*?)```/g)) {
const block = parseReportChartBlock(match[1]);
if (!block) continue;
const occurrence = blocks.filter(item => item.group === "chart" && item.id.startsWith(`chart:${block.id}:`)).length + 1;
chartIds.add(block.id);
// Only the immediately preceding SVG belongs to this occurrence (D9 may repeat).
// The public projection has already rejected unsafe SVG; never recover raw HTML.
const preceding = projected.slice(0, match.index);
const svg = preceding.match(/(