/**
 * studiograph update
 *
 * Self-update command that checks for and installs the latest version
 * from GitHub releases or npm registry.
 */
import { Command } from 'commander';
import { intro, outro, spinner, confirm, log } from '@clack/prompts';
import { execSync, spawnSync } from 'child_process';
import { readFileSync } from 'fs';
import { join } from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
// Get current CLI version
function getCurrentVersion() {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    const pkgPath = join(__dirname, '../../../package.json');
    const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
    return pkg.version;
}
// Check npm for latest version
async function getLatestNpmVersion() {
    try {
        const result = execSync('npm view studiograph version', {
            encoding: 'utf-8',
            stdio: 'pipe',
        });
        return result.trim();
    }
    catch {
        return null;
    }
}
// Compare semantic versions
function compareVersions(v1, v2) {
    const parts1 = v1.split('.').map(Number);
    const parts2 = v2.split('.').map(Number);
    for (let i = 0; i < 3; i++) {
        if (parts1[i] > parts2[i])
            return 1;
        if (parts1[i] < parts2[i])
            return -1;
    }
    return 0;
}
// Detect package manager
function detectPackageManager() {
    // Check if we're installed globally
    try {
        const globalPath = execSync('which studiograph', { encoding: 'utf-8' }).trim();
        if (globalPath.includes('/.yarn/'))
            return 'yarn';
        if (globalPath.includes('/.pnpm/'))
            return 'pnpm';
        return 'npm';
    }
    catch {
        return 'npm';
    }
}
// Update via package manager
function updateViaPM(pm) {
    const commands = {
        npm: ['npm', 'install', '-g', 'studiograph@latest'],
        yarn: ['yarn', 'global', 'add', 'studiograph@latest'],
        pnpm: ['pnpm', 'add', '-g', 'studiograph@latest'],
    };
    try {
        const result = spawnSync(commands[pm][0], commands[pm].slice(1), {
            stdio: 'inherit',
            shell: true,
        });
        return result.status === 0;
    }
    catch {
        return false;
    }
}
export const updateCommand = new Command('update')
    .description('Check for and install the latest version of Studiograph')
    .option('--check', 'Check for updates without installing')
    .option('--force', 'Force reinstall current version')
    .action(async (options) => {
    intro('Studiograph Update');
    const s = spinner();
    s.start('Checking for updates...');
    const currentVersion = getCurrentVersion();
    const latestVersion = await getLatestNpmVersion();
    if (!latestVersion) {
        s.stop('Could not check for updates');
        log.error('Failed to fetch latest version from npm registry');
        outro('Update check failed. Try again later or update manually with:');
        console.log('  npm install -g studiograph@latest');
        process.exit(1);
    }
    s.stop();
    const comparison = compareVersions(latestVersion, currentVersion);
    if (comparison === 0 && !options.force) {
        log.success(`You're already on the latest version (v${currentVersion})`);
        outro('No update needed');
        return;
    }
    if (comparison < 0) {
        log.warn(`You're on v${currentVersion}, which is newer than npm (v${latestVersion})`);
        log.info('You may be using a development version');
        outro('No update needed');
        return;
    }
    // Update available
    log.info(`Current version: v${currentVersion}`);
    log.success(`Latest version:  v${latestVersion}`);
    if (options.check) {
        outro('Update available. Run `studiograph update` to install');
        return;
    }
    // Confirm update
    const shouldUpdate = await confirm({
        message: `Update to v${latestVersion}?`,
        initialValue: true,
    });
    if (typeof shouldUpdate === 'symbol' || !shouldUpdate) {
        outro('Update cancelled');
        return;
    }
    // Detect package manager
    const pm = detectPackageManager();
    log.info(`Detected package manager: ${pm}`);
    // Perform update
    const updateSpinner = spinner();
    updateSpinner.start(`Installing v${latestVersion} via ${pm}...`);
    const success = updateViaPM(pm);
    if (success) {
        updateSpinner.stop(`✓ Updated to v${latestVersion}`);
        // Verify new version
        const newVersion = getCurrentVersion();
        if (newVersion === latestVersion) {
            log.success('Update completed successfully!');
            outro(`Studiograph is now at v${newVersion}`);
        }
        else {
            log.warn('Update may have succeeded, but version check shows unexpected result');
            log.info('Try running `studiograph --version` to verify');
            outro('Update completed');
        }
    }
    else {
        updateSpinner.stop('Update failed');
        log.error('Failed to install update via package manager');
        outro('You can try updating manually with:');
        console.log(`  ${pm} ${pm === 'npm' ? 'install -g' : 'global add'} studiograph@latest`);
        process.exit(1);
    }
});
//# sourceMappingURL=update.js.map