#!/usr/bin/env pwsh
# Framework-Native Dashboard Launcher
# Starts API server and opens web dashboard

param(
    [int]$Port = 8080,
    [switch]$NoBrowser
)

$ErrorActionPreference = "Stop"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $ScriptDir

Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host "  FRAMEWORK-NATIVE DASHBOARD LAUNCHER" -ForegroundColor White
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host ""

# Check Python
Write-Host "[*] Checking Python..." -ForegroundColor Yellow
$pythonCmd = Get-Command python -ErrorAction SilentlyContinue
if (-not $pythonCmd) {
    Write-Host "[ERROR] Python not found. Please install Python 3.7+" -ForegroundColor Red
    exit 1
}

$pythonVersion = & python --version 2>&1
Write-Host "[OK] Found: $pythonVersion" -ForegroundColor Green

# Check deployment directory
$deploymentDir = Join-Path $ScriptDir "deployment"
if (-not (Test-Path $deploymentDir)) {
    Write-Host ""
    Write-Host "[!] Deployment directory not found" -ForegroundColor Yellow
    Write-Host "    Creating directory..." -ForegroundColor Gray
    New-Item -ItemType Directory -Path $deploymentDir -Force | Out-Null
    New-Item -ItemType Directory -Path "$deploymentDir\logs" -Force | Out-Null
    Write-Host "[OK] Directory created. Run deploy.ps1 to deploy nodes." -ForegroundColor Green
}

# Check for port conflicts
Write-Host ""
Write-Host "[*] Checking for existing server on port $Port..." -ForegroundColor Yellow
$existingProcess = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue
if ($existingProcess) {
    Write-Host "[!] Port $Port is already in use" -ForegroundColor Yellow
    $choice = Read-Host "    Kill existing process? (y/n)"
    if ($choice -eq 'y') {
        $procId = $existingProcess.OwningProcess
        Stop-Process -Id $procId -Force
        Start-Sleep -Seconds 2
        Write-Host "[OK] Killed process $procId" -ForegroundColor Green
    } else {
        Write-Host "[ERROR] Cannot start server - port in use" -ForegroundColor Red
        exit 1
    }
}

# Start API server
Write-Host ""
Write-Host "[*] Starting API server..." -ForegroundColor Yellow
$serverJob = Start-Job -ScriptBlock {
    param($ScriptDir, $Port)
    Set-Location $ScriptDir
    python dashboard_api.py $Port
} -ArgumentList $ScriptDir, $Port

Start-Sleep -Seconds 2

# Check if server started
$serverRunning = $false
for ($i = 0; $i -lt 10; $i++) {
    try {
        $response = Invoke-WebRequest -Uri "http://localhost:$Port/api/status" -TimeoutSec 2 -ErrorAction SilentlyContinue
        if ($response.StatusCode -eq 200) {
            $serverRunning = $true
            break
        }
    } catch {
        Start-Sleep -Milliseconds 500
    }
}

if (-not $serverRunning) {
    Write-Host "[ERROR] Failed to start API server" -ForegroundColor Red
    Write-Host ""
    Write-Host "Server output:" -ForegroundColor Yellow
    Receive-Job -Job $serverJob
    Remove-Job -Job $serverJob -Force
    exit 1
}

Write-Host "[OK] API server running on http://localhost:$Port" -ForegroundColor Green

# Display info
Write-Host ""
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host "  DASHBOARD READY" -ForegroundColor Green
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host ""
Write-Host "Dashboard URL: " -NoNewline -ForegroundColor Yellow
Write-Host "http://localhost:$Port/dashboard.html" -ForegroundColor Cyan
Write-Host ""
Write-Host "API Endpoints:" -ForegroundColor Yellow
Write-Host "  http://localhost:$Port/api/status" -ForegroundColor Gray
Write-Host "  http://localhost:$Port/api/nodes" -ForegroundColor Gray
Write-Host "  http://localhost:$Port/api/contracts" -ForegroundColor Gray
Write-Host ""
Write-Host "Features:" -ForegroundColor Yellow
Write-Host "  * Live node monitoring with auto-refresh" -ForegroundColor Gray
Write-Host "  * Real-time compression graphs" -ForegroundColor Gray
Write-Host "  * Framework-native contract deployment" -ForegroundColor Gray
Write-Host "  * Historical data tracking" -ForegroundColor Gray
Write-Host ""
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host ""
Write-Host "Press Ctrl+C to stop the server" -ForegroundColor Yellow
Write-Host ""

# Open browser
if (-not $NoBrowser) {
    Write-Host "[*] Opening dashboard in browser..." -ForegroundColor Yellow
    Start-Sleep -Seconds 1
    Start-Process "http://localhost:$Port/dashboard.html"
}

# Wait for user interrupt
try {
    Write-Host "[*] Server running... (Press Ctrl+C to stop)" -ForegroundColor Cyan
    Write-Host ""

    while ($true) {
        $jobState = (Get-Job -Id $serverJob.Id).State
        if ($jobState -ne "Running") {
            Write-Host ""
            Write-Host "[ERROR] Server stopped unexpectedly" -ForegroundColor Red
            Write-Host ""
            Write-Host "Server output:" -ForegroundColor Yellow
            Receive-Job -Job $serverJob
            break
        }

        Start-Sleep -Seconds 1
    }
} finally {
    Write-Host ""
    Write-Host "[*] Stopping server..." -ForegroundColor Yellow
    Stop-Job -Job $serverJob -ErrorAction SilentlyContinue
    Remove-Job -Job $serverJob -Force -ErrorAction SilentlyContinue
    Write-Host "[OK] Server stopped" -ForegroundColor Green
    Write-Host ""
}
