import { intro, outro, text, select, multiselect, confirm, isCancel, cancel, spinner, note, group, } from '@clack/prompts';
import pc from 'picocolors';
import { writeFile, readFile, mkdir, access } from 'node:fs/promises';
import { resolve, dirname } from 'node:path';
import { generatePlaybook } from '@ew53/seo-core';
export async function runInit(opts = {}) {
    console.log();
    intro(pc.bgMagenta(pc.black(' @ew53/seo-toolkit ')));
    const configPath = resolve(process.cwd(), 'seo.config.ts');
    const playbookPath = resolve(process.cwd(), 'SEO_PLAYBOOK.md');
    if (!opts.force) {
        const exists = await fileExists(configPath);
        if (exists) {
            const overwrite = await confirm({
                message: 'seo.config.ts already exists. Overwrite?',
                initialValue: false,
            });
            if (isCancel(overwrite) || !overwrite) {
                cancel('Init cancelled.');
                process.exit(0);
            }
        }
    }
    note(`This will create ${pc.cyan('seo.config.ts')} and ${pc.cyan('SEO_PLAYBOOK.md')}.\n` +
        `Takes about 2 minutes. Answers tune the LLM suggestions to your client's brand.`, 'Setup');
    // ─── Group of questions, fully type-safe ─────────────────────────────────
    const answers = await group({
        siteName: () => text({
            message: 'Client/site name',
            placeholder: 'Acme Coffee Co.',
            validate: (v) => (v.length < 2 ? 'Name is required' : undefined),
        }),
        siteUrl: () => text({
            message: 'Site URL',
            placeholder: 'https://acmecoffee.com',
            validate: (v) => {
                try {
                    new URL(v);
                    return undefined;
                }
                catch {
                    return 'Must be a valid URL (with https://)';
                }
            },
        }),
        adapter: () => select({
            message: 'What type of site is this?',
            options: [
                { value: 'shopify', label: 'Shopify', hint: 'theme + Admin API' },
                { value: 'react', label: 'React/custom', hint: 'Next, Vite, Astro, Remix, etc.' },
                { value: 'generic', label: 'Generic / unknown', hint: 'crawl-only mode' },
            ],
            initialValue: 'shopify',
        }),
        framework: ({ results }) => {
            if (results.adapter !== 'react')
                return Promise.resolve('next');
            return select({
                message: 'Which framework?',
                options: [
                    { value: 'next', label: 'Next.js' },
                    { value: 'vite', label: 'Vite + React' },
                    { value: 'astro', label: 'Astro' },
                    { value: 'remix', label: 'Remix' },
                    { value: 'gatsby', label: 'Gatsby' },
                    { value: 'other', label: 'Other' },
                ],
                initialValue: 'next',
            });
        },
        shopifyDomain: ({ results }) => {
            if (results.adapter !== 'shopify')
                return Promise.resolve(undefined);
            return text({
                message: 'Shopify store domain (optional, for Admin API)',
                placeholder: 'acmecoffee.myshopify.com',
            });
        },
        goal: () => select({
            message: 'Primary business goal?',
            options: [
                { value: 'ecommerce', label: 'E-commerce sales' },
                { value: 'lead-gen', label: 'Lead generation' },
                { value: 'content-traffic', label: 'Content/SEO traffic' },
                { value: 'brand-awareness', label: 'Brand awareness' },
                { value: 'mixed', label: 'Mixed / multiple' },
            ],
            initialValue: 'ecommerce',
        }),
        industry: () => text({
            message: 'Industry (optional, helps LLM context)',
            placeholder: 'e.g. specialty coffee, B2B SaaS, fashion',
            defaultValue: '',
        }),
        targetMarkets: () => multiselect({
            message: 'Target markets (space to toggle, enter to confirm)',
            options: [
                { value: 'Global', label: 'Global' },
                { value: 'US', label: 'United States' },
                { value: 'UK', label: 'United Kingdom' },
                { value: 'EU', label: 'Europe' },
                { value: 'SEA', label: 'Southeast Asia' },
                { value: 'APAC', label: 'Asia-Pacific' },
                { value: 'LATAM', label: 'Latin America' },
                { value: 'MEA', label: 'Middle East & Africa' },
            ],
            initialValues: ['Global'],
            required: true,
        }),
        primaryLanguage: () => select({
            message: 'Primary content language',
            options: [
                { value: 'en', label: 'English' },
                { value: 'zh', label: 'Chinese (Mandarin)' },
                { value: 'ms', label: 'Malay' },
                { value: 'es', label: 'Spanish' },
                { value: 'fr', label: 'French' },
                { value: 'de', label: 'German' },
                { value: 'ja', label: 'Japanese' },
                { value: 'other', label: 'Other (edit config after)' },
            ],
            initialValue: 'en',
        }),
        voice: () => select({
            message: 'Brand voice for meta descriptions and rewrites',
            options: [
                { value: 'professional', label: 'Professional', hint: 'corporate, trustworthy' },
                { value: 'casual', label: 'Casual', hint: 'conversational, approachable' },
                { value: 'playful', label: 'Playful', hint: 'witty, energetic' },
                { value: 'luxury', label: 'Luxury', hint: 'refined, aspirational' },
                { value: 'technical', label: 'Technical', hint: 'precise, detail-oriented' },
                { value: 'friendly', label: 'Friendly', hint: 'warm, helpful' },
            ],
            initialValue: 'professional',
        }),
        voiceNotes: () => text({
            message: 'Voice notes — anything specific? (optional)',
            placeholder: "e.g. 'use 'we' not 'our team', no exclamation marks'",
            defaultValue: '',
        }),
        avoidWords: () => text({
            message: 'Words to avoid (comma-separated, optional)',
            placeholder: 'e.g. cheap, basic, simple',
            defaultValue: '',
        }),
        primaryKeywords: () => text({
            message: 'Top 3-5 primary keywords (comma-separated)',
            placeholder: 'e.g. specialty coffee beans, single origin coffee, espresso roast',
            validate: (v) => (v.trim().length < 3 ? 'Add at least one keyword' : undefined),
        }),
        secondaryKeywords: () => text({
            message: 'Secondary keywords (comma-separated, optional)',
            placeholder: 'long-tail variants',
            defaultValue: '',
        }),
        competitors: () => text({
            message: 'Competitor URLs (comma-separated, optional)',
            placeholder: 'https://blueBottle.com, https://stumptown.com',
            defaultValue: '',
        }),
        aggressiveness: () => select({
            message: 'How aggressively should the LLM rewrite copy?',
            options: [
                {
                    value: 'conservative',
                    label: 'Conservative',
                    hint: 'only fix obvious issues, preserve existing copy',
                },
                {
                    value: 'balanced',
                    label: 'Balanced',
                    hint: 'fix issues + rewrite weak copy — recommended',
                },
                {
                    value: 'aggressive',
                    label: 'Aggressive',
                    hint: 'rewrite freely to maximize SEO',
                },
            ],
            initialValue: 'balanced',
        }),
        gscEnabled: () => confirm({
            message: 'Connect Google Search Console? (you can do this later)',
            initialValue: false,
        }),
        pagespeedEnabled: () => confirm({
            message: 'Enable PageSpeed Insights API for Core Web Vitals?',
            initialValue: true,
        }),
    }, {
        onCancel: () => {
            cancel('Setup cancelled.');
            process.exit(0);
        },
    });
    // ─── Build the config object ────────────────────────────────────────────
    const config = {
        version: 1,
        siteName: answers.siteName,
        siteUrl: answers.siteUrl,
        adapter: answers.adapter,
        business: {
            goal: answers.goal,
            industry: answers.industry || undefined,
            targetMarkets: answers.targetMarkets,
            primaryLanguage: answers.primaryLanguage,
            additionalLanguages: [],
        },
        brand: {
            voice: answers.voice,
            voiceNotes: answers.voiceNotes || undefined,
            avoidWords: splitCsv(answers.avoidWords),
        },
        targeting: {
            primaryKeywords: splitCsv(answers.primaryKeywords),
            secondaryKeywords: splitCsv(answers.secondaryKeywords),
            competitors: splitCsv(answers.competitors).filter((c) => {
                try {
                    new URL(c);
                    return true;
                }
                catch {
                    return false;
                }
            }),
        },
        aggressiveness: answers.aggressiveness,
        llm: {
            bulkModel: 'claude-sonnet-4-6',
            heavyModel: 'claude-opus-4-7',
            classifyModel: 'claude-haiku-4-5',
            apiKeyEnv: 'ANTHROPIC_API_KEY',
        },
        shopify: answers.adapter === 'shopify'
            ? {
                storeDomain: answers.shopifyDomain || undefined,
                adminApiTokenEnv: 'SHOPIFY_ADMIN_TOKEN',
            }
            : undefined,
        react: answers.adapter === 'react'
            ? {
                framework: answers.framework,
                projectPath: '.',
                pageGlobs: ['app/**/page.{tsx,jsx}', 'pages/**/*.{tsx,jsx}'],
            }
            : undefined,
        integrations: {
            googleSearchConsole: { enabled: answers.gscEnabled },
            pageSpeedInsights: {
                enabled: answers.pagespeedEnabled,
                apiKeyEnv: 'PAGESPEED_API_KEY',
            },
        },
        output: {
            auditReport: '.seo-toolkit/audit-report.json',
            suggestions: '.seo-toolkit/suggested-changes.json',
            patches: '.seo-toolkit/patches',
            playbook: 'SEO_PLAYBOOK.md',
        },
        urls: [],
        dashboard: { port: 4001 },
    };
    // ─── Write files ────────────────────────────────────────────────────────
    const s = spinner();
    s.start('Writing config and playbook');
    await mkdir(dirname(configPath), { recursive: true });
    await writeFile(configPath, renderConfigFile(config), 'utf8');
    await writeFile(playbookPath, generatePlaybook(config), 'utf8');
    await mkdir(resolve(process.cwd(), '.seo-toolkit'), { recursive: true });
    s.stop('Wrote config and playbook ✓');
    // Auto-inject "seo" script into package.json
    let addedSeoScript = false;
    const pkgPath = resolve(process.cwd(), 'package.json');
    if (await fileExists(pkgPath)) {
        try {
            const raw = await readFile(pkgPath, 'utf8');
            const pkg = JSON.parse(raw);
            if (!pkg.scripts?.seo) {
                pkg.scripts = pkg.scripts ?? {};
                pkg.scripts.seo = 'seo-toolkit';
                await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf8');
                addedSeoScript = true;
            }
        }
        catch {
            // non-fatal — user can add it manually
        }
    }
    note(`${pc.green('✓')} ${pc.cyan('seo.config.ts')}\n` +
        `${pc.green('✓')} ${pc.cyan('SEO_PLAYBOOK.md')}\n` +
        `${pc.green('✓')} ${pc.cyan('.seo-toolkit/')} (output dir)\n` +
        (addedSeoScript ? `${pc.green('✓')} ${pc.cyan('package.json')} ${pc.dim('— added "seo" script')}` : `${pc.dim('ℹ "seo" script already in package.json')}`), 'Created');
    note(`Run these now:\n\n` +
        `  ${pc.bgCyan(pc.black(' 1 '))} ${pc.cyan('npm run seo audit')}    ${pc.dim('— crawl your site and find SEO issues')}\n` +
        `  ${pc.bgCyan(pc.black(' 2 '))} ${pc.cyan('npm run seo dev')}      ${pc.dim('— open the dashboard at localhost:4001')}\n\n` +
        `Then in the dashboard:\n` +
        `  • Click ${pc.bold('Suggest fixes')} to generate AI-powered fixes\n` +
        `  • Review and accept suggestions\n` +
        `  • Click ${pc.bold('Fix')} to apply them to your source code\n` +
        `  • Click ${pc.bold('Report')} to export a PDF/HTML client report`, 'What to do next');
    outro(pc.green('Setup complete — run: npm run seo audit'));
}
function splitCsv(value) {
    if (!value)
        return [];
    return value
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);
}
async function fileExists(path) {
    try {
        await access(path);
        return true;
    }
    catch {
        return false;
    }
}
/**
 * Render the config as a TypeScript file using defineConfig().
 * We hand-format for readability rather than using JSON.stringify.
 */
function renderConfigFile(config) {
    return `import { defineConfig } from '@ew53/seo-core';

/**
 * SEO toolkit config for ${config.siteName}.
 * Generated by \`seo-toolkit init\`. Edit freely.
 *
 * Run \`seo-toolkit dev\` to open the dashboard.
 */
export default defineConfig(${JSON.stringify(config, null, 2)});
`;
}
//# sourceMappingURL=init.js.map