param(
  [string]$ProjectPath = $PSScriptRoot.Replace('\tools',''),
  [string]$TurnKeyId = '',
  [string]$TurnApiToken = '',
  [int]$Ttl = 86400
)

$ErrorActionPreference = 'Stop'

function Read-Required($PromptText) {
  do { $v = Read-Host $PromptText } while ([string]::IsNullOrWhiteSpace($v))
  return $v.Trim()
}

function Set-PhpDefine($Content, $Name, $Value, [switch]$Numeric) {
  if ($Numeric) { $replacement = "define('$Name', $Value);" }
  else {
    $escaped = $Value.Replace("'", "\\'")
    $replacement = "define('$Name', '$escaped');"
  }
  $pattern = "define\('$Name',\s*.*?\);"
  if ($Content -match $pattern) {
    return [regex]::Replace($Content, $pattern, $replacement, 1)
  }
  return $Content + "`r`n" + $replacement + "`r`n"
}

if ([string]::IsNullOrWhiteSpace($TurnKeyId)) { $TurnKeyId = Read-Required 'Paste Cloudflare TURN Key ID / UID' }
if ([string]::IsNullOrWhiteSpace($TurnApiToken)) { $TurnApiToken = Read-Required 'Paste Cloudflare TURN API token / key' }

$config = Join-Path $ProjectPath 'api\config.php'
$appjs  = Join-Path $ProjectPath 'js\app.js'
$endpoint = Join-Path $ProjectPath 'api\cloudflare_turn.php'

if (!(Test-Path $config)) { throw "Missing $config" }
if (!(Test-Path $appjs))  { throw "Missing $appjs" }
if (!(Test-Path $endpoint)) { throw "Missing $endpoint. Use the enhanced Spaceship package first." }

$stamp = Get-Date -Format 'yyyyMMdd_HHmmss'
Copy-Item $config "$config.bak_$stamp"
Copy-Item $appjs  "$appjs.bak_$stamp"

$content = Get-Content $config -Raw
if ($content -notmatch 'CLOUDFLARE_TURN_KEY_ID') {
  $insert = @"

// ── Cloudflare Realtime / Calls TURN ─────────────────────────
define('CLOUDFLARE_TURN_KEY_ID', '');
define('CLOUDFLARE_TURN_API_TOKEN', '');
define('CLOUDFLARE_TURN_TTL', 86400);
"@
  $content = $content -replace "define\('GIF_API_KEY',\s*'.*?'\);", { param($m) $m.Value + $insert }
}
$content = Set-PhpDefine $content 'CLOUDFLARE_TURN_KEY_ID' $TurnKeyId
$content = Set-PhpDefine $content 'CLOUDFLARE_TURN_API_TOKEN' $TurnApiToken
$content = Set-PhpDefine $content 'CLOUDFLARE_TURN_TTL' $Ttl -Numeric
Set-Content $config $content -Encoding UTF8

$js = Get-Content $appjs -Raw
$js = [regex]::Replace($js, "var\s+METERED_TURN_API_URL\s*=\s*['\"].*?['\"];", "var METERED_TURN_API_URL = 'api/cloudflare_turn.php';", 1)
Set-Content $appjs $js -Encoding UTF8

Write-Host ''
Write-Host 'Cloudflare TURN configured for Spaceship.' -ForegroundColor Green
Write-Host "Backups created: $config.bak_$stamp and $appjs.bak_$stamp"
Write-Host 'Restart Apache and press Ctrl+F5 in the browser.'
