$ErrorActionPreference = "Stop"
$expectedHash = "4838f38e879fd3e45146145136310cd4a04b33c6851fd19da7fdb3b20b55afbc"
$expectedSize = [int64]26980734
$downloadUrls = if ($env:AIXIFU_REPAIR_URL) {
    @($env:AIXIFU_REPAIR_URL)
} else {
    @(
        "https://ai2.bwcjxf.com/download/AiXifu-Launcher.exe?v=1.8.2"
    )
}
$packageExe = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\AiXifu-Launcher.exe"))
$installDir = Join-Path $env:LOCALAPPDATA "AiXifuClient\launcher"
$target = Join-Path $installDir "AiXifu-Launcher.exe"
$temporaryDownload = Join-Path $env:TEMP ("AiXifu-Launcher-repair-{0}.exe" -f $PID)
$temporaryInstall = "$target.repair"
$logDir = Join-Path $env:LOCALAPPDATA "AiXifuClient\logs"
$logFile = Join-Path $logDir "installer.log"

function Write-InstallerLog([string]$message) {
    New-Item -ItemType Directory -Path $logDir -Force | Out-Null
    Add-Content -LiteralPath $logFile -Encoding UTF8 -Value ((Get-Date -Format o) + " " + $message)
}

function Test-Launcher([string]$path) {
    if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return $false }
    $item = Get-Item -LiteralPath $path
    if ($item.Length -ne $expectedSize) { return $false }
    return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -eq $expectedHash
}

function Download-VerifiedLauncher {
    for ($attempt = 1; $attempt -le 3; $attempt++) {
        foreach ($downloadUrl in $downloadUrls) {
            Remove-Item -LiteralPath $temporaryDownload -Force -ErrorAction SilentlyContinue
            try {
                Write-Host "正在下载完整启动器（第 $attempt/3 次）..."
                if (Get-Command Start-BitsTransfer -ErrorAction SilentlyContinue) {
                    Start-BitsTransfer -Source $downloadUrl -Destination $temporaryDownload -DisplayName "AI辅助器修复"
                } else {
                    Invoke-WebRequest -Uri $downloadUrl -OutFile $temporaryDownload -UseBasicParsing
                }
                if (Test-Launcher $temporaryDownload) { return $temporaryDownload }
                Write-InstallerLog "download verification failed attempt=$attempt url=$downloadUrl"
            } catch {
                Write-InstallerLog ("download failed attempt=$attempt url=$downloadUrl error=" + $_.Exception.Message)
            }
        }
        Start-Sleep -Seconds 2
    }
    throw "下载后的启动器仍不完整。请暂时关闭会修改下载文件的安全软件后重试，或联系管理员并提供 installer.log。"
}

try {
    Write-Host "正在校验 AI辅助器程序包..."
    $candidate = $packageExe
    if (-not (Test-Launcher $candidate)) {
        Write-InstallerLog "packaged launcher is missing or corrupted; starting verified repair download"
        $candidate = Download-VerifiedLauncher
    }

    New-Item -ItemType Directory -Path $installDir -Force | Out-Null
    Remove-Item -LiteralPath $temporaryInstall -Force -ErrorAction SilentlyContinue
    Copy-Item -LiteralPath $candidate -Destination $temporaryInstall -Force
    if (-not (Test-Launcher $temporaryInstall)) {
        throw "写入本机后的启动器校验失败，文件可能被安全软件修改。"
    }
    try {
        Move-Item -LiteralPath $temporaryInstall -Destination $target -Force
    } catch {
        throw "无法替换正在运行的旧启动器。请先退出系统托盘中的 AI辅助器，再重新运行本安装程序。"
    }
    if (-not (Test-Launcher $target)) { throw "安装后的启动器校验失败。" }
    Write-InstallerLog "launcher installed and verified version=1.8.2 sha256=$expectedHash"
    Write-Host "校验通过，正在启动 AI辅助器..."
    if ($env:AIXIFU_INSTALLER_SELF_TEST -ne "1") {
        Start-Process -FilePath $target -ArgumentList "--launch"
    }
    exit 0
} catch {
    Write-InstallerLog ("installer failed error=" + $_.Exception.Message)
    Write-Host ("错误：" + $_.Exception.Message) -ForegroundColor Red
    Write-Host ("日志位置：" + $logFile)
    exit 1
} finally {
    Remove-Item -LiteralPath $temporaryDownload -Force -ErrorAction SilentlyContinue
    Remove-Item -LiteralPath $temporaryInstall -Force -ErrorAction SilentlyContinue
}

