$msBuildToolsVersion = "17"
$msBuildToolsInstallerUrl = "https://aka.ms/vs/${msBuildToolsVersion}/release/vs_BuildTools.exe"
$msBuildToolsInstallerPath = "$env:TEMP\vs_BuildTools${msBuildToolsVersion}.exe"

function Uninstall-Espeakng {
    Write-Output "Uninstalling eSpeak NG..."
    $app = (Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -like "*eSpeak NG*"})
    Start-Process -FilePath "msiexec.exe" -ArgumentList "/x ${app.IdentifyingNumber} /passive /norestart"
}

function Uninstall-MsBuildTools {
    Write-Output "Uninstalling Visual Studio Build Tools..."
    Invoke-WebRequest -Uri $msBuildToolsInstallerUrl -OutFile $msBuildToolsInstallerPath
    Start-Process -FilePath $msBuildToolsInstallerPath -ArgumentList `
    "--remove Microsoft.VisualStudio.Workload.VCTools --passive --wait" -Wait
    Remove-Item $msBuildToolsInstallerPath -Force
}

function Uninstall-CUDA { 
    Write-Output "Uninstalling CUDA Toolkit..."
    $uninstall = (gci "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" `
    | foreach { gp $_.PSPath } | ? { $_ -like "*CUDA Toolkit*" } | select UninstallString)
	$uninstall = ($uninstall.UninstallString -Replace '^"[^"]+"\s+', '')
    Start-Process -FilePath "rundll32.exe" -ArgumentList "$uninstall -silent -deviceinitiated"
}

function Remove-Local-Files {
    Write-Output "Removing local files..."
    $ExcludeFiles = @(".gitattributes", ".gitignore", "README.md", "GenerateDialogue.py", `
    "Install.ps1", "Uninstall.ps1", "voices")
    $FilesToDelete = Get-ChildItem -Path . -File | Where-Object { $_.Name -notin $ExcludeFiles }
    foreach ($File in $FilesToDelete) {
        Remove-Item -Path $File.FullName -Force
    }
}



Write-Output "Starting voice environment uninstall process."
Uninstall-Espeakng
Uninstall-MsBuildTools
Uninstall-CUDA
Remove-Local-Files
Write-Output "Uninstall finished. Please restart your machine to clear temp files."
