# =============================================================================
# ADA P1 Meter - Native Firmware Updater (Universal Port Detection)
# =============================================================================

$ErrorActionPreference = "Continue"

Write-Host "==============================================" -ForegroundColor Cyan
Write-Host "    ADA P1 Meter - Firmware Frissito          " -ForegroundColor Cyan
Write-Host "==============================================`n" -ForegroundColor Cyan

# 1. Portok keresese a PnP eszkozok kozott
# 1. Portok keresese (Kombinalt, atombiztos modszer)
Write-Host "[*] Eszkozok keresese..." -ForegroundColor Gray

# Eloszor megprobaljuk a PnP listat a szep nevek miatt
$pnpPorts = Get-WmiObject Win32_PnPEntity | Where-Object { $_.Name -match '\(COM\d+\)' }

# Lekerdezzuk a nyers portneveket is a rendszerbol
$rawPortNames = [System.IO.Ports.SerialPort]::GetPortNames() | Sort-Object -Unique

$ports = @()

if ($rawPortNames.Count -gt 0) {
    foreach ($rawName in $rawPortNames) {
        # Megkeressuk, hatha van hozza szep nevunk a PnP listaban
        $matchingPnp = $pnpPorts | Where-Object { $_.Name -contains "($rawName)" -or $_.Name -match "\($rawName\)" }
        
        if ($matchingPnp) {
            $ports += [PSCustomObject]@{ Name = $matchingPnp.Name; DeviceID = $rawName }
        } else {
            # Ha nincs szep nev, akkor is beletesszuk a nyers nevet, hogy lehessen flashelni!
            $ports += [PSCustomObject]@{ Name = "Soros eszkoz ($rawName)"; DeviceID = $rawName }
        }
    }
}

if ($ports.Count -eq 0) {
    Write-Host "[-] Nem talalhato aktiv COM port!" -ForegroundColor Red
    Read-Host "Nyomj Enter-t a kilepeshez..."
    exit
}

Write-Host "[+] Elerheto portok:" -ForegroundColor Yellow
$portMap = @{}
for ($i = 0; $i -lt $ports.Count; $i++) {
    $p = $ports[$i]
    $portMap[$i + 1] = $p.DeviceID
    Write-Host "  $($i + 1). $($p.Name)"
}

# 2. Port kivalasztasa
$selection = Read-Host "`nValasz ki a port sorszamat (1-$($ports.Count))"
if ($selection -match '^\d+$' -and $portMap.ContainsKey([int]$selection)) {
    $targetPort = $portMap[[int]$selection]
} else {
    Write-Host "[-] Ervenytelen valasztas!" -ForegroundColor Red
    Read-Host "Nyomj Enter-t a kilepeshez..."
    exit
}

# 3. Utvonalak (Firmware v1.7.2)
$PSScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition
$toolExe     = Join-Path $PSScriptRoot "tools\esptool.exe"
$binBoot     = Join-Path $PSScriptRoot "ada\ada_1_7_2.ino.bootloader.bin"
$binParts    = Join-Path $PSScriptRoot "ada\ada_1_7_2.ino.partitions.bin"
$binBootApp  = Join-Path $PSScriptRoot "ada\boot_app0.bin"
$binFirmware = Join-Path $PSScriptRoot "ada\ada_1_7_2.ino.bin"

if (-not (Test-Path $toolExe)) {
    Write-Host "[-] HIBA: Nem talalhato: $toolExe" -ForegroundColor Red
    Read-Host "Nyomj Enter-t a kilepeshez..."
    exit
}

# 4. Flasheles
Write-Host "`n>>> Firmware feltoltese: $targetPort" -ForegroundColor Green
& "$toolExe" --chip esp32 --port "$targetPort" --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode keep --flash_freq keep --flash_size keep 0x1000 "$binBoot" 0x8000 "$binParts" 0xe000 "$binBootApp" 0x10000 "$binFirmware"

if ($LASTEXITCODE -ne 0) {
    Write-Host "`n[-] HIBA a feltoltes soran!" -ForegroundColor Red
    Read-Host "Nyomj Enter-t a kilepeshez..."
    exit
}

# 5. Monitorozas (HTTP server started VAGY WiFi connected)
Write-Host "`n>>> Monitorozas inditasa (max 120 mp)..." -ForegroundColor Yellow
try {
    $portObj = New-Object System.IO.Ports.SerialPort $targetPort, 115200, None, 8, One
    $portObj.Open()
    $startTime = Get-Date
    $buffer = ""

    while ($portObj.IsOpen -and ((Get-Date) - $startTime).TotalSeconds -lt 120) {
        if ($portObj.BytesToRead -gt 0) {
            $data = $portObj.ReadExisting()
            $buffer += $data
            Write-Host $data -NoNewline
            
            # Ellenorzes mindket sikeres inditasi jelre
            if ($buffer -match "HTTP server started\." -or $buffer -match "WiFi connected") {
                Write-Host "`n`n[OK] Az ADA sikeresen elindult es csatlakozott!" -ForegroundColor Green
                break
            }
        }
        Start-Sleep -Milliseconds 100
    }
    $portObj.Close()
} catch {
    Write-Host "`n[!] Monitor hiba: $_" -ForegroundColor DarkYellow
}

Write-Host "`n=== KESZ ===" -ForegroundColor Cyan
Read-Host "Nyomj Enter-t a befejezeshez..."