[CmdletBinding(SupportsShouldProcess,ConfirmImpact='High')]
param(
    [Parameter(Mandatory)]
    [ValidatePattern('^[0-9a-fA-F-]{36}$')]
    [string]$SubscriptionId,
    [switch]$Force
)

Set-StrictMode -Version Latest
$ErrorActionPreference='Stop'
. (Join-Path $PSScriptRoot 'GoldenImageWorkshop.Common.ps1')

$paths=Get-GoldenImageWorkshopPaths -ScriptRoot $PSScriptRoot
$state=Read-GoldenImageWorkshopState -Path $paths.StatePath
if ([string]$state.SubscriptionId -ne $SubscriptionId) { throw 'Subscription does not match the private runtime state.' }
$expectedGroups=@('rg-golden-images-deepdive-we','rg-golden-images-staging-v1-we','rg-golden-images-staging-v2-we')
if ((@($state.ResourceGroups) -join '|') -ne ($expectedGroups -join '|')) { throw 'Runtime state contains unexpected resource-group names.' }

$workspace=[System.IO.Path]::GetFullPath($paths.WorkspaceRoot).TrimEnd('\')
$runtime=[System.IO.Path]::GetFullPath($paths.RuntimeRoot).TrimEnd('\')
$expectedRuntime=[System.IO.Path]::GetFullPath((Join-Path $workspace 'work\azure-golden-images-deep-dive')).TrimEnd('\')
if ($runtime -ne $expectedRuntime -or -not $runtime.StartsWith("$workspace\",[System.StringComparison]::OrdinalIgnoreCase)) { throw 'Runtime cleanup path safety validation failed.' }

Invoke-GoldenImageAzCli -Arguments @('account','set','--subscription',$SubscriptionId) -Quiet | Out-Null
$existingGroups=@()
foreach ($name in $expectedGroups) {
    $group=Invoke-GoldenImageAzJson -Arguments @('group','show','--name',$name) -AllowFailure -Quiet
    if ($group) {
        if ([string]$group.tags.workshop -ne [string]$state.WorkshopTag -or [string]$group.tags.'workshop-session' -ne [string]$state.SessionId) { throw "Cleanup refused for unowned resource group $name." }
        $existingGroups+=$name
    }
}

$cleanup=[pscustomobject]@{
    Workshop='Azure Golden Images Deep Dive'
    RequestedUtc=[DateTime]::UtcNow.ToString('o')
    ExactResourceGroups=$expectedGroups
    OwnershipTagsVerified=$true
    ProviderBaselineRestorationPlanned=([string]$state.ProviderBaseline.'Microsoft.VirtualMachineImages' -ne 'Registered')
    Status=if($existingGroups.Count){'Pending deletion'}else{'Already absent'}
}
$cleanupPath=Join-Path $paths.EvidenceRoot 'cleanup-evidence.json'
Write-GoldenImageJson -InputObject $cleanup -Path $cleanupPath
Assert-GoldenImageSanitizedFile -Path $cleanupPath

if ($existingGroups.Count) {
    $approved=$Force -or $PSCmdlet.ShouldProcess(($existingGroups -join ', '),'Delete the exact tagged workshop resource groups and all contained image-build resources')
    if (-not $approved) { Write-Warning 'Cleanup was not approved.'; return }

    foreach ($templateName in @($state.V1TemplateName,$state.V2TemplateName)) {
        if (Invoke-GoldenImageAzJson -Arguments @('image','builder','show','--resource-group',$state.MainResourceGroup,'--name',$templateName) -AllowFailure -Quiet) {
            Invoke-GoldenImageAzCli -Arguments @('image','builder','delete','--resource-group',$state.MainResourceGroup,'--name',$templateName) -Quiet | Out-Null
        }
    }
    foreach ($name in @($state.StagingV1ResourceGroup,$state.StagingV2ResourceGroup,$state.MainResourceGroup)) {
        if ((Invoke-GoldenImageAzCli -Arguments @('group','exists','--name',$name,'--output','tsv') -Quiet).Output.Trim() -eq 'true') {
            Invoke-GoldenImageAzCli -Arguments @('group','delete','--name',$name,'--yes','--no-wait') -Quiet | Out-Null
        }
    }
    $deadline=[DateTime]::UtcNow.AddMinutes(35)
    do {
        $remaining=@($expectedGroups | Where-Object { (Invoke-GoldenImageAzCli -Arguments @('group','exists','--name',$_,'--output','tsv') -Quiet).Output.Trim() -eq 'true' })
        if ($remaining.Count -eq 0) { break }
        Start-Sleep -Seconds 20
    } while ([DateTime]::UtcNow -lt $deadline)
    if ($remaining.Count) { throw "Workshop groups still exist after cleanup wait: $($remaining -join ', ')" }
}

if ([string]$state.ProviderBaseline.'Microsoft.VirtualMachineImages' -ne 'Registered') {
    $remainingTemplates=@(Invoke-GoldenImageAzJson -Arguments @('image','builder','list') -AllowFailure -Quiet)
    if ($remainingTemplates.Count -eq 0) {
        Invoke-GoldenImageAzCli -Arguments @('provider','unregister','--namespace','Microsoft.VirtualMachineImages','--wait') -Quiet | Out-Null
    }
    else { Write-Warning 'Microsoft.VirtualMachineImages remains registered because non-workshop templates exist.' }
}

$cleanup.Status='Deleted and verified absent'
$cleanup | Add-Member -NotePropertyName CompletedUtc -NotePropertyValue ([DateTime]::UtcNow.ToString('o'))
Write-GoldenImageJson -InputObject $cleanup -Path $cleanupPath
Assert-GoldenImageSanitizedFile -Path $cleanupPath
if (Test-Path -LiteralPath $runtime) { Remove-Item -LiteralPath $runtime -Recurse -Force }
Write-Host 'The three tagged workshop resource groups were removed and private runtime state was deleted.' -ForegroundColor Green
