# ComfyUI Serverless — Windows launcher (PowerShell)

$ErrorActionPreference = "Stop"
$DIR = $PSScriptRoot
Set-Location $DIR

function Fail($msg, $help) {
    Write-Host ""
    Write-Host "  ERROR: $msg" -ForegroundColor Red
    Write-Host "  $help"
    Write-Host ""
    exit 1
}

# --- Load .env ----------------------------------------------------------------
Remove-Item Env:FAL_KEY -ErrorAction SilentlyContinue
Remove-Item Env:FAL_COMFY_ENDPOINT -ErrorAction SilentlyContinue

$envFile = Join-Path $DIR ".env"
$falKey = ""
$falEndpoint = ""
if (Test-Path $envFile) {
    Get-Content $envFile | ForEach-Object {
        if ($_ -match "^\s*([A-Z_]+)\s*=\s*(.+?)\s*$") {
            if ($matches[1] -eq "FAL_KEY") { $falKey = $matches[2] }
            if ($matches[1] -eq "FAL_COMFY_ENDPOINT") { $falEndpoint = $matches[2] }
        }
    }
}

# --- Configuration prompt -----------------------------------------------------
Write-Host ""
Write-Host "  ComfyUI Serverless — Configuration"
Write-Host ""

Write-Host "  API Key (get yours at https://fal.ai/dashboard/keys)"
if ($falKey) {
    $mask = $falKey.Substring(0, [Math]::Min(8, $falKey.Length)) + "..."
    $newKey = Read-Host "  FAL_KEY [$mask]"
    if ($newKey) { $falKey = $newKey }
} else {
    $falKey = Read-Host "  FAL_KEY"
    if (-not $falKey) { Fail "No key provided." "Get one at https://fal.ai/dashboard/keys" }
}

Write-Host ""
Write-Host "  Endpoint (ask your team lead if unsure)"
if ($falEndpoint) {
    $newEndpoint = Read-Host "  FAL_COMFY_ENDPOINT [$falEndpoint]"
    if ($newEndpoint) { $falEndpoint = $newEndpoint }
} else {
    Write-Host "  Example: my-team/comfy"
    $falEndpoint = Read-Host "  FAL_COMFY_ENDPOINT"
    if (-not $falEndpoint) { Fail "No endpoint provided." "Ask your team lead." }
}

Set-Content -Path $envFile -Value "FAL_KEY=$falKey`nFAL_COMFY_ENDPOINT=$falEndpoint"
$env:FAL_KEY = $falKey
$env:FAL_COMFY_ENDPOINT = $falEndpoint

# --- Check & install tools (winget) -------------------------------------------
function Need-Cmd($name) {
    return -not (Get-Command $name -ErrorAction SilentlyContinue)
}

$missing = @()
if (Need-Cmd "uv") { $missing += "astral-sh.uv" }
if (Need-Cmd "ffmpeg") { $missing += "Gyan.FFmpeg" }

if ($missing.Count -gt 0) {
    Write-Host "  Missing dependencies: $($missing -join ', ')"
    if (Need-Cmd "winget") {
        Fail "winget not found." "Install App Installer from Microsoft Store: https://apps.microsoft.com/detail/9NBLGGH4NNS1"
    }
    foreach ($pkg in $missing) {
        Write-Host "  Installing $pkg..."
        winget install --id $pkg --accept-package-agreements --accept-source-agreements --silent --disable-interactivity
    }
    # Refresh PATH
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
}

# --- Download frontend if missing ---------------------------------------------
$frontendIndex = Join-Path $DIR "frontend\dist\index.html"
if (-not (Test-Path $frontendIndex)) {
    Write-Host "  Downloading ComfyUI frontend..."
    $frontendZip = Join-Path $env:TEMP "frontend-dist.zip"
    $frontendUrl = "https://github.com/fal-ai-community/serverless-comfyui-v2/releases/download/v0.0.26/frontend-dist.zip"
    Invoke-WebRequest -Uri $frontendUrl -OutFile $frontendZip
    Expand-Archive -Path $frontendZip -DestinationPath $DIR -Force
    Remove-Item $frontendZip
    Write-Host "  Frontend ready."
}

# --- Python env ---------------------------------------------------------------
$venvPython = Join-Path $DIR ".venv\Scripts\python.exe"
if (-not (Test-Path $venvPython)) {
    Write-Host "  Installing Python environment..."
    & uv venv --seed ".venv"
}

& $venvPython -c "import fastapi, fal_client" 2>$null
if ($LASTEXITCODE -ne 0) {
    Write-Host "  Installing dependencies..."
    & uv pip install --python $venvPython -r "proxy\requirements.txt"
}

# --- Kill previous proxy ------------------------------------------------------
Get-NetTCPConnection -LocalPort 8188 -ErrorAction SilentlyContinue | ForEach-Object {
    try { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue } catch {}
}
Remove-Item "$DIR\node_class_mappings.*.json" -ErrorAction SilentlyContinue

# --- Dashboard URL ------------------------------------------------------------
$parts = $falEndpoint -split "/"
$org = $parts[0]
$app = $parts[1]
$dashboard = "https://fal.ai/dashboard/apps/$org/$app/runners"

Write-Host ""
Write-Host "  ComfyUI Serverless"
Write-Host "  Endpoint: $falEndpoint"
Write-Host "  Runners:  $dashboard"
Write-Host ""
Write-Host "  Starting... (first launch takes ~5 minutes)"
Write-Host "  ComfyUI will open at http://localhost:8188"
Write-Host ""

# Open browser after 5s
Start-Job -ScriptBlock { Start-Sleep -Seconds 5; Start-Process "http://localhost:8188" } | Out-Null

# Launch proxy in foreground
& $venvPython "proxy\fal_comfy_server.py"
