# GitLink CLI Windows 卸载脚本
# 用法: powershell -NoProfile -ExecutionPolicy Bypass -File uninstall.ps1

param(
    [switch]$Purge,
    [switch]$Yes,
    [switch]$Help
)

$ErrorActionPreference = "Stop"

# ---------- 工具函数 ----------
function Info-Message {
    param([string]$Message)
    Write-Host "[INFO]  $Message" -ForegroundColor Green
}

function Warn-Message {
    param([string]$Message)
    Write-Host "[WARN]  $Message" -ForegroundColor Yellow
}

function Error-Message {
    param([string]$Message)
    Write-Host "[ERROR] $Message" -ForegroundColor Red
}

function Step-Message {
    param([string]$Message)
    Write-Host "[STEP]  $Message" -ForegroundColor Cyan
}

function Ask-Question {
    param([string]$Question)
    Write-Host "[ASK]   $Question" -ForegroundColor Blue
}

# ---------- 显示帮助 ----------
if ($Help) {
    Write-Host ""
    Write-Host "GitLink CLI Windows 卸载脚本"
    Write-Host ""
    Write-Host "用法: powershell -NoProfile -ExecutionPolicy Bypass -File uninstall.ps1 [选项]"
    Write-Host ""
    Write-Host "选项:"
    Write-Host "  -Purge   删除所有文件（包括配置）"
    Write-Host "  -Yes     自动确认，不询问"
    Write-Host "  -Help    显示此帮助"
    Write-Host ""
    Write-Host "示例:"
    Write-Host "  .\uninstall.ps1           # 交互式卸载"
    Write-Host "  .\uninstall.ps1 -Purge    # 完全删除"
    Write-Host "  .\uninstall.ps1 -Yes      # 自动确认"
    exit 0
}

# ---------- 查找二进制文件 ----------
function Find-Binary {
    Step-Message "查找 gitlink-cli 二进制文件..."

    $possibleDirs = @(
        "$env:USERPROFILE\.gitlink-cli\bin",
        "$env:USERPROFILE\.local\bin",
        "$env:USERPROFILE\scoop\shims",
        "$env:ChocolateyInstall\bin",
        "$env:USERPROFILE\go\bin"
    )

    foreach ($dir in $possibleDirs) {
        $binaryPath = Join-Path $dir "gitlink-cli.exe"
        if (Test-Path $binaryPath) {
            $script:InstallDir = $dir
            Info-Message "找到安装目录: $dir"
            return $true
        }
    }

    # 检查PATH
    if (Get-Command "gitlink-cli" -ErrorAction SilentlyContinue) {
        $script:InstallDir = Split-Path (Get-Command "gitlink-cli").Source -Parent
        Info-Message "通过PATH找到安装目录: $script:InstallDir"
        return $true
    }

    Warn-Message "未找到 gitlink-cli 二进制文件"
    return $false
}

# ---------- 检查安装状态 ----------
function Test-InstallationStatus {
    Step-Message "检查安装状态..."

    $foundItems = @()

    if ($script:InstallDir -and (Test-Path (Join-Path $script:InstallDir "gitlink-cli.exe"))) {
        $foundItems += "二进制文件: $($script:InstallDir)\gitlink-cli.exe"
    }

    if (Test-Path "$env:USERPROFILE\.gitlink\skills") {
        $foundItems += "Skills: $env:USERPROFILE\.gitlink\skills"
    }

    if (Test-Path "$env:USERPROFILE\.gitlink-cli") {
        $foundItems += "配置: $env:USERPROFILE\.gitlink-cli"
    }

    if (Test-Path "$env:USERPROFILE\.gitlink") {
        $foundItems += "GitLink数据: $env:USERPROFILE\.gitlink"
    }

    # 检查npm
    try {
        $null = npm list -g @gitlink-ai/cli 2>&1 | Select-String "@gitlink-ai/cli"
        if ($?) {
            $foundItems += "npm包: @gitlink-ai/cli (全局)"
        }
    } catch {
        # npm未安装或包未安装
    }

    if ($foundItems.Count -eq 0) {
        Warn-Message "未检测到 gitlink-cli 安装"
        return $false
    }

    Info-Message "检测到以下组件:"
    foreach ($item in $foundItems) {
        Write-Host "  - $item"
    }

    return $true
}

# ---------- 删除二进制 ----------
function Remove-Binary {
    if (-not $script:InstallDir) {
        Warn-Message "跳过二进制删除（未找到安装目录）"
        return
    }

    Step-Message "删除二进制文件..."
    $binaryPath = Join-Path $script:InstallDir "gitlink-cli.exe"

    if (-not (Test-Path $binaryPath)) {
        Warn-Message "二进制文件不存在: $binaryPath"
        return
    }

    try {
        Remove-Item $binaryPath -Force
        Info-Message "已删除: $binaryPath"
    } catch {
        Error-Message "删除失败: $_"
        Error-Message "请手动删除: $binaryPath"
        throw
    }
}

