# OpenFin - Start script
# Usage: powershell -ExecutionPolicy Bypass -File c:\DataS\OpenFin\start.ps1

$Root = Split-Path -Parent $MyInvocation.MyCommand.Path

Write-Host ""
Write-Host "  ============================================" -ForegroundColor Cyan
Write-Host "    OpenFin Intelligence Cockpit v2.0" -ForegroundColor Cyan
Write-Host "  ============================================" -ForegroundColor Cyan
Write-Host ""

# 1. Kill existing processes on ports 8000 and 5173
Write-Host "  [1/4] Liberation des ports..." -ForegroundColor Yellow
foreach ($port in @(8000, 5173)) {
    $lines = netstat -ano | Select-String ":$port\s" | Select-String "LISTENING"
    foreach ($line in $lines) {
        $p = ($line -split '\s+')[-1].Trim()
        if ($p -match '^\d+$' -and $p -ne '0') {
            try {
                Stop-Process -Id ([int]$p) -Force -ErrorAction Stop
                Write-Host "    Port $port : PID $p stoppe." -ForegroundColor Gray
            } catch {}
        }
    }
}
Start-Sleep -Seconds 1

# 2. Write temp bat files
$backendBat  = "$Root\_start_backend.bat"
$frontendBat = "$Root\_start_frontend.bat"

$backendLines = @(
    "@echo off",
    "title OpenFin Backend",
    "cd /d `"$Root\backend`"",
    "if not exist venv python -m venv venv",
    "call venv\Scripts\activate.bat",
    "pip install -r requirements.txt -q",
    "python -m uvicorn main:app --host 0.0.0.0 --port 8000 --reload"
)
$backendLines | Set-Content -Path $backendBat -Encoding ASCII

$frontendLines = @(
    "@echo off",
    "title OpenFin Frontend",
    "cd /d `"$Root\frontend`"",
    "if not exist node_modules npm install",
    "npm run dev"
)
$frontendLines | Set-Content -Path $frontendBat -Encoding ASCII

# 3. Start backend
Write-Host "  [2/4] Demarrage du backend..." -ForegroundColor Yellow
Start-Process "cmd.exe" -ArgumentList "/k `"$backendBat`"" -WindowStyle Normal

# 4. Wait until backend port is open (max 90s)
Write-Host "  [3/4] Attente backend sur port 8000..." -ForegroundColor Yellow
$timeout = 90
$elapsed = 0
$ready   = $false
while ($elapsed -lt $timeout) {
    Start-Sleep -Seconds 2
    $elapsed += 2
    $tcp = New-Object System.Net.Sockets.TcpClient
    try {
        $tcp.Connect("127.0.0.1", 8000)
        if ($tcp.Connected) { $ready = $true; $tcp.Close(); break }
    } catch {}
    finally { if ($tcp) { $tcp.Close() } }
    Write-Host "    ...attente ($elapsed`s / $timeout`s)" -ForegroundColor DarkGray
}

if ($ready) {
    Write-Host "    Backend OK" -ForegroundColor Green
} else {
    Write-Host "    ATTENTION : backend non repond apres $timeout`s" -ForegroundColor Red
    Write-Host "    Verifie la fenetre OpenFin Backend pour voir l'erreur." -ForegroundColor Red
}

# 5. Start frontend
Write-Host "  [4/4] Demarrage du frontend..." -ForegroundColor Yellow
Start-Process "cmd.exe" -ArgumentList "/k `"$frontendBat`"" -WindowStyle Normal

Start-Sleep -Seconds 4
Start-Process "http://localhost:5173"

Write-Host ""
Write-Host "  Cockpit : http://localhost:5173" -ForegroundColor Green
Write-Host "  API     : http://localhost:8000/docs" -ForegroundColor Green
Write-Host ""
