# Windows 客户端安装：pip + Console + 登录启动脚本
param(
    [string]$RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
)

$ErrorActionPreference = "Stop"
$DataHome = Join-Path $env:LOCALAPPDATA "NianNian"
$StartScript = Join-Path $RepoRoot "client\windows\start-agent.ps1"
$TaskName = "NianNianAgent"

Write-Host "==> NianNian Windows client install"
Write-Host "    repo: $RepoRoot"
Write-Host "    home: $DataHome"

New-Item -ItemType Directory -Force -Path $DataHome | Out-Null

$envExample = Join-Path $RepoRoot "client\config\client-agent.env.example"
$envDst = Join-Path $RepoRoot "client\config\client-agent.env"
if (-not (Test-Path $envDst)) {
    Copy-Item $envExample $envDst
}

Push-Location $RepoRoot
python -m pip install -e ".[http]" --quiet
$distIndex = Join-Path $RepoRoot "console\web\dist\index.html"
if (Test-Path $distIndex) {
    Write-Host "==> Console dist present, skip npm build"
} else {
    bash client/scripts/build-console-client.sh
}
Pop-Location

$action = New-ScheduledTaskAction -Execute "powershell.exe" `
    -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$StartScript`""
$trigger = New-ScheduledTaskTrigger -AtLogOn
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Settings $settings -Force | Out-Null
Start-ScheduledTask -TaskName $TaskName

Start-Sleep -Seconds 3
bash client/scripts/health-check.sh
Write-Host "Done. http://127.0.0.1:18765/niannian/chat"
