# Build firmware .bin using PlatformIO
# Usage: powershell -ExecutionPolicy Bypass -File tools/build_firmware.ps1

[CmdletBinding()]
param(
    [string]$EnvName = "nodemcuv2",
    [switch]$VerboseOutput
)

$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest

function Resolve-PioPath {
    try {
        $cmd = Get-Command pio -ErrorAction Stop
        return $cmd.Path
    } catch {
        # Fallback típico de VS Code PlatformIO en Windows
        $cand = Join-Path $env:USERPROFILE ".platformio/penv/Scripts/pio.exe"
        if (Test-Path $cand) { return $cand }

        # Instalación vía pip --user (Roaming) para Python 3.12
        $cand = Join-Path $env:APPDATA "Python/Python312/Scripts/pio.exe"
        if (Test-Path $cand) { return $cand }

        # Instalación local de Python (winget) típica
        $cand = Join-Path $env:LocalAppData "Programs/Python/Python312/Scripts/pio.exe"
        if (Test-Path $cand) { return $cand }

        return $null
    }
}

function Write-Info($msg) { Write-Host "[INFO] $msg" -ForegroundColor Cyan }
function Write-Ok($msg)   { Write-Host "[ OK ] $msg" -ForegroundColor Green }
function Write-Warn($msg) { Write-Host "[WARN] $msg" -ForegroundColor Yellow }
function Write-Err($msg)  { Write-Host "[ERR ] $msg" -ForegroundColor Red }

# Resolve paths
$repoRoot   = Split-Path -Parent $PSScriptRoot
$firmDir    = Join-Path $repoRoot 'firmware'
$assetsDir  = Join-Path $repoRoot 'assets/flash/firmware'
$outLatest  = Join-Path $firmDir 'firmware.bin'
$buildDir   = Join-Path $firmDir ".pio/build/$EnvName"
$builtBin   = Join-Path $buildDir 'firmware.bin'

# Ensure PlatformIO is available
$pio = Resolve-PioPath
if (-not $pio) {
    Write-Err "No se encontró PlatformIO (pio). Instálalo desde https://platformio.org/install"
    Write-Host "Opciones de instalación:" -ForegroundColor Yellow
    Write-Host "  1) VS Code extension PlatformIO IDE (recomendado)" -ForegroundColor Yellow
    Write-Host "  2) Python:  python -m pip install -U platformio" -ForegroundColor Yellow
    exit 1
}
try {
    $pioVersion = & $pio --version
    Write-Ok "PlatformIO detectado: $pioVersion"
} catch {
    Write-Err ("No se pudo ejecutar PlatformIO en '{0}': {1}" -f $pio, $_)
    exit 1
}

# Ensure folders exist
if (-not (Test-Path $firmDir)) { Write-Err "No existe directorio de firmware: $firmDir"; exit 1 }
if (-not (Test-Path $assetsDir)) { Write-Info "Creando carpeta de artefactos: $assetsDir"; New-Item -ItemType Directory -Force -Path $assetsDir | Out-Null }

# Build
Push-Location $firmDir
try {
    Write-Info "Compilando (env=$EnvName) en $firmDir ..."
    $args = @('run','-e', $EnvName)
    if ($VerboseOutput) { $args += '-v' }
    & $pio @args
    Write-Ok "Compilación finalizada"
} catch {
    Pop-Location
    Write-Err "Fallo al compilar con PlatformIO: $_"
    exit 1
}
Pop-Location

# Locate built binary
if (-not (Test-Path $builtBin)) {
    Write-Err "No se encontró el binario construido en: $builtBin"
    exit 1
}

# Copy as latest
try {
    Copy-Item -Path $builtBin -Destination $outLatest -Force
    Write-Ok "Binario actualizado: $outLatest"
} catch {
    Write-Err ("No se pudo copiar a {0}: {1}" -f $outLatest, $_)
}

# Copy timestamped artifact to assets for OTA/flash hosting
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$artifactName = "esp8266-$EnvName-$stamp.bin"
$artifactPath = Join-Path $assetsDir $artifactName
try {
    Copy-Item -Path $builtBin -Destination $artifactPath -Force
    Write-Ok "Artefacto generado: $artifactPath"
} catch {
    Write-Warn ("No se pudo copiar artefacto a assets: {0}" -f $_)
}

Write-Host ""; Write-Ok "Listo"
Write-Host "- Bin generado: $builtBin"
Write-Host "- Copia rápida: $outLatest"
Write-Host "- Artefacto:    $artifactPath"
