/**
 * Interactive Update Prompt (Codex-style)
 *
 * Shows a blocking interactive prompt at startup when a cached update is
 * available. Three options via list selection (per CLAUDE.md UX rules):
 *   1. Update now — runs the package manager command and exits
 *   2. Skip — dismiss for this session only
 *   3. Skip until next version — persists dismissed_version in cache
 *
 * Suppressed in non-TTY / CI environments and when the
 * `check_for_update_on_startup` machine-level setting is disabled.
 */
import { execSync } from 'node:child_process';
import { dismissVersion } from './update-check.js';
// ---------------------------------------------------------------------------
// Environment guards
// ---------------------------------------------------------------------------
/**
 * Returns true when the update prompt should be suppressed:
 * - Non-TTY stdout (piped output)
 * - CI environment (CI, GITHUB_ACTIONS, etc.)
 * - PRLT_NO_UPDATE_PROMPT=1 env var
 */
export function shouldSuppressPrompt() {
    if (!process.stdout.isTTY)
        return true;
    if (!process.stdin.isTTY)
        return true;
    // Standard CI env vars
    if (process.env.CI)
        return true;
    if (process.env.GITHUB_ACTIONS)
        return true;
    if (process.env.GITLAB_CI)
        return true;
    if (process.env.JENKINS_URL)
        return true;
    if (process.env.CIRCLECI)
        return true;
    if (process.env.BUILDKITE)
        return true;
    if (process.env.TRAVIS)
        return true;
    if (process.env.TF_BUILD)
        return true; // Azure DevOps
    // Explicit opt-out
    if (process.env.PRLT_NO_UPDATE_PROMPT === '1')
        return true;
    if (process.env.PRLT_SKIP_NEW_VERSION_CHECK === 'true')
        return true;
    // oclif compilation / test environments
    if (process.env.OCLIF_COMPILATION)
        return true;
    if (process.env.PRLT_TEST_ENV)
        return true;
    return false;
}
/**
 * Show the interactive update prompt and return the user's choice.
 *
 * ```
 * ✨ Update available! 0.3.52 → 0.3.53
 *
 * Release notes: https://github.com/chrismcdermut/proletariat/releases/latest
 *
 * › Update now (runs `brew upgrade chrismcdermut/proletariat/prlt`)
 *   Skip
 *   Skip until next version
 * ```
 */
export async function showUpdatePrompt(info) {
    const chalk = (await import('chalk')).default;
    const inquirer = (await import('inquirer')).default;
    console.log('');
    console.log(`${chalk.yellow('✨ Update available!')} ${chalk.dim(info.currentVersion)} → ${chalk.green(info.latestVersion)}`);
    console.log('');
    console.log(`Release notes: ${chalk.cyan('https://github.com/chrismcdermut/proletariat/releases/latest')}`);
    console.log('');
    const choices = [
        {
            name: `Update now (runs \`${info.updateCommand}\`)`,
            value: 'update',
        },
        {
            name: 'Skip',
            value: 'skip',
        },
        {
            name: 'Skip until next version',
            value: 'skip_version',
        },
    ];
    const { action } = await inquirer.prompt([
        {
            type: 'list',
            name: 'action',
            message: 'What would you like to do?',
            choices,
        },
    ]);
    return action;
}
// ---------------------------------------------------------------------------
// Action handlers
// ---------------------------------------------------------------------------
/**
 * Execute the update command, then exit.
 * Runs synchronously so the user sees output in real time.
 */
function executeUpdate(info) {
    console.log('');
    console.log(`Running: ${info.updateCommand}`);
    console.log('');
    try {
        execSync(info.updateCommand, {
            stdio: 'inherit',
            timeout: 120_000, // 2 minute timeout
        });
        console.log('');
        console.log('Update complete! Run your command again to use the new version.');
        process.exit(0);
    }
    catch {
        console.error('');
        console.error('Update failed. You can try running the command manually:');
        console.error(`  ${info.updateCommand}`);
        process.exit(1);
    }
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Handle the full update prompt flow:
 * 1. Check if prompt should be suppressed
 * 2. Check if an update is available (from cache)
 * 3. Show interactive prompt
 * 4. Handle the user's choice
 *
 * Returns true if the process should continue (skip/skip_version),
 * or never returns (update now → process.exit).
 */
export async function handleUpdatePrompt(info) {
    if (shouldSuppressPrompt())
        return;
    if (!info.updateAvailable)
        return;
    const action = await showUpdatePrompt(info);
    switch (action) {
        case 'update':
            executeUpdate(info);
            break; // unreachable — executeUpdate calls process.exit
        case 'skip':
            // Session-only dismiss — do nothing, just continue
            break;
        case 'skip_version':
            if (info.latestVersion) {
                dismissVersion(info.latestVersion);
            }
            break;
    }
}
//# sourceMappingURL=update-prompt.js.map