#Requires -Version 5.1
$ErrorActionPreference = "Stop"
$APP = Split-Path -Parent $MyInvocation.MyCommand.Path

function Write-Step($n, $msg) {
    Write-Host ""
    Write-Host "[$n] $msg" -ForegroundColor Cyan
}
function Write-OK($msg)   { Write-Host "    OK — $msg" -ForegroundColor Green }
function Write-Warn($msg) { Write-Host "    [!] $msg"  -ForegroundColor Yellow }
function Write-Fail($msg) { Write-Host "    ERROR: $msg" -ForegroundColor Red; Read-Host "Presiona Enter para salir"; exit 1 }

Clear-Host
Write-Host ""
Write-Host "  ============================================================" -ForegroundColor Cyan
Write-Host "   AidsMonitoring  |  Maritime Traffic System" -ForegroundColor White
Write-Host "   Instalador para Windows 10 / 11" -ForegroundColor Gray
Write-Host "  ============================================================" -ForegroundColor Cyan

# ── 1. Python ────────────────────────────────────────────────────────────────
Write-Step 1 "Verificando Python 3.10+..."

$python = $null
foreach ($cmd in @("python","python3","py")) {
    try {
        $ver = & $cmd --version 2>&1
        if ($ver -match "Python (\d+)\.(\d+)") {
            $maj = [int]$Matches[1]; $min = [int]$Matches[2]
            if ($maj -ge 3 -and $min -ge 10) { $python = $cmd; break }
        }
    } catch {}
}

if (-not $python) {
    Write-Warn "Python 3.10+ no encontrado."
    $resp = Read-Host "    Instalar Python 3.12 via winget? [S/N]"
    if ($resp -match "^[Ss]") {
        Write-Host "    Instalando..." -ForegroundColor Yellow
        winget install Python.Python.3.12 --silent --accept-package-agreements --accept-source-agreements
        # Refrescar PATH
        $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" +
                    [System.Environment]::GetEnvironmentVariable("Path","User")
        $python = "python"
    } else {
        Write-Fail "Instala Python 3.12 desde https://python.org y vuelve a ejecutar."
    }
}

$verStr = & $python --version 2>&1
Write-OK "Usando $python ($verStr)"

# ── 2. Entorno virtual ───────────────────────────────────────────────────────
Write-Step 2 "Creando entorno virtual..."

$venv = Join-Path $APP "venv"
if (Test-Path "$venv\Scripts\python.exe") {
    Write-OK "Entorno virtual ya existe — omitiendo."
} else {
    & $python -m venv $venv
    if ($LASTEXITCODE -ne 0) { Write-Fail "No se pudo crear el entorno virtual." }
    Write-OK "Entorno virtual creado en venv\"
}

$vpython = "$venv\Scripts\python.exe"
$vpip    = "$venv\Scripts\pip.exe"

# ── 3. Dependencias ──────────────────────────────────────────────────────────
Write-Step 3 "Instalando dependencias Python (puede tardar 2-3 min)..."

$reqs = Join-Path $APP "backend\requirements.txt"
& $vpip install --upgrade pip -q
& $vpip install -r $reqs -q
if ($LASTEXITCODE -ne 0) { Write-Fail "Error instalando paquetes. Revisa la conexion a internet." }
Write-OK "Todos los paquetes instalados."

# ── 4. Archivo .env ──────────────────────────────────────────────────────────
Write-Step 4 "Configuracion inicial..."

$env_file = Join-Path $APP "backend\.env"
if (-not (Test-Path $env_file)) {
    @"
AIS_SOURCE=SIMULATOR
GPS_PORT=
GPS_BAUD=9600
PROXIMITY_ALERT_METERS=500
PROJECTION_MINUTES=10
SECRET_KEY=AidsMonitoring2026ChangeMe
"@ | Set-Content $env_file -Encoding UTF8
    Write-OK ".env creado con valores por defecto."
} else {
    Write-OK ".env ya existe."
}

# ── 5. Actualizar start.bat ──────────────────────────────────────────────────
Write-Step 5 "Actualizando start.bat..."

