# clauth-watchdog.ps1
# Monitors clauth daemon on port 52437. Restarts it if not responding.
# Installed by: npm install -g @lifeaitools/clauth
# Managed by:   clauth watchdog [install|uninstall|status]

$clauth   = "$env:APPDATA\npm\clauth.cmd"
$logFile  = "$env:APPDATA\clauth\watchdog.log"
$pingUrl  = "http://127.0.0.1:52437/ping"
$interval = 15

function Write-Log($msg) {
    $ts   = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
    $line = "[$ts] $msg"
    Add-Content -Path $logFile -Value $line -ErrorAction SilentlyContinue
}

Write-Log "Watchdog started (PID $PID, clauth=$clauth)"

while ($true) {
    $alive = $false
    try {
        $r = Invoke-WebRequest -Uri $pingUrl -TimeoutSec 3 -UseBasicParsing -ErrorAction Stop
        if ($r.StatusCode -eq 200) { $alive = $true }
    } catch { }

    if (-not $alive) {
        Write-Log "Daemon not responding — restarting..."
        Start-Process -FilePath "cmd.exe" `
            -ArgumentList "/c `"$clauth`" serve start" `
            -WindowStyle Hidden
        Start-Sleep -Seconds 5
        try {
            $r = Invoke-WebRequest -Uri $pingUrl -TimeoutSec 5 -UseBasicParsing -ErrorAction Stop
            if ($r.StatusCode -eq 200) { Write-Log "Daemon restarted OK." }
            else { Write-Log "WARNING: Daemon still not responding." }
        } catch {
            Write-Log "WARNING: Daemon still not responding after restart."
        }
    }

    Start-Sleep -Seconds $interval
}
