$ErrorActionPreference = "Stop"
$target = "D:\Docker\crawler\.env"
$parent = Split-Path -Parent $target
New-Item -ItemType Directory -Force -Path $parent | Out-Null

$defaults = [ordered]@{
  "CRAWLER_HOST" = "0.0.0.0"
  "CRAWLER_PORT" = "8114"
  "CRAWLER_PUBLIC_BASE_URL" = "https://crawler.prototype.prolicht.digital"
  "CRAWLER_HEADLESS" = "true"
  "CRAWLER_DOCKER" = "true"
  "CRAWLER_USE_XVFB" = "true"
  "DISPLAY" = ":99"
  "PYTHONUNBUFFERED" = "1"
}

$secretNames = @("GEMINI_API_KEY", "DEEPSEEK_API_KEY", "OPENAI_API_KEY")
$lines = New-Object System.Collections.Generic.List[string]
$lines.Add("# Generated from the current Windows environment. Do not commit this file.")
$lines.Add("# Generated at $(Get-Date -Format o)")

foreach ($name in $secretNames) {
  $value = [Environment]::GetEnvironmentVariable($name, "Process")
  if ([string]::IsNullOrWhiteSpace($value)) { $value = [Environment]::GetEnvironmentVariable($name, "User") }
  if ([string]::IsNullOrWhiteSpace($value)) { $value = [Environment]::GetEnvironmentVariable($name, "Machine") }
  if ($null -eq $value) { $value = "" }
  $value = $value -replace "`r", "" -replace "`n", ""
  $lines.Add("$name=$value")
}

foreach ($key in $defaults.Keys) {
  $lines.Add("$key=$($defaults[$key])")
}

Set-Content -LiteralPath $target -Value $lines -Encoding UTF8
Write-Host "Wrote $target"
