[CmdletBinding(SupportsShouldProcess)]
param(
    [string]$InstallDirectory = (Join-Path $env:LOCALAPPDATA 'Programs\Free2 CSV')
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Assert-SafeInstallDirectory {
    param([Parameter(Mandatory)][string]$Path)

    $programsRoot = [IO.Path]::GetFullPath((Join-Path $env:LOCALAPPDATA 'Programs'))
    $resolved = [IO.Path]::GetFullPath($Path)
    $prefix = $programsRoot.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar
    if (-not $resolved.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
        throw "InstallDirectory must be inside $programsRoot."
    }

    return $resolved.TrimEnd([IO.Path]::DirectorySeparatorChar)
}

$installRoot = Assert-SafeInstallDirectory -Path $InstallDirectory
$classesRoot = 'HKCU:\Software\Classes'
$openWithProgIds = Join-Path $classesRoot '.csv\OpenWithProgids'
$shortcutPath = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Free2 CSV.lnk'
$ownershipMarker = Join-Path $installRoot '.free2csv-install.json'

if (-not (Test-Path -LiteralPath $ownershipMarker -PathType Leaf)) {
    throw "Refusing to remove $installRoot because its Free2 CSV ownership marker is missing."
}

$marker = Get-Content -LiteralPath $ownershipMarker -Raw | ConvertFrom-Json
if ($marker.productId -ne 'Free2Csv' -or
    [IO.Path]::GetFullPath([string]$marker.installDirectory) -ne $installRoot) {
    throw "Refusing to remove $installRoot because its ownership marker is invalid."
}

if ($PSCmdlet.ShouldProcess('Free2 CSV per-user registration', 'Remove')) {
    if (Test-Path -LiteralPath $openWithProgIds) {
        Remove-ItemProperty -LiteralPath $openWithProgIds -Name 'Free2Csv.csv' -ErrorAction SilentlyContinue
    }

    Remove-Item -LiteralPath (Join-Path $classesRoot 'Free2Csv.csv') -Recurse -Force -ErrorAction SilentlyContinue
    Remove-Item -LiteralPath (Join-Path $classesRoot 'Applications\Free2Csv.exe') -Recurse -Force -ErrorAction SilentlyContinue
    Remove-ItemProperty -LiteralPath 'HKCU:\Software\RegisteredApplications' -Name 'Free2 CSV' -ErrorAction SilentlyContinue
    Remove-Item -LiteralPath 'HKCU:\Software\Free2Csv' -Recurse -Force -ErrorAction SilentlyContinue
    Remove-Item -LiteralPath 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Free2Csv' -Recurse -Force -ErrorAction SilentlyContinue
    Remove-Item -LiteralPath $shortcutPath -Force -ErrorAction SilentlyContinue
}

if ((Test-Path -LiteralPath $installRoot -PathType Container) -and
    $PSCmdlet.ShouldProcess($installRoot, 'Remove installed files')) {
    Remove-Item -LiteralPath $installRoot -Recurse -Force
}

Write-Host 'Free2 CSV was uninstalled for the current Windows user.'
