$tours='tours_list.txt'; $out='wikimedia_replacements.txt'; '' | Out-File $out -Force
if(-Not (Test-Path $tours)){ Write-Error "Missing $tours"; Exit 1 }
$toursContent = Get-Content $tours | Where-Object { $_ -and $_ -notmatch '^\s*$' }
foreach($line in $toursContent){ $parts = $line -split '\|'; $id=$parts[0]; $title=$parts[1]; $hero=$parts[2]; $search = $id -replace '-', ' ';
    # special case: restore apostrophes for hells-gate
    if($search -eq 'hells gate'){ $search = "Hell's Gate" }
    Write-Output "Searching commons for: $search";
    $api1 = "https://commons.wikimedia.org/w/api.php?action=query&format=json&list=search&srsearch=$( [uri]::EscapeDataString($search) )&srnamespace=6&srwhat=text&srlimit=1"
    try{
        $resp = Invoke-RestMethod -Uri $api1 -Method Get -TimeoutSec 15 -ErrorAction Stop
        if($resp.query.search.Count -gt 0){ $fileTitle = $resp.query.search[0].title; Write-Output "Found file title: $fileTitle";
            $api2 = "https://commons.wikimedia.org/w/api.php?action=query&format=json&titles=$( [uri]::EscapeDataString($fileTitle) )&prop=imageinfo&iiprop=url&srlimit=1"
            try{ $resp2 = Invoke-RestMethod -Uri $api2 -Method Get -TimeoutSec 15 -ErrorAction Stop; $pages = $resp2.query.pages; foreach($p in $pages.PSObject.Properties){ if($p.Value.imageinfo){ $imgUrl = $p.Value.imageinfo[0].url; "$hero|$imgUrl|$id|$title" | Out-File $out -Append; break } } }
            catch { Write-Output "  imageinfo fetch failed for $fileTitle"; "$hero|images/placeholder.svg|$id|$title" | Out-File $out -Append }
        } else { Write-Output "No search results for $search"; "$hero|images/placeholder.svg|$id|$title" | Out-File $out -Append }
    } catch { Write-Output "Search API failed for $search"; "$hero|images/placeholder.svg|$id|$title" | Out-File $out -Append }
}
Write-Output "Wrote $out"