[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
    $agent_proc = Get-Process -Name "proxy-agent" | Select-Object -First 1
    $frpc_proc = Get-Process -Name "frpc" | Select-Object -First 1
    $gost_proc = Get-Process -Name "gost" | Select-Object -First 1
    
    $agent_status = if ($agent_proc) { "Running (PID $($agent_proc.Id))" } else { "STOPPED" }
    $frpc_status = if ($frpc_proc) { "Running (PID $($frpc_proc.Id))" } else { "STOPPED" }
    $gost_status = if ($gost_proc) { "Running (PID $($gost_proc.Id))" } else { "STOPPED" }
    
    Write-Host "Agent: $agent_status" -ForegroundColor $(if ($agent_proc) { "Green" } else { "Red" })
    Write-Host "FRPC : $frpc_status" -ForegroundColor $(if ($frpc_proc) { "Green" } else { "Red" })
    Write-Host "GOST : $gost_status" -ForegroundColor $(if ($gost_proc) { "Green" } else { "Red" })
    Write-Host ""
    Write-Host "--------------------------------------------------------"
    
    # Read last 5 lines of logs safely
    Write-Host "`n[ Agent Log ]" -ForegroundColor Yellow
    if (Test-Path "proxy-agent-error.log") {
        Get-Content "proxy-agent-error.log" -Tail 5 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
    } elseif (Test-Path "proxy-agent.log") {
        Get-Content "proxy-agent.log" -Tail 5 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
    } else {
        Write-Host "  Log file not generated yet." -ForegroundColor DarkGray
    }
    
    Write-Host "`n[ FRPC Log ]" -ForegroundColor Yellow
    if (Test-Path "frpc.log") {
        Get-Content "frpc.log" -Tail 5 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
    } elseif (Test-Path "frpc-error.log") {
        Get-Content "frpc-error.log" -Tail 5 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
    } else {
        Write-Host "  Log file not generated yet." -ForegroundColor DarkGray
    }
    
    Write-Host "`n[ GOST Log ]" -ForegroundColor Yellow
    if (Test-Path "gost-error.log") {
        Get-Content "gost-error.log" -Tail 5 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
    } elseif (Test-Path "gost.log") {
        Get-Content "gost.log" -Tail 5 | ForEach-Object { Write-Host "  $_" -ForegroundColor Gray }
    } 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

