$gallery='gallery_list.txt'; $out='gallery_replacements.txt'; '' | Out-File $out -Force
if(-Not (Test-Path $gallery)){ Write-Error "Missing $gallery"; Exit 1 }
$galleryContent = Get-Content $gallery | Where-Object { $_ -and $_ -notmatch '^\s*$' }
foreach($line in $galleryContent){ $parts = $line -split '\|'; $id=$parts[0]; $idx=$parts[1]; $url=$parts[2]; $search = $id -replace '-', ' ';
    # try to search commons for tour title + 'photo' to get relevant images
    $query = "$search photo"
    $api1 = "https://commons.wikimedia.org/w/api.php?action=query&format=json&list=search&srsearch=$( [uri]::EscapeDataString($query) )&srnamespace=6&srwhat=text&srlimit=3"
    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
            $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; $foundUrl = $null; foreach($p in $pages.PSObject.Properties){ if($p.Value.imageinfo){ $foundUrl = $p.Value.imageinfo[0].url; break } }
                if($foundUrl){ "$id|$idx|$url|$foundUrl" | Out-File $out -Append; continue } else { "$id|$idx|$url|images/placeholder.svg" | Out-File $out -Append; continue }
            } catch { "$id|$idx|$url|images/placeholder.svg" | Out-File $out -Append; continue }
        } else { "$id|$idx|$url|images/placeholder.svg" | Out-File $out -Append; continue }
    } catch { "$id|$idx|$url|images/placeholder.svg" | Out-File $out -Append; continue }
}
Write-Output "Wrote $out"