$startBat = Join-Path $APP "start.bat"
@"
@echo off
title AidsMonitoring Server
cd /d "%~dp0backend"

for /f "tokens=5" %%a in ('netstat -ano 2^>nul ^| findstr ":5503 " ^| findstr "LISTENING"') do (
    taskkill /F /PID %%a >nul 2>&1
)
timeout /t 1 /nobreak >nul

echo.
echo  ================================================
echo   AidsMonitoring  ^|  http://localhost:5503
echo  ================================================
echo.

start "" /b cmd /c "timeout /t 3 /nobreak >nul && start http://localhost:5503"

"%~dp0venv\Scripts\python.exe" -m uvicorn main:app --host 0.0.0.0 --port 5503
pause
"@ | Set-Content $startBat -Encoding ASCII
Write-OK "start.bat actualizado."

# ── 6. Acceso directo en escritorio ─────────────────────────────────────────
Write-Step 6 "Creando acceso directo en el escritorio..."

$desktop  = [Environment]::GetFolderPath("Desktop")
$shortcut = "$desktop\AidsMonitoring.lnk"
$shell = New-Object -ComObject WScript.Shell
$lnk   = $shell.CreateShortcut($shortcut)
$lnk.TargetPath       = $startBat
$lnk.WorkingDirectory = $APP
$lnk.WindowStyle      = 1
$lnk.Description      = "AidsMonitoring Maritime Traffic System"
$lnk.Save()
Write-OK "Acceso directo creado en el escritorio."

# ── 7. Zadig para RTL-SDR ────────────────────────────────────────────────────
Write-Host ""
Write-Host "  ============================================================" -ForegroundColor Yellow
Write-Host "   Driver RTL-SDR (NESDR SMArt v5) — paso OBLIGATORIO" -ForegroundColor Yellow
Write-Host "  ============================================================" -ForegroundColor Yellow
Write-Host ""
Write-Host "  Para que AIS-catcher funcione necesitas instalar WinUSB."
Write-Host "  Esto solo se hace UNA VEZ por computadora."
Write-Host ""
Write-Host "  Pasos:"
Write-Host "    1. Conecta el NESDR SMArt v5 al USB"
Write-Host "    2. Se abrira Zadig automaticamente"
Write-Host "    3. Menu: Options -> List All Devices"
Write-Host "    4. Selecciona 'RTL2838UHIDIR' o 'Bulk-In, Interface 0'"
Write-Host "    5. Driver destino: WinUSB"
Write-Host "    6. Click 'Install Driver'"
Write-Host ""

$zadig = Join-Path $APP "tools\zadig.exe"
if (-not (Test-Path $zadig)) {
    $resp = Read-Host "  Descargar Zadig ahora? [S/N]"
    if ($resp -match "^[Ss]") {
        Write-Host "  Descargando Zadig..." -ForegroundColor Yellow
        try {
            Invoke-WebRequest -Uri "https://zadig.akeo.ie/downloads/zadig-2.9.exe" `
                              -OutFile $zadig -UseBasicParsing
            Write-OK "Zadig descargado."
        } catch {
            Write-Warn "No se pudo descargar Zadig. Descargalo manualmente desde zadig.akeo.ie"
        }
    }
}

if (Test-Path $zadig) {
    $resp = Read-Host "  Abrir Zadig ahora? [S/N]"
    if ($resp -match "^[Ss]") { Start-Process $zadig }
}

# ── Fin ──────────────────────────────────────────────────────────────────────
Write-Host ""
Write-Host "  ============================================================" -ForegroundColor Green
Write-Host "   Instalacion completada!" -ForegroundColor Green
Write-Host "  ============================================================" -ForegroundColor Green
Write-Host ""
Write-Host "  Para iniciar AidsMonitoring:" -ForegroundColor White
Write-Host "    - Doble click en el acceso directo del escritorio, o"
Write-Host "    - Ejecuta start.bat"
Write-Host ""
Write-Host "  El navegador se abrira automaticamente en http://localhost:5503"
Write-Host ""
Write-Host "  Usuario por defecto:  admin / admin" -ForegroundColor Cyan
Write-Host ""
Read-Host "Presiona Enter para salir"
