$failFile='scan_failing_urls.txt'; $out='replacement_map.txt'; '' | Out-File $out -Force
if(-Not (Test-Path $failFile)){ Write-Output "No failing list found ($failFile)."; Exit 1 }
$failUrls = Get-Content $failFile | Where-Object { $_ -and $_ -ne "```plaintext" -and $_ -ne '```' } | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }
foreach($u in $failUrls){
    try{
        $uri = [uri]$u
        $segments = $uri.Segments
        # find filename (last segment)
        $filename = $segments[-1]
        # construct thumb URL: insert 'thumb' after '/wikipedia/commons'
        $thumbBase = $uri.OriginalString -replace '/wikipedia/commons/','/wikipedia/commons/thumb/'
        $thumbUrl = "$thumbBase/$filename/1200px-$filename"
        # test thumb
        try{ $h=Invoke-WebRequest -Uri $thumbUrl -Method Head -TimeoutSec 10 -ErrorAction Stop; if($h.StatusCode -eq 200){ "$u|$thumbUrl" | Out-File $out -Append; continue } } catch {}
        # if thumb fails, try original GET as fallback test
        try{ $h2=Invoke-WebRequest -Uri $u -Method Head -TimeoutSec 10 -ErrorAction Stop; if($h2.StatusCode -eq 200){ "$u|$u" | Out-File $out -Append; continue } } catch {}
        # final fallback -> placeholder path
        "$u|images/placeholder.svg" | Out-File $out -Append
    } catch { "$u|images/placeholder.svg" | Out-File $out -Append }
}
Write-Output "Wrote replacements to $out"
