$ErrorActionPreference = "Stop"
$InstallDir = if ($env:ZOI_AGENT_DIR) { $env:ZOI_AGENT_DIR } else { Join-Path $HOME "zoi-agent" }
$SourceUrl = if ($env:ZOI_AGENT_SOURCE_URL) { $env:ZOI_AGENT_SOURCE_URL } else { "https://ponsagent.com/zoi-agent-source.zip" }

if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
  throw "Docker Desktop is required. Install it, then run this script again."
}
if (-not (Get-Command Expand-Archive -ErrorAction SilentlyContinue)) {
  throw "PowerShell Expand-Archive is required."
}

$Archive = Join-Path ([System.IO.Path]::GetTempPath()) "zoi-agent-source.zip"
New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
Invoke-WebRequest -Uri $SourceUrl -OutFile $Archive
Expand-Archive -Path $Archive -DestinationPath $InstallDir -Force
Remove-Item $Archive -Force

$EnvExample = Join-Path $InstallDir "apps/agent/.env.example"
$EnvFile = Join-Path $InstallDir "apps/agent/.env"
if (-not (Test-Path $EnvFile)) { Copy-Item $EnvExample $EnvFile }

docker network inspect pons-control *> $null
if ($LASTEXITCODE -ne 0) { docker network create pons-control | Out-Null }

Write-Host "Zoi Agent source installed at $InstallDir"
Write-Host "1. Edit $EnvFile with your own RPC, API keys, and wallet."
Write-Host "2. Keep AGENT_MODE=observe until doctor passes."
Write-Host "3. Run: cd $InstallDir; docker compose -f docker-compose.agent.yml up -d --build"
