import { Command } from 'commander';
import { RegistryClient, writeCredentials } from '@expxagents/registry-client';
const DEFAULT_REGISTRY = 'https://expxagents-marketplace-production.up.railway.app';
export const loginCommand = new Command('login')
    .description('Authenticate with the ExpxAgents registry')
    .option('--registry <url>', 'Registry URL', DEFAULT_REGISTRY)
    .option('--scope <scope>', 'Author scope')
    .option('--name <name>', 'Author display name')
    .option('--api-key <key>', 'Existing API key (skip registration)')
    .action(async (options) => {
    const registryUrl = options.registry;
    if (options.apiKey) {
        const client = new RegistryClient({ registryUrl, apiKey: options.apiKey });
        try {
            const { author } = await client.whoami();
            writeCredentials({ apiKey: options.apiKey, registryUrl });
            console.log(`\u2713 Logged in as @${author.scope}`);
        }
        catch {
            console.error('\u2717 Invalid API key');
            process.exit(1);
        }
        return;
    }
    if (!options.scope) {
        console.error('--scope is required for registration. Example: expxagents login --scope my-org');
        process.exit(1);
    }
    const client = new RegistryClient({ registryUrl });
    try {
        const result = await client.register(options.scope, options.name);
        writeCredentials({ apiKey: result.apiKey, registryUrl });
        console.log(`\u2713 Registered as @${result.author.scope}`);
        console.log(`  API Key: ${result.apiKey}`);
        console.log('  \u26a0 Save this key \u2014 it will not be shown again.');
    }
    catch (err) {
        console.error(`\u2717 Registration failed: ${err.message}`);
        process.exit(1);
    }
});
