[CmdletBinding()]
param()

$previousErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'

while ($true) {
    Clear-Host
    Write-Host "=== AI-Network Node Monitor ===" -ForegroundColor Cyan
    Write-Host "Timestamp: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
    Write-Host ""
    
    # Check processes
    $proxy_proc = Get-Process -Name "proxy-node" | Select-Object -First 1
    $frpc_proc = Get-Process -Name "frpc" | Select-Object -First 1
    
    $proxy_status = if ($proxy_proc) { "Running (PID $($proxy_proc.Id))" } else { "STOPPED" }
    $frpc_status = if ($frpc_proc) { "Running (PID $($frpc_proc.Id))" } else { "STOPPED" }
    
    Write-Host "Proxy: $proxy_status" -ForegroundColor $(if ($proxy_proc) { "Green" } else { "Red" })
    Write-Host "FRPC : $frpc_status" -ForegroundColor $(if ($frpc_proc) { "Green" } else { "Red" })
    Write-Host ""
    Write-Host "--------------------------------------------------------"
    
    # Read last 5 lines of logs safely
    Write-Host "`n[ Proxy-Node Log ]" -ForegroundColor Yellow
    if (Test-Path "proxy-node-error.log") {
        $content = Get-Content "proxy-node-error.log" -Tail 5
        if ($content) { $content | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray } }
        else { Write-Host "  (empty)" -ForegroundColor DarkGray }
    } elseif (Test-Path "proxy-node.log") {
        $content = Get-Content "proxy-node.log" -Tail 5
        if ($content) { $content | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray } }
        else { Write-Host "  (empty)" -ForegroundColor DarkGray }
    } else {
        Write-Host "  Log file not generated yet." -ForegroundColor DarkGray
    }
    
    Write-Host "`n[ FRPC Log ]" -ForegroundColor Yellow
    if (Test-Path "frpc.log") {
        $content = Get-Content "frpc.log" -Tail 5
        if ($content) { $content | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray } }
        else { Write-Host "  (empty)" -ForegroundColor DarkGray }
    } elseif (Test-Path "frpc-error.log") {
        $content = Get-Content "frpc-error.log" -Tail 5
        if ($content) { $content | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray } }
        else { Write-Host "  (empty)" -ForegroundColor DarkGray }
    } else {
        Write-Host "  Log file not generated yet." -ForegroundColor DarkGray
    }
    
    Write-Host "`n--------------------------------------------------------"
    Write-Host "Press Ctrl+C to stop monitoring (apps will keep running in the background)..." -ForegroundColor White
    
    Start-Sleep -Seconds 2
}

$ErrorActionPreference = $previousErrorActionPreference
