$ErrorActionPreference = "Stop"

function Test-IsAdministrator {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($identity)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

if (-not (Test-IsAdministrator)) {
    Write-Host "Administrator permission is required."
    Write-Host "A UAC prompt will be shown. Please approve it to remove stale Python 3.11.9 registry entries."
    $args = @(
        "-NoProfile",
        "-ExecutionPolicy", "Bypass",
        "-File", "`"$PSCommandPath`""
    )
    $p = Start-Process -FilePath "powershell.exe" -ArgumentList $args -Verb RunAs -Wait -PassThru
    exit $p.ExitCode
}

$base = Split-Path -Parent $PSCommandPath
$stamp = Get-Date -Format "yyyyMMdd_HHmmss"
$backup = Join-Path $base "python311_registry_backup_$stamp"
$logPath = Join-Path $backup "cleanup_python311.log"
New-Item -ItemType Directory -Path $backup -Force | Out-Null

Start-Transcript -Path $logPath -Force | Out-Null

try {
    Write-Host "MCAT Python 3.11.9 stale registry cleanup"
    Write-Host "Backup folder: $backup"
    Write-Host ""

    $targets = @(
        @{ Code = "{1D653E80-09B2-40AB-9530-7DF12E632F8A}"; Label = "pip Bootstrap" },
        @{ Code = "{29CEC70F-9D96-472B-B6A1-AE7578376985}"; Label = "Utility Scripts" },
        @{ Code = "{425B36E9-4EA6-47B4-88C3-E798BA903188}"; Label = "Documentation" },
        @{ Code = "{57AC2A86-EC99-4E9C-9FF9-15DAA88D1FAE}"; Label = "TclTk Support" },
        @{ Code = "{9AFDC691-40E5-4B15-835F-9A524AC4672C}"; Label = "Standard Library" },
        @{ Code = "{B074012B-9B85-4049-BA01-A58A8C4C2236}"; Label = "Core Interpreter" },
        @{ Code = "{C038789C-DCB5-42D3-8C51-3BC9DDB26B90}"; Label = "Executables" },
        @{ Code = "{CEE03ABD-D5F9-4104-BFA5-520711B8D71F}"; Label = "Development Libraries" }
    )

    $removed = New-Object System.Collections.Generic.List[string]
    $skipped = New-Object System.Collections.Generic.List[string]

    foreach ($target in $targets) {
        $code = $target.Code
        $keyPath = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\$code"
        if (-not (Test-Path -LiteralPath $keyPath)) {
            continue
        }

        $props = Get-ItemProperty -LiteralPath $keyPath
        if ($props.DisplayName -notlike "Python 3.11.9*") {
            $skipped.Add("Unexpected uninstall key: $code / $($props.DisplayName)")
            continue
        }

        $safe = $code.Trim("{}")
        $nativePath = "HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\$code"
        & reg.exe export $nativePath (Join-Path $backup "uninstall_$safe.reg") /y | Out-Null
        Remove-Item -LiteralPath $keyPath -Recurse -Force
        $removed.Add("Uninstall: $($props.DisplayName)")
    }

    $userDataRoot = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData"
    if (Test-Path -LiteralPath $userDataRoot) {
        Get-ChildItem -LiteralPath $userDataRoot -ErrorAction SilentlyContinue | ForEach-Object {
            $sid = $_.PSChildName
            $productsPath = Join-Path $_.PSPath "Products"
            if (-not (Test-Path -LiteralPath $productsPath)) {
                return
            }

            Get-ChildItem -LiteralPath $productsPath -ErrorAction SilentlyContinue | ForEach-Object {
                $productKey = $_
                $propsPath = Join-Path $productKey.PSPath "InstallProperties"
                if (-not (Test-Path -LiteralPath $propsPath)) {
                    return
                }

                $props = Get-ItemProperty -LiteralPath $propsPath -ErrorAction SilentlyContinue
                if ($props.DisplayName -notlike "Python 3.11.9*") {
                    return
                }

                $safe = ("userdata_{0}_{1}" -f $sid, $productKey.PSChildName) -replace "[^A-Za-z0-9_\-]", "_"
                & reg.exe export $productKey.Name (Join-Path $backup "$safe.reg") /y | Out-Null
                Remove-Item -LiteralPath $productKey.PSPath -Recurse -Force
                $removed.Add("Installer UserData: $($props.DisplayName) [$sid/$($productKey.PSChildName)]")
            }
        }
    }

    $ufhPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\UFH\ARP"
    if (Test-Path -LiteralPath $ufhPath) {
        & reg.exe export "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\UFH\ARP" (Join-Path $backup "UFH_ARP.reg") /y | Out-Null
        $props = Get-ItemProperty -LiteralPath $ufhPath
        foreach ($prop in $props.PSObject.Properties) {
            if ($prop.Name -like "PS*") {
                continue
            }

            $text = ($prop.Value -join " ")
            foreach ($target in $targets) {
                if ($text -like "*$($target.Code)*") {
                    Remove-ItemProperty -LiteralPath $ufhPath -Name $prop.Name -ErrorAction SilentlyContinue
                    $removed.Add("UFH ARP value: $($prop.Name)")
                    break
                }
            }
        }
    }

    Write-Host ""
    Write-Host "Removed items: $($removed.Count)"
    foreach ($item in $removed) {
        Write-Host "  $item"
    }

    if ($skipped.Count -gt 0) {
        Write-Host ""
        Write-Host "Skipped items:"
        foreach ($item in $skipped) {
            Write-Host "  $item"
        }
    }

    $remainingUninstall = @()
    Get-ChildItem -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall" -ErrorAction SilentlyContinue | ForEach-Object {
        try {
            $props = Get-ItemProperty -LiteralPath $_.PSPath
            if ($props.DisplayName -like "Python 3.11.9*") {
                $remainingUninstall += $props.DisplayName
            }
        } catch {
        }
    }

    $remainingUserData = @()
    if (Test-Path -LiteralPath $userDataRoot) {
        Get-ChildItem -LiteralPath $userDataRoot -ErrorAction SilentlyContinue | ForEach-Object {
            $productsPath = Join-Path $_.PSPath "Products"
            if (-not (Test-Path -LiteralPath $productsPath)) {
                return
            }

            Get-ChildItem -LiteralPath $productsPath -ErrorAction SilentlyContinue | ForEach-Object {
                $propsPath = Join-Path $_.PSPath "InstallProperties"
                if (-not (Test-Path -LiteralPath $propsPath)) {
                    return
                }

                $props = Get-ItemProperty -LiteralPath $propsPath -ErrorAction SilentlyContinue
                if ($props.DisplayName -like "Python 3.11.9*") {
                    $remainingUserData += $props.DisplayName
                }
            }
        }
    }

    Write-Host ""
    if ($remainingUninstall.Count -eq 0 -and $remainingUserData.Count -eq 0) {
        Write-Host "Cleanup finished. No Python 3.11.9 stale registry entries were found."
        exit 0
    }

    Write-Host "Cleanup finished, but some entries remain:"
    foreach ($item in $remainingUninstall) {
        Write-Host "  Uninstall: $item"
    }
    foreach ($item in $remainingUserData) {
        Write-Host "  Installer UserData: $item"
    }
    exit 2
} catch {
    Write-Host ""
    Write-Host "Cleanup failed:"
    Write-Host $_.Exception.Message
    exit 1
} finally {
    Stop-Transcript | Out-Null
    Write-Host ""
    Write-Host "Log: $logPath"
    Write-Host "Press Enter to close."
    Read-Host | Out-Null
}
