import { intro, outro, spinner, note } from '@clack/prompts';
import pc from 'picocolors';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { resolve } from 'node:path';
import { renderHtmlReport, renderPdfReport } from '@ew53/seo-report';
import { loadConfig } from '../lib/config-loader.js';
export async function runReport(opts = {}) {
    console.log();
    intro(pc.bgWhite(pc.black(' seo-toolkit report ')));
    const config = await loadConfig();
    const format = opts.format ?? 'both';
    // Load audit + optional suggestions.
    const auditPath = resolve(process.cwd(), config.output.auditReport);
    const audit = JSON.parse(await readFile(auditPath, 'utf8'));
    let suggestions;
    try {
        const sPath = resolve(process.cwd(), config.output.suggestions);
        suggestions = JSON.parse(await readFile(sPath, 'utf8'));
    }
    catch {
        // No suggestions available — generate audit-only report.
    }
    const reportDir = resolve(process.cwd(), '.seo-toolkit/reports');
    await mkdir(reportDir, { recursive: true });
    const stamp = new Date().toISOString().slice(0, 10);
    const hostname = new URL(audit.siteUrl).hostname.replace(/[^a-z0-9]+/gi, '-');
    const baseName = `${hostname}-${stamp}`;
    const generated = [];
    if (format === 'html' || format === 'both') {
        const s = spinner();
        s.start('Rendering HTML report...');
        const html = renderHtmlReport({ audit, suggestions });
        const htmlPath = resolve(reportDir, `${baseName}.html`);
        await writeFile(htmlPath, html, 'utf8');
        generated.push(htmlPath);
        s.stop('HTML report ready');
    }
    if (format === 'pdf' || format === 'both') {
        const s = spinner();
        s.start('Rendering PDF (launching Chromium)...');
        try {
            const pdfPath = resolve(reportDir, `${baseName}.pdf`);
            await renderPdfReport({ audit, suggestions }, pdfPath);
            generated.push(pdfPath);
            s.stop('PDF report ready');
        }
        catch (err) {
            s.stop('PDF generation failed');
            const msg = err instanceof Error ? err.message : String(err);
            if (msg.includes('Executable doesn') || msg.includes('browser')) {
                note(`Playwright Chromium not installed.\n` +
                    `Run: ${pc.cyan('pnpm exec playwright install chromium')}\n` +
                    `Then re-run ${pc.cyan('seo-toolkit report')}.`, 'Setup needed');
            }
            else {
                throw err;
            }
        }
    }
    note(generated.map((p) => `${pc.green('✓')} ${pc.cyan(p)}`).join('\n'), 'Reports');
    outro(pc.green('Reports ready.'));
}
//# sourceMappingURL=report.js.map