import chalk from 'chalk';
import { clearXllSessionCache } from '../app/xll/session.js';
import { run } from './install-utils.js';
import { header, log, ok, promptEnter } from './preflight/utils.js';
import { ensureExcelAndXll, ensurePipPackages, ensureXllRegistry, smokeTestExcel } from './preflight/windows.js';
import { stablePythonRuntimeNeedsReset, syncXll } from './sync-xll.js';
function isExcelRunning() {
    const tasklist = run('tasklist /FI "IMAGENAME eq EXCEL.EXE" /NH');
    return tasklist.ok && tasklist.stdout.includes('EXCEL.EXE');
}
async function waitForExcelClosed(canPrompt) {
    while (isExcelRunning()) {
        if (!canPrompt) {
            console.error(chalk.red('ShortcutXL needs to upgrade its embedded Python runtime. Close Excel and restart ShortcutXL.'));
            return false;
        }
        await promptEnter('Please close Excel to complete the ShortcutXL runtime upgrade, then press Enter.');
    }
    return true;
}
/**
 * Blocking repair for installed users crossing an embedded Python ABI boundary
 * such as python312 -> python313. The normal sync path preserves site-packages,
 * but ABI upgrades must replace the stable Python tree before COM execution.
 */
export async function runWindowsPythonRuntimeUpgradeIfNeeded({ canPrompt, platform = process.platform }) {
    if (platform !== 'win32')
        return true;
    if (!stablePythonRuntimeNeedsReset())
        return true;
    header('Python Runtime Upgrade', 'Updating ShortcutXL');
    log('ShortcutXL is updating its embedded Python runtime.', 'Updating Python runtime...');
    if (!(await waitForExcelClosed(canPrompt))) {
        return false;
    }
    clearXllSessionCache();
    const syncResult = syncXll();
    if (!syncResult.xllReady || syncResult.staleLocked) {
        console.error(chalk.red('ShortcutXL could not replace its embedded Python runtime. Close Excel and retry.'));
        return false;
    }
    ok('Python runtime updated.');
    await ensurePipPackages();
    ensureXllRegistry();
    await ensureExcelAndXll();
    const smokePassed = await smokeTestExcel();
    if (!smokePassed) {
        console.error(chalk.red('ShortcutXL runtime upgrade did not pass the Excel smoke test.'));
        return false;
    }
    return true;
}
//# sourceMappingURL=windows-python-upgrade.js.map