param(
    [string]$ProjectDir = (Get-Location).Path
)

$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
$runtimeConfig = Join-Path $ProjectDir "config\python-runtime.json"
$cacheDir = Join-Path $ProjectDir ".runtime-cache"
$logDir = Join-Path $ProjectDir "logs"
$logPath = Join-Path $logDir "python-bootstrap-windows.log"

New-Item -ItemType Directory -Path $cacheDir -Force | Out-Null
New-Item -ItemType Directory -Path $logDir -Force | Out-Null

function Stop-WithMessage {
    param([string]$Code, [string]$Message, [string]$Suggestion)
    $line = "[$Code] $Message`r`n处理建议：$Suggestion"
    Add-Content -LiteralPath $logPath -Value $line -Encoding UTF8
    Write-Host $line
    exit 2
}

if (-not (Test-Path -LiteralPath $runtimeConfig)) {
    Stop-WithMessage "PYTHON_RUNTIME_CONFIG_MISSING" "缺少 Python 运行时配置。" "重新解压完整系统 ZIP。"
}

try {
    $config = Get-Content -LiteralPath $runtimeConfig -Raw -Encoding UTF8 | ConvertFrom-Json
    $url = [Uri]$config.windows.url
    $expectedSha256 = [string]$config.windows.sha256
    $fileName = [IO.Path]::GetFileName($url.AbsolutePath)
} catch {
    Stop-WithMessage "PYTHON_RUNTIME_CONFIG_INVALID" "Python 运行时配置无法读取。" "重新生成或重新下载完整系统 ZIP。"
}

if ($url.Scheme -ne "https" -or $url.Host -ne "www.python.org") {
    Stop-WithMessage "PYTHON_INSTALLER_SOURCE_REJECTED" "安装包不是 Python 官方 HTTPS 来源。" "只允许使用 www.python.org 的固定版本安装包。"
}
if ($expectedSha256 -notmatch "^[A-Fa-f0-9]{64}$") {
    Stop-WithMessage "PYTHON_INSTALLER_HASH_MISSING" "安装包 SHA-256 未固定。" "由系统生成方从 Python 官方发布页核对并写入哈希。"
}

$installer = Join-Path $cacheDir $fileName
if (-not (Test-Path -LiteralPath $installer)) {
    try {
        Invoke-WebRequest -Uri $url.AbsoluteUri -OutFile $installer -UseBasicParsing
    } catch {
        Stop-WithMessage "PYTHON_INSTALLER_DOWNLOAD_FAILED" "Python 官方安装包下载失败。" "检查网络，或把已验证的官方安装包放入 .runtime-cache 后重试。"
    }
}

$actualSha256 = (Get-FileHash -LiteralPath $installer -Algorithm SHA256).Hash
if ($actualSha256 -ne $expectedSha256) {
    Remove-Item -LiteralPath $installer -Force -ErrorAction SilentlyContinue
    Stop-WithMessage "PYTHON_INSTALLER_HASH_MISMATCH" "Python 安装包哈希不匹配，已停止安装。" "不要使用该文件；重新从官方来源获取。"
}

$signature = Get-AuthenticodeSignature -LiteralPath $installer
if ($signature.Status -ne "Valid" -or $signature.SignerCertificate.Subject -notmatch "Python Software Foundation") {
    Stop-WithMessage "PYTHON_INSTALLER_SIGNATURE_INVALID" "Python 安装包数字签名无效或发布者不正确。" "只使用 Python Software Foundation 签名的官方安装包。"
}

$userArgs = "/quiet InstallAllUsers=0 Include_pip=1 Include_launcher=1 PrependPath=1 Shortcuts=0"
try {
    $process = Start-Process -FilePath $installer -ArgumentList $userArgs -Wait -PassThru
    if ($process.ExitCode -ne 0) { throw "exit=$($process.ExitCode)" }
} catch {
    if ($config.windows.allow_admin_install -ne $true) {
        Stop-WithMessage "PYTHON_USER_INSTALL_FAILED" "当前用户安装 Python 失败。" "联系电脑管理员放行安装，或由管理员启用系统级安装。"
    }
    Write-Host "[PYTHON_ADMIN_AUTH_REQUIRED] 当前用户安装受策略限制，即将显示 Windows 管理员授权窗口。"
    try {
        $adminArgs = "/quiet InstallAllUsers=1 Include_pip=1 Include_launcher=1 PrependPath=1 Shortcuts=0"
        $process = Start-Process -FilePath $installer -ArgumentList $adminArgs -Verb RunAs -Wait -PassThru
        if ($process.ExitCode -ne 0) { throw "exit=$($process.ExitCode)" }
    } catch {
        Stop-WithMessage "PYTHON_ADMIN_INSTALL_DENIED" "管理员授权被拒绝或系统级安装失败。" "请由电脑管理员完成安装后重新启动系统。"
    }
}

$pythonCandidates = @(
    (Join-Path $env:LocalAppData "Programs\Python\Python313\python.exe"),
    (Join-Path $env:LocalAppData "Programs\Python\Python312\python.exe"),
    (Join-Path $env:ProgramFiles "Python313\python.exe"),
    (Join-Path $env:ProgramFiles "Python312\python.exe")
)
$pythonPath = $pythonCandidates | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
if (-not $pythonPath) {
    Stop-WithMessage "PYTHON_INSTALL_VERIFY_FAILED" "安装完成后未找到受支持的 Python。" "重启终端；仍无法识别时联系管理员检查安装日志。"
}

& $pythonPath -c "import sys; raise SystemExit(0 if sys.version_info >= (3,10) else 1)"
if ($LASTEXITCODE -ne 0) {
    Stop-WithMessage "PYTHON_INSTALL_VERIFY_FAILED" "安装后的 Python 版本不受支持。" "安装 Python 3.10 或更高版本。"
}

Write-Host "[PYTHON_INSTALL_OK] Python 已安装并验证：$pythonPath"
Add-Content -LiteralPath $logPath -Value "[PYTHON_INSTALL_OK] $pythonPath" -Encoding UTF8
exit 0
