$ErrorActionPreference = 'Stop'

$kioskUrl = 'http://localhost:3000/'
$kioskPort = 3000
$readyTimeoutSeconds = 120
$edgeArgs = @(
    '--kiosk', $kioskUrl,
    '--edge-kiosk-type=fullscreen',
    '--no-first-run',
    '--disable-pinch'
)

function Test-EmmaKioskPortListening {
    param([int]$Port)
    return [bool](Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue)
}

function Wait-EmmaKioskReady {
    param(
        [string]$Url,
        [int]$Port,
        [int]$TimeoutSeconds
    )

    Write-Host "Warte auf Emma Local (Port $Port, max. ${TimeoutSeconds}s)..."
    $sw = [System.Diagnostics.Stopwatch]::StartNew()
    while ($sw.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
        if (Test-EmmaKioskPortListening -Port $Port) {
            try {
                Invoke-WebRequest -Uri $Url -UseBasicParsing -TimeoutSec 3 | Out-Null
                Write-Host "Emma Local bereit auf $Url"
                return $true
            }
            catch {
                # Port is listening but HTTP not ready yet.
                Write-Verbose "HTTP noch nicht bereit: $($_.Exception.Message)"
            }
        }
        Start-Sleep -Seconds 1
    }

    Write-Warning "Emma Local antwortet nicht nach ${TimeoutSeconds}s - Edge-Kiosk wird nicht gestartet"
    return $false
}

if (Get-Process -Name 'msedge' -ErrorAction SilentlyContinue) {
    Write-Host 'Microsoft Edge laeuft bereits.'
    exit 0
}

if (-not (Wait-EmmaKioskReady -Url $kioskUrl -Port $kioskPort -TimeoutSeconds $readyTimeoutSeconds)) {
    exit 1
}

Start-Process 'msedge.exe' -ArgumentList $edgeArgs
Write-Host "Edge Kiosk gestartet: $kioskUrl"
