$ErrorActionPreference = "Stop"

$Project = Join-Path $PSScriptRoot "brain-h5"
$Launcher = Join-Path $Project "scripts\start-local.cmd"
$Url = "http://127.0.0.1:4173/"

if (-not (Test-Path -LiteralPath $Project)) {
  throw "Project folder not found: $Project"
}

if (-not (Test-Path -LiteralPath $Launcher)) {
  throw "Launcher not found: $Launcher"
}

Write-Host "Starting Brain H5..."
Write-Host "Project: $Project"
Write-Host "Url: $Url"

$server = [System.Diagnostics.ProcessStartInfo]::new()
$server.FileName = "cmd.exe"
$server.Arguments = "/k `"$Launcher`""
$server.WorkingDirectory = $Project
$server.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized
$server.UseShellExecute = $true
[System.Diagnostics.Process]::Start($server) | Out-Null

$deadline = (Get-Date).AddMinutes(6)
do {
  try {
    $response = Invoke-WebRequest -UseBasicParsing -Uri $Url -TimeoutSec 2
    if ($response.StatusCode -eq 200) {
      Write-Host "Brain H5 is ready. Opening browser..."
      Start-Process $Url
      exit 0
    }
  } catch {
    Start-Sleep -Seconds 1
  }
} while ((Get-Date) -lt $deadline)

Write-Host ""
Write-Host "Startup timed out. Check the minimized server window for errors."
Write-Host "You can also open this URL after the server is ready: $Url"
exit 1
