$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $PSScriptRoot
Set-Location $root

$envFile = Join-Path $root ".env.production"
if (-not (Test-Path $envFile)) {
  Write-Error ".env.production not found. Create it from .env.production.template first."
}

Get-Content $envFile | ForEach-Object {
  $line = $_.Trim()
  if (-not $line -or $line.StartsWith("#")) {
    return
  }
  $parts = $line -split "=", 2
  if ($parts.Count -ne 2) {
    return
  }
  $name = $parts[0].Trim()
  $value = $parts[1].Trim()
  if ($name) {
    Set-Item -Path "Env:$name" -Value $value
  }
}

python scripts\local_stack.py start --force-restart
if ($LASTEXITCODE -ne 0) {
  exit $LASTEXITCODE
}

$amiHost = $env:ASTERISK_AMI_HOST
$amiPortValue = $env:ASTERISK_AMI_PORT
if (-not $amiPortValue) {
  $amiPortValue = "5038"
}
$amiPort = [int]$amiPortValue

$sftpHost = $env:ASTERISK_SFTP_HOST
$sftpPortValue = $env:ASTERISK_SFTP_PORT
if (-not $sftpPortValue) {
  $sftpPortValue = "22"
}
$sftpPort = [int]$sftpPortValue

if ($amiHost) {
  $ami = Test-NetConnection $amiHost -Port $amiPort -WarningAction SilentlyContinue
  Write-Host "AMI TCP check: $($ami.TcpTestSucceeded) (${amiHost}:$amiPort)"
}
if ($sftpHost) {
  $sftp = Test-NetConnection $sftpHost -Port $sftpPort -WarningAction SilentlyContinue
  Write-Host "SFTP TCP check: $($sftp.TcpTestSucceeded) (${sftpHost}:$sftpPort)"
}

python scripts\track9_preflight.py --base-url http://127.0.0.1:8080
if ($LASTEXITCODE -ne 0) {
  exit $LASTEXITCODE
}

Write-Host ""
Write-Host "Track 9 QA stack is up."
Write-Host "Next step: place real softphone call 1001 -> 7000."
