import { intro, outro, spinner, note, log } from '@clack/prompts';
import pc from 'picocolors';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { generateSuggestions } from '@ew53/seo-llm';
import { loadConfig, loadPlaybook } from '../lib/config-loader.js';
export async function runSuggest(opts = {}) {
    console.log();
    intro(pc.bgYellow(pc.black(' seo-toolkit suggest ')));
    const config = await loadConfig(opts.config);
    const playbook = await loadPlaybook(config.output.playbook);
    // Load most recent audit.
    const auditPath = resolve(process.cwd(), config.output.auditReport);
    let audit;
    try {
        audit = JSON.parse(await readFile(auditPath, 'utf8'));
    }
    catch {
        throw new Error(`No audit report found at ${auditPath}.\n` +
            `Run \`seo-toolkit audit\` first.`);
    }
    log.info(`Loaded audit: ${audit.pages.length} pages, scoring ${audit.score}/100`);
    log.info(`Scope: ${pc.cyan(opts.scope ?? 'all')}`);
    const s = spinner();
    s.start('Generating suggestions...');
    const suggestions = await generateSuggestions({
        config,
        audit,
        playbook,
        scope: opts.scope,
        onProgress: (info) => {
            s.message(`${info.done}/${info.total} · ${info.field} for ${info.pageUrl.slice(-50)}`);
        },
    });
    s.stop(`Generated ${suggestions.changes.length} suggestions`);
    const outputPath = resolve(process.cwd(), config.output.suggestions);
    await mkdir(dirname(outputPath), { recursive: true });
    await writeFile(outputPath, JSON.stringify(suggestions, null, 2), 'utf8');
    note(`Suggestions: ${pc.bold(suggestions.changes.length)}\n` +
        `Model usage: ` +
        `${pc.dim('haiku')} ${suggestions.modelUsage.haiku ?? 0} · ` +
        `${pc.cyan('sonnet')} ${suggestions.modelUsage.sonnet ?? 0} · ` +
        `${pc.magenta('opus')} ${suggestions.modelUsage.opus ?? 0}\n\n` +
        `Saved to ${pc.cyan(config.output.suggestions)}`, 'Results');
    note(`${pc.cyan('seo-toolkit dev')} ${pc.dim('— review accept/reject in dashboard')}`, 'Next');
    outro(pc.green('Suggestions ready.'));
}
//# sourceMappingURL=suggest.js.map