$ErrorActionPreference='Stop'
$folder=(Get-Location).Path
$utf8=[Text.UTF8Encoding]::new($false,$true)
$inputPath=Join-Path $folder 'input.txt'
$mapPath=Join-Path $folder 'replacements.json'
$outputPath=Join-Path $folder 'sanitized.txt'
if(Test-Path -LiteralPath $outputPath){throw 'Output exists; choose a new folder.'}
$text=[IO.File]::ReadAllText($inputPath,$utf8)
$rawMap=[IO.File]::ReadAllText($mapPath,$utf8)
if(-not $rawMap.TrimStart().StartsWith('[')){throw 'The replacement list must be a JSON array.'}
$parsed=ConvertFrom-Json -InputObject $rawMap
$items=@($parsed)
if($null -eq $parsed){throw 'The replacement list is empty.'}
if($text.Length -lt 1 -or $text.Length -gt 100000){throw 'Input size is outside this example limit.'}
if($items.Count -lt 1 -or $items.Count -gt 50){throw 'Use 1 to 50 explicit replacements.'}
$lookup=[Collections.Generic.Dictionary[string,string]]::new([StringComparer]::Ordinal)
$counts=[Collections.Generic.Dictionary[string,int]]::new([StringComparer]::Ordinal)
foreach($item in $items){
    $names=@($item.PSObject.Properties.Name)
    if($names.Count -ne 2 -or $names -cnotcontains 'from' -or $names -cnotcontains 'token'){throw 'Each replacement needs from and token only.'}
    if($item.from -isnot [string] -or $item.from.Length -lt 3 -or $item.from.Length -gt 2000){throw 'Invalid source string.'}
    if($item.token -isnot [string] -or $item.token -cnotmatch '^\[[A-Z][A-Z0-9_]{1,40}\]$'){throw 'Use an explicit marker such as [CLIENT_01].'}
    if($lookup.ContainsKey($item.from)){throw 'Duplicate source string.'}
    if($text.Contains($item.token)){throw 'An output marker already exists in input.'}
    $lookup.Add($item.from,$item.token)
    $counts.Add($item.from,0)
}
$parts=@($lookup.Keys|Sort-Object { $_.Length } -Descending|ForEach-Object { [regex]::Escape($_) })
$regex=[regex]::new(($parts -join '|'),[Text.RegularExpressions.RegexOptions]::CultureInvariant,[TimeSpan]::FromSeconds(2))
$replace=[Text.RegularExpressions.MatchEvaluator]{
    param($match)
    $counts[$match.Value]=$counts[$match.Value]+1
    return $lookup[$match.Value]
}
$result=$regex.Replace($text,$replace)
foreach($key in $lookup.Keys){
    if($counts[$key] -lt 1){throw 'A listed string was not found exactly; review input and map.'}
    if($result.Contains($key)){throw 'A listed string is still present; no output written.'}
}
[IO.File]::WriteAllText($outputPath,$result,[Text.UTF8Encoding]::new($false))
Write-Output 'Created sanitized.txt. Only listed exact strings were replaced; review the whole text.'
