# ============================================================
# LambdaAgentPaaS — Windows Native 安装（无 Docker）
#
# 用法:
#   .\deploy\install-native.ps1          # 安装
#   .\deploy\install-native.ps1 -Start   # 安装后启动
#
# 要求: Python 3.10+,  Node.js 18+
# ============================================================
param([switch]$Start)
$ErrorActionPreference = "Stop"

$ScriptDir  = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectDir = Split-Path -Parent $ScriptDir
$VenvDir    = Join-Path $ProjectDir ".venv"
$DataDir    = Join-Path $env:USERPROFILE ".agentpaas\data"
$EnvFile    = Join-Path $env:USERPROFILE ".agentpaas\.env"

function Write-Info    { param($m) Write-Host "ℹ  $m" -ForegroundColor Cyan }
function Write-Success { param($m) Write-Host "✅ $m" -ForegroundColor Green }
function Write-Warn    { param($m) Write-Host "⚠️  $m" -ForegroundColor Yellow }
function Exit-Error    { param($m) Write-Host "❌ $m" -ForegroundColor Red; exit 1 }

Write-Host "`n=== LambdaAgentPaaS Native 安装 (Windows) ===`n" -ForegroundColor Magenta

# ── 检查 Python ──────────────────────────────────────────────
$pythonCmd = $null
foreach ($cmd in @("python", "python3", "py")) {
    try {
        $ver = & $cmd -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>$null
        $major, $minor = $ver.Split('.') | ForEach-Object { [int]$_ }
        if ($major -gt 3 -or ($major -eq 3 -and $minor -ge 10)) {
            $pythonCmd = $cmd; break
        }
    } catch {}
}
if (-not $pythonCmd) {
    Exit-Error "需要 Python 3.10+。请从 https://www.python.org/ 安装（勾选 Add to PATH）。"
}
Write-Info "使用 Python: $(& $pythonCmd --version)"

# ── 检查 Node.js ─────────────────────────────────────────────
if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
    Exit-Error "需要 Node.js 18+。请从 https://nodejs.org/ 安装后重试。"
}
$nodeVer = (node -e "process.stdout.write(process.version.replace('v',''))").Split('.')[0]
if ([int]$nodeVer -lt 18) { Exit-Error "需要 Node.js 18+（当前 v$nodeVer）" }
Write-Info "使用 Node.js: $(node --version)"

# ── 创建虚拟环境 ─────────────────────────────────────────────
if (-not (Test-Path $VenvDir)) {
    Write-Info "创建 Python 虚拟环境..."
    & $pythonCmd -m venv $VenvDir
}
$venvPy  = Join-Path $VenvDir "Scripts\python.exe"
$venvPip = Join-Path $VenvDir "Scripts\pip.exe"

# ── 安装 Python 依赖 ─────────────────────────────────────────
Write-Info "安装 Python 依赖（首次约 3-5 分钟）..."
Set-Location $ProjectDir
# 国内网络可改为 https://pypi.tuna.tsinghua.edu.cn/simple
$pipIndex = ""  # "-i https://pypi.tuna.tsinghua.edu.cn/simple"

& $venvPip install --upgrade pip $pipIndex -q
& $venvPip install -e "lambdagent[all]" $pipIndex -q
& $venvPip install -e "agentpaas[all]" $pipIndex -q
& $venvPip install pymupdf $pipIndex -q
Write-Success "Python 依赖安装完成"

# ── 构建前端 ─────────────────────────────────────────────────
Write-Info "安装前端依赖..."
Set-Location (Join-Path $ProjectDir "webui")
npm ci --prefer-offline --loglevel=error
Write-Info "构建前端..."
npm run build
Write-Success "前端构建完成 → webui-dist/"
Set-Location $ProjectDir

# ── 初始化数据目录 ────────────────────────────────────────────
$dirs = @($DataDir,
    (Join-Path $DataDir "instances"),
    (Join-Path $DataDir "knowledge_bases"),
    (Join-Path $DataDir "logs"))