# ---------- 删除Skills ----------
function Remove-Skills {
    Step-Message "删除 Skills..."

    $skillsPath = "$env:USERPROFILE\.gitlink\skills"
    if (-not (Test-Path $skillsPath)) {
        Warn-Message "Skills目录不存在: $skillsPath"
        return
    }

    try {
        $skillCount = (Get-ChildItem $skillsPath -Directory).Count
        Info-Message "找到 $skillCount 个Skills"

        Remove-Item $skillsPath -Recurse -Force
        Info-Message "已删除Skills"
    } catch {
        Error-Message "删除Skills失败: $_"
    }
}

# ---------- 删除配置 ----------
function Remove-Config {
    if ($Purge) {
        Step-Message "删除配置文件（--purge模式）..."
    } else {
        if (-not $Yes) {
            Ask-Question "是否删除配置文件和数据? [y/N] "
            $response = Read-Host
            if ($response -ne 'y' -and $response -ne 'Y') {
                Info-Message "保留配置文件"
                return
            }
        }
        Step-Message "删除配置文件..."
    }

    $configPaths = @(
        "$env:USERPROFILE\.gitlink-cli",
        "$env:USERPROFILE\.gitlink"
    )

    foreach ($path in $configPaths) {
        if (Test-Path $path) {
            try {
                Info-Message "删除: $path"
                Remove-Item $path -Recurse -Force
            } catch {
                Warn-Message "删除失败 $path : $_"
            }
        }
    }

    Info-Message "配置文件已删除"
}

# ---------- 卸载npm包 ----------
function Uninstall-Npm {
    try {
        $null = npm list -g @gitlink-ai/cli 2>&1 | Select-String "@gitlink-ai/cli"
        if (-not $?) {
            return
        }
    } catch {
        return
    }

    Step-Message "卸载npm包..."

    if ($Yes) {
        $response = 'y'
    } else {
        Ask-Question "检测到npm全局安装的 gitlink-cli，是否卸载? [y/N] "
        $response = Read-Host
    }

    if ($response -eq 'y' -or $response -eq 'Y') {
        try {
            npm uninstall -g @gitlink-ai/cli | Out-Null
            Info-Message "npm包已卸载"
        } catch {
            Warn-Message "npm包卸载失败，请手动执行: npm uninstall -g @gitlink-ai/cli"
        }
    } else {
        Info-Message "保留npm包"
    }
}

# ---------- 显示卸载摘要 ----------
function Show-Summary {
    Write-Host ""
    Write-Host "========================================"
    Info-Message "卸载完成！"
    Write-Host "========================================"
    Write-Host ""

    if ($Purge) {
        Warn-Message "已完全删除所有文件（包括配置）"
    } else {
        Info-Message "以下文件可能需要手动清理:"
        Write-Host "  - $env:USERPROFILE\.gitlink-cli"
        Write-Host "  - $env:USERPROFILE\.gitlink"
        Write-Host ""
        Info-Message "如需删除，请重新运行: .\uninstall.ps1 -Purge"
    }

    Write-Host ""
    Info-Message "感谢使用 GitLink CLI！"
    Info-Message "如有任何问题，请访问: https://www.gitlink.org.cn/Gitlink/gitlink-cli/issues"
    Write-Host ""
}

# ---------- 确认卸载 ----------
function Confirm-Uninstall {
    if ($Yes) {
        return
    }

    Write-Host ""
    Warn-Message "即将卸载 gitlink-cli 及相关文件"
    Ask-Question "确认继续? [y/N] "
    $response = Read-Host

    if ($response -ne 'y' -and $response -ne 'Y') {
        Info-Message "取消卸载"
        exit 0
    }
}

# ---------- 主流程 ----------
function Main {
    # 欢迎信息
    Write-Host ""
    Write-Host "========================================"
    Write-Host "  GitLink CLI 一键卸载 (Windows)"
    Write-Host "========================================"
    Write-Host ""

    # 查找二进制
    if (-not (Find-Binary)) {
        Error-Message "未检测到 gitlink-cli 安装"
        exit 1
    }

    # 检查安装状态
    if (-not (Test-InstallationStatus)) {
        Error-Message "未检测到 gitlink-cli 安装"
        exit 1
    }

    # 确认卸载
    Confirm-Uninstall

    # 执行卸载
    Remove-Binary
    Remove-Skills
    Remove-Config
    Uninstall-Npm

    # 显示摘要
    Show-Summary
}

# 运行主流程
try {
    Main
} catch {
    Error-Message "卸载失败: $_"
    exit 1
}