# ComfyUI Serverless — Deploy (Windows)
$ErrorActionPreference = "Stop"
$DIR = $PSScriptRoot
Set-Location $DIR

Write-Host ""
Write-Host "  ComfyUI Serverless — Deploy"
Write-Host ""

$falKey = ""
$appName = ""
$falTeam = ""
$envFile = Join-Path $DIR ".env"
if (Test-Path $envFile) {
    Get-Content $envFile | ForEach-Object {
        if ($_ -match "^([A-Z_]+)=(.+)$") {
            if ($matches[1] -eq "FAL_KEY") { $falKey = $matches[2] }
            if ($matches[1] -eq "APP_NAME") { $appName = $matches[2] }
            if ($matches[1] -eq "FAL_TEAM") { $falTeam = $matches[2] }
        }
    }
}

if (-not $falKey) {
    Write-Host "  You need an ADMIN API key. Get one at https://fal.ai/dashboard/keys"
    $falKey = Read-Host "  FAL_KEY (admin)"
}
if (-not $appName) {
    $appName = Read-Host "  APP_NAME [comfy]"
    if (-not $appName) { $appName = "comfy" }
}
if (-not $falTeam) {
    Write-Host "  Team name (leave empty for personal account)"
    $falTeam = Read-Host "  FAL_TEAM"
}

Set-Content -Path $envFile -Value "FAL_KEY=$falKey`nAPP_NAME=$appName`nFAL_TEAM=$falTeam"

$env:FAL_KEY = $falKey
$env:FAL_TEAM = $falTeam

$python = Get-Command python3.11 -ErrorAction SilentlyContinue
if (-not $python) { $python = Get-Command python -ErrorAction SilentlyContinue }
if (-not $python) { Write-Host "ERROR: Python 3.11 required. Install from python.org"; exit 1 }

Set-Location "server"
if (-not (Test-Path ".venv\Scripts\python.exe")) {
    Write-Host "  Setting up Python environment..."
    & $python.Source -m venv .venv
    .\.venv\Scripts\pip.exe install --quiet --upgrade pip setuptools
    .\.venv\Scripts\pip.exe install --quiet -e ".[dev]"
}

Write-Host "  Verifying API key..."
# Force logout user session (ensures FAL_KEY is used)
try { .\.venv\Scripts\fal.exe auth logout 2>$null } catch {}

$test = .\.venv\Scripts\fal.exe apps list 2>&1 | Select-Object -First 1
if ($test -match "Insufficient permissions") {
    Write-Host "ERROR: Key doesn't have Admin scope. Create an admin key at https://fal.ai/dashboard/keys"
    exit 1
}
Write-Host "  Admin key OK"

Write-Host ""
Write-Host "  Deploy target:"
Write-Host "    App:  $appName"
if ($falTeam) {
    Write-Host "    Team: $falTeam"
    Write-Host "    Endpoint: $falTeam/$appName"
} else {
    Write-Host "    Team: (personal)"
}
$confirm = Read-Host "  Confirm deploy? (y/n)"
if ($confirm -ne "y" -and $confirm -ne "Y") { Write-Host "Cancelled."; exit 0 }

Write-Host "  Deploying..."
.\.venv\Scripts\python.exe -m fal deploy server.py::Comfy --app-name $appName --auth private

Write-Host ""
Write-Host "  Deploy complete!"
if ($falTeam) {
    Write-Host "  Endpoint: $falTeam/$appName"
    Write-Host "  Runners:  https://fal.ai/dashboard/apps/$falTeam/$appName/runners"
}
