// PDF rendering driver — generates agent card and eval report PDFs
import { renderToBuffer } from '@react-pdf/renderer';
import * as fs from 'fs';
import * as path from 'path';
import { AgentCardDocument } from './agent-card/document.js';
import { EvalReportDocument } from './eval-report/document.js';
import type { AgentCardData } from './agent-card/types.js';
import type { EvalReportData } from './eval-report/document.js';

function generateFilename(prefix: string, name: string, date: string, ext: string): string {
  const cleanName = name.replace(/[^a-zA-Z0-9\s]/g, '').replace(/\s+/g, '_');
  const cleanDate = date.replace(/[^a-zA-Z0-9]/g, '_');
  return `${prefix}_${cleanName}_${cleanDate}.${ext}`;
}

export async function generateAgentCardPDF(data: AgentCardData, outputPath?: string): Promise<string> {
  const filename = outputPath || generateFilename('Indemn_Agent_Card', data.name, data.generatedDate, 'pdf');
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const buffer = await renderToBuffer(<AgentCardDocument data={data} /> as any);
  const resolvedPath = path.resolve(filename);
  fs.writeFileSync(resolvedPath, buffer);
  return resolvedPath;
}

export async function generateEvalReportPDF(data: EvalReportData, outputPath?: string): Promise<string> {
  const customerName = data.customerName;
  const filename = outputPath || generateFilename('Indemn_Evaluation', customerName, data.reportDate, 'pdf');
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const buffer = await renderToBuffer(<EvalReportDocument data={data} /> as any);
  const resolvedPath = path.resolve(filename);
  fs.writeFileSync(resolvedPath, buffer);
  return resolvedPath;
}

// Re-export types for convenience
export type { AgentCardData } from './agent-card/types.js';
export type { EvalReportData, EvalReportDataV1, EvalReportDataV2 } from './eval-report/document.js';
