// cli/commands/activate.ts — planu activate <key>: add/update license in all installed configs (SPEC-237)
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { bold, green, yellow, dim, cyan } from '../colors.js';
import { activateLicense } from '../../engine/license-validator.js';
// ---------------------------------------------------------------------------
// Constants — same paths as install.ts
// ---------------------------------------------------------------------------
const PLANU_KEY = 'planu';
function buildTargets() {
    const home = homedir();
    return [
        {
            name: 'Claude Code',
            path: join(home, '.claude.json'),
            format: 'standard',
        },
        {
            name: 'Cursor',
            path: join(home, '.cursor', 'mcp.json'),
            format: 'standard',
        },
        {
            name: 'Windsurf',
            path: join(home, '.codeium', 'windsurf', 'mcp_config.json'),
            format: 'standard',
        },
        {
            name: 'Zed',
            path: join(home, '.config', 'zed', 'settings.json'),
            format: 'zed',
        },
        {
            name: 'Cline',
            path: join(home, '.vscode', 'globalStorage', 'saoudrizwan.claude-dev', 'settings', 'cline_mcp_settings.json'),
            format: 'standard',
        },
        {
            name: 'Continue',
            path: join(home, '.continue', 'config.json'),
            format: 'standard',
        },
    ];
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function readJson(filePath) {
    if (!existsSync(filePath)) {
        return null;
    }
    const raw = readFileSync(filePath, 'utf-8').trim();
    if (!raw) {
        return null;
    }
    return JSON.parse(raw);
}
function hasPlanu(config, format) {
    if (format === 'zed') {
        const zed = config;
        return Boolean(zed.context_servers?.[PLANU_KEY]);
    }
    const std = config;
    return Boolean(std.mcpServers?.[PLANU_KEY]);
}
function updateStandardToken(filePath, licenseKey) {
    const parsed = readJson(filePath);
    if (!parsed) {
        return;
    }
    const raw = parsed;
    const entry = raw.mcpServers?.[PLANU_KEY];
    if (!entry) {
        return;
    }
    entry.env = { ...(entry.env ?? {}), SDD_OWNER_TOKEN: licenseKey };
    writeFileSync(filePath, JSON.stringify(raw, null, 2) + '\n', 'utf-8');
}
function updateZedToken(filePath, licenseKey) {
    const parsed = readJson(filePath);
    if (!parsed) {
        return;
    }
    const raw = parsed;
    const entry = raw.context_servers?.[PLANU_KEY];
    if (!entry) {
        return;
    }
    entry.env = { ...(entry.env ?? {}), SDD_OWNER_TOKEN: licenseKey };
    writeFileSync(filePath, JSON.stringify(raw, null, 2) + '\n', 'utf-8');
}
// Exported for tests
export { buildTargets, hasPlanu, updateStandardToken, updateZedToken };
// ---------------------------------------------------------------------------
// Command
// ---------------------------------------------------------------------------
export const activateCommand = {
    name: 'activate',
    description: 'Activate a Pro license key in all installed Planu configs',
    usage: 'planu activate <license-key>',
    async run(args, _flags) {
        const licenseKey = args[0];
        if (!licenseKey) {
            process.stderr.write(`${yellow('!')} Usage: planu activate <license-key>\n` +
                `Example: planu activate PLN-XXXX-XXXX-XXXX\n`);
            process.exitCode = 1;
            return;
        }
        process.stdout.write(`\n${bold('Planu License Activation')}\n\n`);
        process.stdout.write(`${dim('Validating license key...')}\n`);
        // Validate key via license API
        let customerEmail;
        let variantName;
        try {
            const result = await activateLicense(licenseKey, 'planu-cli');
            if (!result.activated) {
                const errMsg = result.error ?? 'Invalid license key';
                process.stderr.write(`${yellow('!')} License validation failed: ${errMsg}\n`);
                process.exitCode = 1;
                return;
            }
            customerEmail = result.meta.customer_email;
            variantName = result.meta.variant_name;
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            process.stderr.write(`${yellow('!')} License API error: ${msg}\n`);
            process.exitCode = 1;
            return;
        }
        process.stdout.write(`${green('+')} ${variantName} license — ${customerEmail}\n\n`);
        process.stdout.write(`${cyan('Updating Planu configs:')}\n`);
        const targets = buildTargets();
        let updated = 0;
        for (const target of targets) {
            let config;
            try {
                config = readJson(target.path);
            }
            catch {
                process.stdout.write(`  ${yellow('!')} ${target.name}: could not read config\n`);
                continue;
            }
            if (config === null || !hasPlanu(config, target.format)) {
                process.stdout.write(`  ${dim('\u25a1')} ${target.name} — Planu not installed here\n`);
                continue;
            }
            try {
                if (target.format === 'zed') {
                    updateZedToken(target.path, licenseKey);
                }
                else {
                    updateStandardToken(target.path, licenseKey);
                }
                process.stdout.write(`  ${green('+')} ${target.name} — updated\n`);
                updated++;
            }
            catch (err) {
                const msg = err instanceof Error ? err.message : String(err);
                process.stdout.write(`  ${yellow('!')} ${target.name}: failed to write — ${msg}\n`);
            }
        }
        process.stdout.write('\n');
        if (updated === 0) {
            process.stdout.write(`${yellow('!')} Planu is not installed in any tool. Run ${cyan('planu install')} first.\n\n`);
            process.exitCode = 1;
            return;
        }
        process.stdout.write(`${green('+')} License activated in ${String(updated)} config(s). ` +
            `${dim('Restart your AI tools to apply.')}\n\n`);
    },
};
//# sourceMappingURL=activate.js.map