param(
  [string]$EvidenceDate = (Get-Date -Format 'yyyy-MM-dd')
)

$ErrorActionPreference = 'Stop'

$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$evidenceRoot = Join-Path $projectRoot "docs\evidence\ops\$EvidenceDate\alerting"
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$drillRoot = Join-Path $evidenceRoot $timestamp
$renderedConfigPath = Join-Path $drillRoot 'alertmanager.rendered.yaml'
$reportPath = Join-Path $drillRoot 'ALERTMANAGER_RENDER_DRILL.md'

New-Item -ItemType Directory -Force $evidenceRoot, $drillRoot | Out-Null

$env:ALERTMANAGER_DEFAULT_TO = 'ops-team@example.org'
$env:ALERTMANAGER_CRITICAL_TO = 'critical-oncall@example.org'
$env:ALERTMANAGER_WARNING_TO = 'warning-oncall@example.org'
$env:ALERTMANAGER_FROM = 'alertmanager@example.org'
$env:ALERTMANAGER_SMARTHOST = 'smtp.example.org:587'
$env:ALERTMANAGER_AUTH_USERNAME = 'alertmanager@example.org'
$env:ALERTMANAGER_AUTH_PASSWORD = 'synthetic-secret-for-render-drill'

try {
  & (Join-Path $PSScriptRoot 'render-alertmanager-config.ps1') `
    -TemplatePath (Join-Path $projectRoot 'deployment\alertmanager\alertmanager.yml') `
    -OutputPath $renderedConfigPath | Out-Null
} finally {
  Remove-Item Env:ALERTMANAGER_DEFAULT_TO -ErrorAction SilentlyContinue
  Remove-Item Env:ALERTMANAGER_CRITICAL_TO -ErrorAction SilentlyContinue
  Remove-Item Env:ALERTMANAGER_WARNING_TO -ErrorAction SilentlyContinue
  Remove-Item Env:ALERTMANAGER_FROM -ErrorAction SilentlyContinue
  Remove-Item Env:ALERTMANAGER_SMARTHOST -ErrorAction SilentlyContinue
  Remove-Item Env:ALERTMANAGER_AUTH_USERNAME -ErrorAction SilentlyContinue
  Remove-Item Env:ALERTMANAGER_AUTH_PASSWORD -ErrorAction SilentlyContinue
}

$renderedContent = Get-Content $renderedConfigPath -Raw -Encoding UTF8
if ($renderedContent -match '\$\{[A-Z0-9_]+\}') {
  throw 'render drill failed: unresolved placeholders remained'
}

$reportLines = @(
  '# Alertmanager Render Drill',
  '',
  "- Generated at: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz')",
  "- Template file: $(Join-Path $projectRoot 'deployment\alertmanager\alertmanager.yml')",
  "- Rendered file: $renderedConfigPath",
  '- Synthetic secret values were injected through process environment variables for this drill only.',
  '- Result: template placeholders resolved successfully and the rendered config contains no unresolved `${ALERTMANAGER_*}` tokens.',
  '',
  '## Scope Note',
  '',
  '- This drill validates the config injection/rendering path only.',
  '- It does not prove real SMTP delivery, real contact routing, or production secret manager integration.',
  '',
  '## Evidence Files',
  '',
  "- $(Split-Path $renderedConfigPath -Leaf)",
  ''
)

Set-Content -Path $reportPath -Value ($reportLines -join [Environment]::NewLine) -Encoding UTF8
Get-Content $reportPath
