export interface PdfAssets { fontBytes: Uint8Array }
export interface PdfBlock { text: string; size?: number; bold?: boolean; color?: string; gap?: number }
let cachedFont: Promise<Uint8Array> | undefined;
export function fontBytes(): Promise<Uint8Array> {
  return cachedFont ??= fetch('/tools-assets/fonts/NotoSans-Regular.ttf').then(async response => {
    if (!response.ok) throw new Error('PDF font unavailable');
    return new Uint8Array(await response.arrayBuffer());
  }).catch(error => { cachedFont = undefined; throw error; });
}
export async function createTextPdf(blocks: PdfBlock[], assets: PdfAssets, pageSize: 'A4' | 'Letter' = 'A4'): Promise<Uint8Array> {
  const { assertPdfTextSupported } = await import('./pdf-font');
  await assertPdfTextSupported(blocks.map(block => block.text), assets.fontBytes);
  const [{ generate }, { text }] = await Promise.all([import('@pdfme/generator'), import('@pdfme/schemas')]);
  const width = pageSize === 'Letter' ? 215.9 : 210;
  const height = pageSize === 'Letter' ? 279.4 : 297;
  // Templates and plugins are trusted code; business text is supplied only as field input.
  const schemas = blocks.map((block, index) => ({ name: `block${index}`, type: 'text', position: { x: 16, y: 16 + index * 14 }, width: width - 32, height: 10, fontName: 'NotoSans', fontSize: block.size ?? 10, lineHeight: 1.35, fontColor: block.color ?? '#171717', alignment: 'left' as const, verticalAlignment: 'top' as const, overflow: 'expand', required: false }));
  const inputs = Object.fromEntries(blocks.map((block, index) => [`block${index}`, block.text]));
  return generate({ template: { basePdf: { width, height, padding: [16, 16, 16, 16] }, schemas: [schemas] }, inputs: [inputs], plugins: { text }, options: { font: { NotoSans: { data: new Uint8Array(assets.fontBytes), fallback: true } } } });
}
export async function pngToPdf(png: Uint8Array, width: number, height: number): Promise<Uint8Array> {
  if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0 || width * height > 20_000_000) throw new Error('Image dimensions are outside the export limit');
  const { PDFDocument } = await import('@pdfme/pdf-lib');
  const doc = await PDFDocument.create(); const image = await doc.embedPng(png);
  const page = doc.addPage(width > height ? [841.89, 595.28] : [595.28, 841.89]);
  const scale = Math.min((page.getWidth() - 40) / width, (page.getHeight() - 40) / height);
  page.drawImage(image, { x: (page.getWidth() - width * scale) / 2, y: (page.getHeight() - height * scale) / 2, width: width * scale, height: height * scale });
  return doc.save();
}
