#requires -Version 7.0
[CmdletBinding()]
param(
    [string]$SubscriptionId,
    [string]$Location = 'westeurope',
    [string]$VmSize = 'Standard_B1s',
    [ValidateRange(5,120)][int]$EvidenceTimeoutMinutes = 30,
    [ValidateSet('Preflight','Foundation','PublicBaseline','PrivateLink','Lockdown','AMA','TestBoundary','TestDnsRecovery','Validate','All')]
    [string]$Stage = 'Preflight'
)
. "$PSScriptRoot/MonitorPrivateLink.Common.ps1"
Initialize-Context $PSScriptRoot $SubscriptionId $Location $VmSize $EvidenceTimeoutMinutes
try {
    if ($Stage -eq 'Preflight') { Invoke-Preflight; return }
    if ($script:State -and $script:State['DnsDrillActive']) {
        Assert-Ownership
        Restore-MonitorDnsLink
        Write-Host 'Recovered the private DNS link after an interrupted drill. Repeat TestDnsRecovery before accepting validation.'
        $script:State.Completed.Remove('TestDnsRecovery')
        $script:State.Evidence.Remove('TestDnsRecovery')
        Save-State
    }
    $stages = if ($Stage -eq 'All') { @('Foundation','PublicBaseline','PrivateLink','Lockdown','AMA','TestBoundary','TestDnsRecovery','Validate') } else { @($Stage) }
    foreach ($item in $stages) {
        Write-Host "Stage: $item"
        if ($item -eq 'Foundation') { Invoke-Foundation }
        else { Assert-Ownership; & "Invoke-$item" }
        $script:State.Completed[$item] = [datetime]::UtcNow.ToString('o')
        Save-State
        Write-Host "PASS: $item"
    }
} catch {
    if (Test-Path $script:Runtime) {
        Write-PrivateJson 'last-error.json' @{Stage=$Stage;Time=[datetime]::UtcNow.ToString('o');Error=$_.ToString();Stack=$_.ScriptStackTrace}
    }
    throw "Stage $Stage failed. Inspect work/azure-monitor-private-link-deep-dive/last-error.json locally; do not publish raw errors."
}
