$ErrorActionPreference = 'Stop'
if (-not (Get-Command go -ErrorAction SilentlyContinue)) {
  throw 'go tidak ditemukan.'
}

$cmd = 'cd "' + $PSScriptRoot + '"; go run .'
$proc = Start-Process powershell -ArgumentList '-NoExit','-ExecutionPolicy','Bypass','-Command', $cmd -PassThru

$ready = $false
for ($i = 0; $i -lt 20; $i++) {
  Start-Sleep -Milliseconds 500
  try {
    $resp = Invoke-WebRequest -UseBasicParsing -Uri 'http://localhost:8080/api/health' -TimeoutSec 2
    if ($resp.StatusCode -eq 200) {
      $ready = $true
      break
    }
  } catch { }

  if ($proc.HasExited) {
    break
  }
}

if ($ready) {
  Start-Process 'http://localhost:8080/'
  Write-Output 'Service Watch Dashboard dibuka di browser: http://localhost:8080/'
} else {
  Write-Output 'Service Watch Dashboard sedang start atau gagal dibuka. Cek jendela PowerShell baru untuk detail.'
}
