#!/usr/bin/env pwsh
<#
.SYNOPSIS
    Start Framework-Native Dashboard with API Server

.DESCRIPTION
    Launches the dashboard API server and opens the web interface
    Provides live data monitoring and contract deployment capabilities

.PARAMETER Port
    Port to run the server on (default: 8080)

.PARAMETER NoBrowser
    Don't automatically open browser

.EXAMPLE
    .\start_dashboard.ps1
    .\start_dashboard.ps1 -Port 3000 -NoBrowser
#>

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

$ErrorActionPreference = "Stop"

# Get script directory
$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 " Python not found. Please install Python 3.7+" -ForegroundColor Red
    exit 1
}

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

# Check if deployment exists
$deploymentDir = Join-Path $ScriptDir "deployment"
if (-not (Test-Path $deploymentDir)) {
    Write-Host ""
    Write-Host "  Deployment directory not found" -ForegroundColor Yellow
    Write-Host "   Creating directory and deploying nodes..." -ForegroundColor Gray

    # Deploy nodes
    if (Test-Path "deploy.ps1") {
        & .\deploy.ps1 -Mode local -NumNodes 3
    } else {
        New-Item -ItemType Directory -Path $deploymentDir -Force | Out-Null
        New-Item -ItemType Directory -Path "$deploymentDir\logs" -Force | Out-Null
        Write-Host "   Directory created. Run deploy.ps1 to deploy nodes." -ForegroundColor Gray
    }
}

# Check for existing server
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 in background
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 " 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 " API server running on http://localhost:$Port" -ForegroundColor Green

# Display info
Write-Host ""
Write-Host ("=" * 80) -ForegroundColor Cyan
Write-Host "  DASHBOARD READY" -ForegroundColor White -BackgroundColor DarkGreen
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 " 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 " Server stopped" -ForegroundColor Green
    Write-Host ""
}

