import { intro, outro, spinner, note, log } from '@clack/prompts';
import pc from 'picocolors';
import { writeFile, mkdir } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { shopifyAudit } from '@ew53/seo-adapter-shopify';
import { reactAudit } from '@ew53/seo-adapter-react';
import { genericAudit } from '@ew53/seo-adapter-generic';
import { loadConfig } from '../lib/config-loader.js';
export async function runAudit(opts = {}) {
    console.log();
    intro(pc.bgBlue(pc.black(' seo-toolkit audit ')));
    const config = await loadConfig(opts.config);
    log.info(`Auditing ${pc.cyan(config.siteUrl)} via ${pc.cyan(config.adapter)} adapter`);
    const limit = Number(opts.limit ?? 200);
    const s = spinner();
    s.start('Crawling...');
    let progressLine = '';
    const onProgress = (info) => {
        if (info.phase === 'admin') {
            s.message(`Admin API: fetched ${info.count} ${info.resource}`);
            return;
        }
        if (info.crawled !== undefined) {
            progressLine = `${info.crawled}/${info.total ?? '?'} crawled · ${info.url ?? ''}`;
            s.message(progressLine);
        }
    };
    const extraUrls = config.urls.length > 0 ? config.urls : undefined;
    if (extraUrls) {
        log.info(`Seeding ${extraUrls.length} extra URL(s) from config.urls`);
    }
    let report;
    try {
        if (config.adapter === 'shopify') {
            const adminToken = process.env[config.shopify?.adminApiTokenEnv ?? 'SHOPIFY_ADMIN_TOKEN'];
            if (!adminToken) {
                s.message('Crawling (no Admin token set — crawl-only mode)');
            }
            report = await shopifyAudit({
                config,
                adminToken,
                crawl: { limit, extraUrls },
                onProgress,
            });
        }
        else if (config.adapter === 'react') {
            report = await reactAudit({ config, crawl: { limit, extraUrls }, onProgress });
        }
        else {
            report = await genericAudit({ config, crawl: { limit, extraUrls }, onProgress });
        }
        s.stop(`Crawled ${report.pages.length} pages`);
    }
    catch (err) {
        s.stop('Crawl failed');
        throw err;
    }
    // Write report.
    const outputPath = resolve(process.cwd(), config.output.auditReport);
    await mkdir(dirname(outputPath), { recursive: true });
    await writeFile(outputPath, JSON.stringify(report, null, 2), 'utf8');
    const totalIssues = Object.values(report.summary).reduce((a, b) => a + b, 0);
    note(`Score: ${pc.bold(`${report.score}/100`)}\n` +
        `Issues: ${pc.red(report.summary.critical)} critical · ` +
        `${pc.yellow(report.summary.high)} high · ` +
        `${pc.cyan(report.summary.medium)} medium · ` +
        `${pc.dim(report.summary.low)} low\n` +
        `Total: ${totalIssues} issues across ${report.pages.length} pages\n\n` +
        `Saved to ${pc.cyan(config.output.auditReport)}`, 'Results');
    note(`${pc.cyan('seo-toolkit suggest')}  ${pc.dim('— LLM generates fix suggestions')}\n` +
        `${pc.cyan('seo-toolkit dev')}      ${pc.dim('— review in dashboard')}`, 'Next');
    outro(pc.green('Audit complete.'));
}
//# sourceMappingURL=audit.js.map