import { PDFDocument } from 'pdf-lib' import type { Report } from '@/domain/schema/report' import type { SpeciesFindings } from '@/domain/schema/findings' import type { Locale } from '@/i18n/types' import { getDict } from '@/i18n' import { embedFonts } from './fonts' import { addObservationPage } from './render/observationPage' import { addConclusionPage } from './render/conclusionPage' import { attachReportJson } from './attachment' import { drawFooter } from './render/footer' import { loadFaunosteoLogo, loadFaunosteoComLogo, loadZenqualityLogo } from './render/logo' import { loadSvg } from '@/anatomy/svgLoader' import { parseSvgBones } from '@/anatomy/svgConvention' import { getSpecies } from '@/domain/species/registry' export interface PdfExportOptions { locale: Locale } /** Bilingual label pair surfaced to the PDF render layer. */ export interface ZoneLabelPair { fr: string en: string } /** * Builds a `data-anno-id → { fr, en }` map by parsing every SVG the * species manifest knows about. Each SVG is loaded independently so a * failure on the detail asset never prevents the main labels (or vice * versa) from making it into the returned map. The PDF render layer * picks the locale-appropriate label at draw time (falls back to the * opposite language when one side is missing). * * Exported for unit testing — the editor calls it indirectly via * `exportReportToPdf`. */ export async function buildZoneLabels( report: Report, ): Promise> { const labels = new Map() const species = getSpecies(report.animal.speciesId) if (!species) return labels const sources: string[] = [ species.mainSvg, ...Object.values(species.details), ] await Promise.all( sources.map(async (src) => { try { const root = await loadSvg(src) parseSvgBones(root).forEach((b, id) => { const existing = labels.get(id) if (existing) { if (!existing.fr && b.fr) existing.fr = b.fr if (!existing.en && b.en) existing.en = b.en } else if (b.fr || b.en) { labels.set(id, { fr: b.fr, en: b.en }) } }) } catch (err) { console.warn(`buildZoneLabels: skipped ${src}`, err) } }), ) return labels } /** * Loads the parsed findings catalog for a species so the PDF renderer * can resolve a Finding's `zoneId` (JSON catalog key) back to its * human-readable zone name. */ async function loadSpeciesFindings( speciesId: string, ): Promise { const species = getSpecies(speciesId) if (!species) return null try { const m = await species.findings() return m.default } catch (err) { console.warn(`loadSpeciesFindings: failed for ${speciesId}`, err) return null } } export async function exportReportToPdf( report: Report, opts: PdfExportOptions, ): Promise { const { locale } = opts const dict = getDict(locale) const pdfDoc = await PDFDocument.create() pdfDoc.setTitle(`${dict['pdf.title.suffix.bilan']}${report.animal.name}`) pdfDoc.setAuthor(report.practitioner.name) pdfDoc.setSubject(dict['pdf.subject']) pdfDoc.setCreationDate(new Date()) pdfDoc.setModificationDate(new Date()) const fonts = await embedFonts(pdfDoc) const zoneLabels = await buildZoneLabels(report) const findingsTree = await loadSpeciesFindings(report.animal.speciesId) let headerLogoPdf = null let footerLogoPdf = null let zqLogoPdfImage = null try { const bytes = await loadFaunosteoLogo() headerLogoPdf = await pdfDoc.embedPng(bytes) } catch (err) { console.warn('Faunosteo logo embed failed:', err) } try { const bytes = await loadFaunosteoComLogo() footerLogoPdf = await pdfDoc.embedPng(bytes) } catch (err) { console.warn('Faunosteo -com logo embed failed:', err) } try { const zqPngBytes = await loadZenqualityLogo() zqLogoPdfImage = await pdfDoc.embedPng(zqPngBytes) } catch (err) { console.warn('ZenQuality logo embed failed:', err) } const headerAssets = { logoPng: headerLogoPdf } const totalObs = report.observations.length for (let i = 0; i < totalObs; i += 1) { await addObservationPage( pdfDoc, report, report.observations[i], i, fonts, zoneLabels, findingsTree, locale, headerAssets, ) } await addConclusionPage(pdfDoc, report, fonts, locale, headerAssets) const pages = pdfDoc.getPages() const footerAssets = { logoPng: footerLogoPdf, zqLogoPng: zqLogoPdfImage } pages.forEach((page, idx) => { drawFooter(page, fonts, idx + 1, pages.length, locale, footerAssets) }) await attachReportJson(pdfDoc, report) return pdfDoc.save() }