#requires -Version 7.0
[CmdletBinding(SupportsShouldProcess,ConfirmImpact='High')]
param([string]$SubscriptionId,[string]$Location='westeurope',[string]$VmSize='Standard_B1s')
. "$PSScriptRoot/MonitorPrivateLink.Common.ps1"
Initialize-Context $PSScriptRoot $SubscriptionId $Location $VmSize 30
if (-not $script:State) { throw 'Ownership state missing. Refusing inferred cleanup.' }
$account=Invoke-Az @('account','show')
if ($account.id -ne $script:State.Subscription -or ($SubscriptionId -and $SubscriptionId -ne $account.id)) { throw 'Subscription mismatch.' }
if ($script:State.GroupId -ne "/subscriptions/$($account.id)/resourceGroups/rg-ampls-deepdive-we") { throw 'Unexpected cleanup target.' }
$exists=Invoke-Az @('group','exists','--name',$script:Rg)
if ($exists) {
    Assert-Ownership
    # Refuse to delete a group into which an unrelated top-level resource has been added.
    $items=Invoke-Az @('resource','list','--resource-group',$script:Rg)
    foreach ($item in $items) {
        if ($item.type -in @('Microsoft.Compute/disks','Microsoft.Network/networkInterfaces')) {
            # Disks/PE NICs are Azure-created dependants: check exact attachment instead of assuming by name.
            if ($item.type -eq 'Microsoft.Compute/disks') {
                $disk=Invoke-Arm GET $item.id '2024-03-02'
                $allowed=@((Resource-Id 'Microsoft.Compute/virtualMachines' 'vm-ampls-inside'),(Resource-Id 'Microsoft.Compute/virtualMachines' 'vm-ampls-outside'))
                if ($disk.managedBy -notin $allowed -and $item.tags['session'] -ne $script:State.Session) { throw 'Unowned/unattached disk in workshop group; refusing deletion.' }
            } elseif ($item.id -notin $script:State.Resources) {
                $pe=Invoke-Arm GET (Resource-Id 'Microsoft.Network/privateEndpoints' 'pe-ampls') $script:Api.Network -MissingOkay
                if (-not $pe -or $item.id -notin @($pe.properties.networkInterfaces | ForEach-Object {$_.id})) { throw 'Unowned NIC in workshop group.' }
            }
        } elseif ($item.id -notin $script:State.Resources -and $item.type -notmatch '/(extensions|tables|virtualNetworkLinks)$') { throw 'Unexpected resource in workshop group; review locally before cleanup.' }
    }
    if (-not $PSCmdlet.ShouldProcess($script:Rg,'Delete exact session-owned AMPLS associations and resource group')) { return }
    $amplsId=Resource-Id 'Microsoft.Insights/privateLinkScopes' 'ampls-deepdive'
    if (Invoke-Arm GET $amplsId $script:Api.Ampls -MissingOkay) {
        foreach ($name in @('workspace','dce')) {
            if (Invoke-Arm GET "$amplsId/scopedResources/$name" $script:Api.Ampls -MissingOkay) {
                $null=Invoke-Arm DELETE "$amplsId/scopedResources/$name" $script:Api.Ampls
            }
        }
    }
    $null=Invoke-Az @('group','delete','--name',$script:Rg,'--yes','--no-wait')
    $deadline=[datetime]::UtcNow.AddMinutes(40)
    while (Invoke-Az @('group','exists','--name',$script:Rg)) {
        if ([datetime]::UtcNow -gt $deadline) { throw 'Deletion still pending. Runtime state retained for safe retry.' }
        Start-Sleep 15
    }
} elseif (-not $PSCmdlet.ShouldProcess($script:Runtime,'Remove private runtime after verifying Azure group is absent')) { return }
$report=@{GroupDeleted=$true;PrivateRuntimeRemoval='Authorized after absence verification';ExistingNetworkWatcherUnchanged=$true;ProviderRegistrationsUnchanged=$true;ObservedUtc=[datetime]::UtcNow.ToString('o')}
$evidence=Join-Path $PSScriptRoot 'evidence'
$null=New-Item -ItemType Directory -Path $evidence -Force
[IO.File]::WriteAllText((Join-Path $evidence 'cleanup.json'),($report | ConvertTo-Json),[Text.UTF8Encoding]::new($false))
$target=[IO.Path]::GetFullPath($script:Runtime)
$expected=[IO.Path]::GetFullPath((Join-Path (Split-Path (Split-Path $script:Bundle)) 'work/azure-monitor-private-link-deep-dive'))
if ($target -ne $expected -or (Split-Path $target -Leaf) -ne 'azure-monitor-private-link-deep-dive') { throw 'Runtime deletion path validation failed.' }
if ((Get-Item -LiteralPath $target).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Runtime is a link; refusing recursive deletion.' }
Remove-Item -LiteralPath $target -Recurse -Force
Write-Host 'Cleanup complete. Private runtime removed; reusable bundle preserved.'
