# Fix Siraya print agent when service shows Running but port 5000 is dead.
$ErrorActionPreference = "Stop"
$LogFile = Join-Path $env:TEMP "SirayaPrinter-Fix.log"
$InstallDir = Join-Path $env:ProgramFiles "Siraya\Printer"
$DataDir = Join-Path $env:ProgramData "Siraya\Printer"
$NodeExe = Join-Path $InstallDir "runtime\node.exe"
$IndexJs = Join-Path $InstallDir "index.js"
$StartBat = Join-Path $InstallDir "start-agent.bat"

function Log($msg) {
  $line = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $msg"
  Add-Content -Path $LogFile -Value $line
  Write-Host $msg
}

function Find-HealthPort {
  try {
    $r = Invoke-WebRequest -Uri "http://127.0.0.1:5000/health" -UseBasicParsing -TimeoutSec 2
    if ($r.StatusCode -eq 200) { return 5000 }
  } catch { }
  return $null
}

function Ensure-StartBat {
  if (Test-Path -LiteralPath $StartBat) { return }
  $content = @(
    '@echo off',
    'cd /d "%~dp0"',
    '"%~dp0runtime\node.exe" "%~dp0index.js"'
  ) -join "`r`n"
  Set-Content -LiteralPath $StartBat -Value $content -Encoding ASCII
  Log "Created start-agent.bat"
}

function Get-TaskRunAsUser {
  if ($env:USERDOMAIN -and $env:USERNAME) {
    return "$env:USERDOMAIN\$env:USERNAME"
  }
  return $env:USERNAME
}

function Register-Task {
  Ensure-StartBat
  $runAs = Get-TaskRunAsUser
  schtasks /Delete /TN "SirayaPrinterAgent" /F 2>$null | Out-Null
  schtasks /Create /TN "SirayaPrinterAgent" /TR "`"$StartBat`"" /SC ONLOGON /RU $runAs /RL HIGHEST /F | Out-Null
  Log "Registered scheduled task SirayaPrinterAgent (ONLOGON as $runAs)"
}

Log "=== Siraya printer agent fix ==="

if (-not (Test-Path -LiteralPath $IndexJs)) {
  Log "ERROR: Not installed at $InstallDir"
  Log "Download from https://pos.siraya.food/downloads/printer/ and run Install.cmd"
  Read-Host "Press Enter"
  exit 1
}

if (-not (Test-Path -LiteralPath $NodeExe)) {
  Log "ERROR: Missing $NodeExe"
  Read-Host "Press Enter"
  exit 1
}

$existing = Find-HealthPort
if ($existing) {
  Log "Agent already healthy on port $existing"
  Start-Process "http://127.0.0.1:$existing/"
  Read-Host "Press Enter"
  exit 0
}

Log "Stopping Windows service (if any)..."
  try { schtasks /End /TN "SirayaPrinterAgent" 2>$null | Out-Null } catch { }
  try { net stop SirayaPrinterService 2>$null | Out-Null } catch { }
Start-Sleep -Seconds 2

Log "Killing stale node processes for Siraya..."
Get-Process -Name node -ErrorAction SilentlyContinue | ForEach-Object {
  try {
    $cmd = (Get-CimInstance Win32_Process -Filter "ProcessId=$($_.Id)").CommandLine
    if ($cmd -and $cmd -like "*Siraya\Printer*") {
      Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue
      Log "Stopped PID $($_.Id)"
    }
  } catch { }
}

Register-Task

Log "Starting agent in current user context..."
Start-Process -FilePath $StartBat -WindowStyle Hidden
Start-Sleep -Seconds 5

$port = Find-HealthPort
if (-not $port) {
  Log "Slow start - waiting longer..."
  Start-Sleep -Seconds 8
  $port = Find-HealthPort
}

if (-not $port) {
  Log "ERROR: Still no health on http://127.0.0.1:5000"
  Log "Check: $DataDir\logs\error.log"
  Log "Log: $LogFile"
  if (Test-Path "$DataDir\logs\error.log") {
    Get-Content "$DataDir\logs\error.log" -Tail 15 | ForEach-Object { Log $_ }
  }
  Read-Host "Press Enter"
  exit 1
}

Log "SUCCESS - agent on port $port"
try { net start SirayaPrinterService 2>$null | Out-Null } catch { }
Start-Process "http://127.0.0.1:$port/"
Read-Host "Press Enter"
exit 0
