import { intro, outro, spinner, note, log } from '@clack/prompts';
import pc from 'picocolors';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { generatePatches, pushShopifyChanges } from '@ew53/seo-patch';
import { loadConfig } from '../lib/config-loader.js';
export async function runApply(opts = {}) {
    console.log();
    intro(pc.bgMagenta(pc.black(' seo-toolkit apply ')));
    const config = await loadConfig(opts.config);
    // Load suggestions.
    const suggestionsPath = resolve(process.cwd(), config.output.suggestions);
    let suggestions;
    try {
        suggestions = JSON.parse(await readFile(suggestionsPath, 'utf8'));
    }
    catch {
        throw new Error(`No suggestions found at ${suggestionsPath}.\nRun \`seo-toolkit suggest\` first.`);
    }
    const accepted = suggestions.changes.filter((c) => c.status === 'accepted');
    if (accepted.length === 0) {
        note(`No accepted changes yet. Open ${pc.cyan('seo-toolkit dev')} and review suggestions.\n` +
            `(${suggestions.changes.length} total suggestions, all currently ${pc.dim('pending')})`, 'Nothing to apply');
        outro('Done');
        return;
    }
    log.info(`${accepted.length} accepted suggestions to apply`);
    // ─── Generate patches ──────────────────────────────────────────────────
    const s = spinner();
    s.start('Generating patches...');
    const result = await generatePatches({
        config,
        changes: accepted,
        projectRoot: process.cwd(),
        patchDir: config.output.patches,
    });
    s.stop(`Generated ${result.patches.length} patches`);
    // ─── Admin API writes (Shopify only) ───────────────────────────────────
    if (config.adapter === 'shopify' && opts.adminWrite !== false) {
        const adminToken = process.env[config.shopify?.adminApiTokenEnv ?? 'SHOPIFY_ADMIN_TOKEN'];
        const storeDomain = config.shopify?.storeDomain;
        if (adminToken && storeDomain && result.unresolved.length > 0) {
            const adminApplicable = result.unresolved.filter((c) => c.adminApiTarget);
            if (adminApplicable.length > 0) {
                const s2 = spinner();
                s2.start(`Pushing ${adminApplicable.length} changes via Shopify Admin API${opts.dryRun ? ' (dry run)' : ''}`);
                const writeRes = await pushShopifyChanges(adminApplicable, {
                    storeDomain,
                    accessToken: adminToken,
                    dryRun: opts.dryRun,
                    onProgress: (info) => {
                        s2.message(`${info.done}/${info.total} · ${info.status} · ${info.resource}`);
                    },
                });
                s2.stop(opts.dryRun
                    ? `Dry run: would push ${writeRes.pushed.length} changes`
                    : `Pushed ${writeRes.pushed.length}, ${writeRes.failed.length} failed`);
            }
        }
    }
    // ─── Summary ───────────────────────────────────────────────────────────
    note(`${pc.green('✓')} ${result.patches.length} patches in ${pc.cyan(config.output.patches)}\n` +
        `${result.unresolved.length > 0 ? `${pc.yellow('!')} ${result.unresolved.length} unresolved (manual or Admin API)` : ''}\n\n` +
        `Apply all: ${pc.cyan('git apply ' + config.output.patches + '/*.diff')}\n` +
        `Open PR:   ${pc.cyan('seo-toolkit pr')}`, 'Results');
    outro(pc.green('Patches ready.'));
}
//# sourceMappingURL=apply.js.map