import { Command } from 'commander';
import { resolve } from 'node:path';
import { createInterface } from 'node:readline';
import { RegistryClient, readCredentials } from '@expxagents/registry-client';
import { scanInstalledSquads, checkOutdated } from './outdated.js';
function confirm(question) {
    const rl = createInterface({ input: process.stdin, output: process.stdout });
    return new Promise((res) => {
        rl.question(question, (answer) => {
            rl.close();
            res(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
        });
    });
}
async function updateSquads(client, squads, targetDir) {
    for (const squad of squads) {
        try {
            console.log(`  Updating ${squad.fullName} ${squad.current} \u2192 ${squad.latest}...`);
            const result = await client.installWithDeps(squad.fullName, squad.latest, targetDir);
            console.log(`  \u2713 ${result.root}`);
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            console.error(`  \u2717 ${squad.fullName}: ${message}`);
        }
    }
}
export const updateCommand = new Command('update')
    .description('Update installed squads to their latest versions')
    .argument('[squad]', 'Specific squad to update (@scope/name)')
    .option('--dir <dir>', 'Squads directory', './squads')
    .option('--yes', 'Skip confirmation prompt')
    .action(async (squad, options) => {
    const squadsDir = resolve(options.dir);
    const creds = readCredentials();
    const client = new RegistryClient({
        registryUrl: creds?.registryUrl || 'https://expxagents-marketplace-production.up.railway.app',
        apiKey: creds?.apiKey,
    });
    // If specific squad provided, update just that one
    if (squad) {
        try {
            console.log(`Updating ${squad}...`);
            const result = await client.installWithDeps(squad, 'latest', squadsDir);
            console.log(`\u2713 Updated ${result.root}`);
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            console.error(`\u2717 Update failed: ${message}`);
            process.exit(1);
        }
        return;
    }
    // Otherwise: scan all, check for updates, confirm, update
    const installed = scanInstalledSquads(squadsDir);
    if (installed.length === 0) {
        console.log('No registry squads installed.');
        return;
    }
    console.log(`Checking ${installed.length} squad(s)...\n`);
    const outdated = await checkOutdated(client, installed);
    if (outdated.length === 0) {
        console.log('All squads are up to date.');
        return;
    }
    console.log('Updates available:\n');
    for (const o of outdated) {
        console.log(`  ${o.fullName}  ${o.current} \u2192 ${o.latest}`);
    }
    console.log('');
    if (!options.yes) {
        const ok = await confirm(`Update ${outdated.length} squad(s)? (y/N) `);
        if (!ok) {
            console.log('Cancelled.');
            return;
        }
    }
    console.log('');
    await updateSquads(client, outdated, squadsDir);
    console.log('\nDone.');
});
