# Cortex Agent Windows One-Liner Provisioner
Write-Host "🚀 Starting Cortex Agent Provisioning for node: {{ node_id }}" -ForegroundColor Cyan

$installDir = "C:\CortexAgent"
if (!(Test-Path $installDir)) {
    New-Item -ItemType Directory -Path $installDir | Out-Null
}
Set-Location $installDir

# 1. Write agent_config.yaml
Write-Host "[*] Writing configuration..." -ForegroundColor Gray
$configContent = @"
{{ config_yaml.replace('—', '-') }}
"@
$configPath = Join-Path $installDir "agent_config.yaml"
$utf8NoBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllText($configPath, $configContent, $utf8NoBom)

# 2. Download bootstrap_windows.ps1
$installerUrl = "{{ base_url }}/api/v1/agent/installer/ps1"
$installerPath = Join-Path $installDir "bootstrap_windows.ps1"
Write-Host "[*] Downloading installer from $installerUrl ..." -ForegroundColor Gray

try {
    Invoke-WebRequest -Uri $installerUrl -OutFile $installerPath
} catch {
    Write-Host "❌ Failed to download installer: $_" -ForegroundColor Red
    exit 1
}

# 3. Run bootstrap_windows.ps1
Write-Host "[*] Bootstrapping agent..." -ForegroundColor Cyan
powershell.exe -ExecutionPolicy Bypass -File $installerPath -HubUrl "{{ base_url }}" -GrpcUrl "{{ grpc_url }}" -AuthToken "{{ invite_token }}" -NodeId "{{ node_id }}" -Tls "{% if tls %}true{% else %}false{% endif %}" -SecretKey "{{ secret_key }}" -RegisterService -AutoRun
