/**
 * Uninstall ShortcutXL - remove generated install artifacts.
 *
 * Removes: Excel registry keys, XLL directory from PATH, Playwright browsers,
 * and generated runtime files. Preserves user-owned data under
 * ~/.shortcut/agent/ such as auth, settings, sessions, memories, skills,
 * prompts, themes, extensions, MCP/package config, and XLL user modules.
 * Does NOT uninstall Git (shared tool).
 */
import { existsSync, readdirSync, rmSync, rmdirSync } from 'fs';
import { isAbsolute, join, relative, resolve } from 'path';
import { getAgentDir, getEmbeddedPythonExe, getXllPath } from '../config.js';
import { escapePSString, header, ok, run, runPS, warn } from './install-utils.js';
const OWNED_INSTALL_ARTIFACTS = [
    'xll/ShortcutXL.xll',
    'xll/python',
    'xll/.sync-version',
    'xll/.pip-version',
    'bin/uv',
    'bin/fd',
    'bin/fd.exe',
    'bin/rg',
    'bin/rg.exe',
    // uv-managed Python install created by Shortcut preflight on macOS/Linux.
    'uv',
    'update.json',
    '.installed'
];
const EMPTY_DIR_CANDIDATES = ['xll', 'bin'];
function isWithinDir(parentDir, targetPath) {
    const parent = resolve(parentDir);
    const target = resolve(targetPath);
    const rel = relative(parent, target);
    return rel === '' || (rel !== '' && !rel.startsWith('..') && !isAbsolute(rel));
}
function removeIfInsideAgentDir(agentDir, relativePath) {
    const target = join(agentDir, relativePath);
    if (!isWithinDir(agentDir, target) || !existsSync(target)) {
        return false;
    }
    rmSync(target, { recursive: true, force: true });
    return true;
}
function removeEmptyDirIfInsideAgentDir(agentDir, relativePath) {
    const target = join(agentDir, relativePath);
    if (!isWithinDir(agentDir, target) || !existsSync(target)) {
        return false;
    }
    if (readdirSync(target).length > 0) {
        return false;
    }
    rmdirSync(target);
    return true;
}
export function removeOwnedInstallArtifacts(agentDir) {
    const result = { removed: [], failed: [] };
    for (const relativePath of OWNED_INSTALL_ARTIFACTS) {
        try {
            if (removeIfInsideAgentDir(agentDir, relativePath)) {
                result.removed.push(relativePath);
            }
        }
        catch {
            result.failed.push(relativePath);
        }
    }
    for (const relativePath of EMPTY_DIR_CANDIDATES) {
        try {
            if (removeEmptyDirIfInsideAgentDir(agentDir, relativePath)) {
                result.removed.push(relativePath);
            }
        }
        catch {
            result.failed.push(relativePath);
        }
    }
    try {
        if (existsSync(agentDir) && readdirSync(agentDir).length === 0) {
            rmdirSync(agentDir);
            result.removed.push('.');
        }
    }
    catch {
        result.failed.push('.');
    }
    return result;
}
export function runUninstall() {
    console.log();
    console.log('  Uninstalling ShortcutXL...');
    console.log('  ' + '-'.repeat(40));
    // 0. Check if Excel is running - files will be locked.
    const tasklist = run('tasklist /FI "IMAGENAME eq EXCEL.EXE" /NH');
    if (tasklist.ok && tasklist.stdout.includes('EXCEL.EXE')) {
        warn('Excel is running. Please close Excel first, then run uninstall again.');
        warn('Excel locks the XLL files - they cannot be removed while Excel is open.');
        return;
    }
    // 1. Remove the OPEN registry key that loads the XLL into Excel.
    header('Excel Registry');
    const regResult = runPS(`
    $ErrorActionPreference = 'Stop'
    $versions = @('16.0', '15.0', '14.0')
    $removed = 0

    foreach ($ver in $versions) {
      $optionsKey = "HKCU:\\Software\\Microsoft\\Office\\$ver\\Excel\\Options"
      if (-not (Test-Path $optionsKey)) { continue }

      $props = Get-ItemProperty -Path $optionsKey -ErrorAction SilentlyContinue
      if (-not $props) { continue }

      foreach ($p in $props.PSObject.Properties) {
        if ($p.Name -match '^OPEN' -and $p.Value -match 'ShortcutXL') {
          Remove-ItemProperty -Path $optionsKey -Name $p.Name -Force
          $removed++
        }
      }
    }

    Write-Output "REMOVED:$removed"
  `);
    if (regResult.ok && regResult.stdout.includes('REMOVED:')) {
        const count = parseInt(regResult.stdout.split('REMOVED:')[1], 10);
        if (count > 0) {
            ok(`Removed ${count} registry key(s).`);
        }
        else {
            ok('No registry keys found.');
        }
    }
    else {
        warn('Could not clean registry.');
    }
    // 2. Remove XLL directory from user PATH.
    header('PATH');
    const xllDir = resolve(getXllPath(), '..').replace(/\//g, '\\');
    const safeDir = escapePSString(xllDir);
    const pathResult = runPS(`
    $dir = "${safeDir}"
    $current = [Environment]::GetEnvironmentVariable('PATH', 'User')
    $entries = $current -split ';' | Where-Object {
      $_ -ne '' -and $_.TrimEnd('\\') -ne $dir.TrimEnd('\\')
    }
    $newPath = $entries -join ';'
    if ($newPath -ne $current) {
      [Environment]::SetEnvironmentVariable('PATH', $newPath, 'User')
      Write-Output 'REMOVED'
    } else {
      Write-Output 'NOT_FOUND'
    }
  `);
    if (pathResult.stdout.includes('REMOVED')) {
        ok('Removed XLL directory from PATH.');
    }
    else {
        ok('XLL directory was not on PATH.');
    }
    // 3. Uninstall Playwright browsers before deleting the embedded Python.
    header('Playwright Browsers');
    const pythonExe = getEmbeddedPythonExe();
    if (existsSync(pythonExe)) {
        const pwResult = run(`"${pythonExe}" -m playwright uninstall --all`, { timeout: 30_000 });
        if (pwResult.ok) {
            ok('Removed Playwright browsers.');
        }
        else if (pwResult.stderr.includes('No module named')) {
            ok('Playwright was not installed.');
        }
        else {
            warn('Could not remove Playwright browsers - remove manually from %LOCALAPPDATA%\\ms-playwright');
        }
    }
    else {
        ok('Embedded Python not found - skipping Playwright cleanup.');
    }
    // 4. Remove only generated install artifacts. User-owned files remain.
    header('Files');
    const agentDir = getAgentDir();
    if (existsSync(agentDir)) {
        const cleanup = removeOwnedInstallArtifacts(agentDir);
        if (cleanup.removed.length > 0) {
            ok(`Removed generated install files from ${agentDir}`);
        }
        else {
            ok('No generated install files found.');
        }
        if (cleanup.failed.length > 0) {
            warn(`Could not remove some generated files from ${agentDir} - some files may be locked.`);
        }
        ok('Preserved user data: settings, auth, sessions, memories, skills, prompts, themes, extensions, and package config.');
    }
    else {
        ok('AgentController directory already removed.');
    }
    console.log();
    ok('ShortcutXL uninstalled.');
    console.log();
}
//# sourceMappingURL=uninstall.js.map