param(
  [Parameter(Mandatory = $true)]
  [ValidateSet("add", "remove")]
  [string]$Action,

  [Parameter(Mandatory = $true)]
  [string]$Target,

  [Parameter(Mandatory = $true)]
  [ValidateSet("User", "Machine")]
  [string]$Scope
)

function Normalize-PathEntry {
  param([string]$Value)

  if ([string]::IsNullOrWhiteSpace($Value)) {
    return $null
  }

  return $Value.Trim().TrimEnd('\\')
}

$currentPath = [Environment]::GetEnvironmentVariable("Path", $Scope)
$entries = @()

if (-not [string]::IsNullOrWhiteSpace($currentPath)) {
  $entries = @(
    $currentPath -split ";" |
      Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
  )
}

$normalizedTarget = Normalize-PathEntry $Target
$filteredEntries = @(
  foreach ($entry in $entries) {
    $normalizedEntry = Normalize-PathEntry $entry
    if (
      $null -ne $normalizedEntry -and
      -not $normalizedEntry.Equals($normalizedTarget, [System.StringComparison]::OrdinalIgnoreCase)
    ) {
      $entry.Trim()
    }
  }
)

if ($Action -eq "add") {
  $filteredEntries += $Target
}

$dedupedEntries = [System.Collections.Generic.List[string]]::new()
$seenEntries = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)

foreach ($entry in $filteredEntries) {
  $normalizedEntry = Normalize-PathEntry $entry
  if ($null -ne $normalizedEntry -and $seenEntries.Add($normalizedEntry)) {
    [void]$dedupedEntries.Add($entry.Trim())
  }
}

[Environment]::SetEnvironmentVariable("Path", ($dedupedEntries -join ";"), $Scope)