$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $PSScriptRoot
$runtimeDir = Join-Path $root "smqjh-agent-runtime"
$logsDir = Join-Path $root "logs"

if (-not (Test-Path $runtimeDir)) {
  throw "Runtime directory not found: $runtimeDir"
}

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

if (-not $env:SMQJH_MCP_URL) {
  $env:SMQJH_MCP_URL = "http://127.0.0.1:8765/mcp"
}
if (-not $env:WEB_AGENT_PORT) {
  $env:WEB_AGENT_PORT = "5188"
}

$venvDir = Join-Path $runtimeDir ".venv"
$python = Join-Path $venvDir "Scripts\python.exe"

if (-not (Test-Path $python)) {
  Push-Location $runtimeDir
  try {
    python -m venv .venv
  } finally {
    Pop-Location
  }
}

Push-Location $runtimeDir
try {
  & $python -m pip install --disable-pip-version-check -r requirements.txt
} finally {
  Pop-Location
}

$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$stdout = Join-Path $logsDir "web-agent-$stamp.out.log"
$stderr = Join-Path $logsDir "web-agent-$stamp.err.log"

Start-Process `
  -FilePath $python `
  -ArgumentList @("-m", "app.server") `
  -WorkingDirectory $runtimeDir `
  -WindowStyle Hidden `
  -RedirectStandardOutput $stdout `
  -RedirectStandardError $stderr

Write-Host "Web Agent start requested."
Write-Host "URL: http://127.0.0.1:$env:WEB_AGENT_PORT"
Write-Host "MCP: $env:SMQJH_MCP_URL"
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