foreach ($d in $dirs) {
    if (-not (Test-Path $d)) { New-Item -ItemType Directory $d -Force | Out-Null }
}

# ── 初始化配置文件 ────────────────────────────────────────────
if (-not (Test-Path $EnvFile)) {
    $configDir = Split-Path -Parent $EnvFile
    if (-not (Test-Path $configDir)) { New-Item -ItemType Directory $configDir -Force | Out-Null }
    Copy-Item (Join-Path $ProjectDir ".env.template") $EnvFile -Force

    # 生成 MASTER_KEY
    $bytes = [byte[]]::new(32)
    [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
    $masterKey = ($bytes | ForEach-Object { $_.ToString("x2") }) -join ""

    $content = Get-Content $EnvFile
    $content = $content -replace "^AGENTPAAS_DATA_DIR=.*", "AGENTPAAS_DATA_DIR=$DataDir"
    $content = $content -replace "^AGENTPAAS_MASTER_KEY=.*", "AGENTPAAS_MASTER_KEY=$masterKey"
    $content | Set-Content $EnvFile -Encoding UTF8
    Write-Success "配置文件已创建: $EnvFile"
    Write-Warn "请编辑 $EnvFile 填写至少一个 LLM API Key"
}

# ── 创建 Windows 启动快捷脚本 ────────────────────────────────
$runnerScript = Join-Path (Split-Path -Parent $EnvFile) "run.ps1"
@"
# LambdaAgentPaaS 启动器（由 install-native.ps1 生成）
Get-Content '$EnvFile' | ForEach-Object {
    if (`$_ -match '^\s*([^#][^=]+)=(.*)$') {
        [System.Environment]::SetEnvironmentVariable(`$matches[1].Trim(), `$matches[2].Trim(), 'Process')
    }
}
`$env:AGENTPAAS_DATA_DIR = '$DataDir'
Set-Location '$ProjectDir'
& '$venvPy' -m agentpaas serve --host 0.0.0.0 --port (`$env:AGENTPAAS_PORT ?? '8000')
"@ | Set-Content $runnerScript -Encoding UTF8

# ── 创建桌面快捷方式 ─────────────────────────────────────────
$desktopShortcut = Join-Path ([System.Environment]::GetFolderPath('Desktop')) "LambdaAgentPaaS.lnk"
$wsh = New-Object -ComObject WScript.Shell
$shortcut = $wsh.CreateShortcut($desktopShortcut)
$shortcut.TargetPath = "powershell.exe"
$shortcut.Arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$runnerScript`""
$shortcut.WorkingDirectory = $ProjectDir
$shortcut.Description = "LambdaAgentPaaS"
$shortcut.IconLocation = "powershell.exe,0"
$shortcut.Save()
Write-Success "桌面快捷方式已创建"

# ── 打印完成信息 ─────────────────────────────────────────────
Write-Host ""
Write-Host "╔══════════════════════════════════════════════╗" -ForegroundColor Green
Write-Host "║  ✅ LambdaAgentPaaS 安装完成！              ║" -ForegroundColor Green
Write-Host "╠══════════════════════════════════════════════╣" -ForegroundColor Green
Write-Host "║  启动方式 1: 双击桌面 LambdaAgentPaaS 图标 ║" -ForegroundColor Green
Write-Host "║  启动方式 2: powershell $runnerScript       ║" -ForegroundColor Green
Write-Host "║  配置文件: $EnvFile" -ForegroundColor Green
Write-Host "║  数据目录: $DataDir" -ForegroundColor Green
Write-Host "╚══════════════════════════════════════════════╝" -ForegroundColor Green
Write-Host ""

if ($Start) {
    Write-Info "正在启动服务..."
    & powershell -NoProfile -ExecutionPolicy Bypass -File $runnerScript
}
