$ErrorActionPreference='Stop'
$projectRoot=Split-Path -Parent $PSScriptRoot
$token=[Guid]::NewGuid().ToString('N')
$imageBase='QA_SWAP_'+$token.ToUpperInvariant()
$pageName='image-swap-'+$token+'.html'
$pagePath=Join-Path $projectRoot ('dist\'+$pageName)
$imagePath=Join-Path $projectRoot ('dist\images\'+$imageBase+'.png')
if((Test-Path -LiteralPath $pagePath)-or(Test-Path -LiteralPath $imagePath)){throw 'Test path already exists'}
$html='
MANGABOMTESTОБЛОЖКА
![Тестовая обложка]()
'
try{
[IO.File]::WriteAllText($pagePath,$html,[Text.UTF8Encoding]::new($false))
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $PSScriptRoot 'check-layout.ps1') -Name image-swap-missing -Width 390 -Height 844 -Page $pageName
if($LASTEXITCODE-ne 0){throw 'Missing image layout failed'}
$metrics=Get-Content -LiteralPath (Join-Path $projectRoot '.qa\image-swap-missing.json') -Raw -Encoding UTF8|ConvertFrom-Json
if($metrics.imageFallbacks-ne 1-or$metrics.managedImages.Count-ne 0){throw 'Missing image did not show a text cover'}
[IO.File]::Copy((Join-Path $projectRoot 'dist\manga\LORD_OF_CHEAP_LUNCH\chapter-001\01.png'),$imagePath,$false)
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $PSScriptRoot 'check-layout.ps1') -Name image-swap-added -Width 390 -Height 844 -Page $pageName
if($LASTEXITCODE-ne 0){throw 'Added image layout failed'}
$metrics=Get-Content -LiteralPath (Join-Path $projectRoot '.qa\image-swap-added.json') -Raw -Encoding UTF8|ConvertFrom-Json
if($metrics.managedImages.Count-ne 1-or-not $metrics.managedImages[0].loaded-or$metrics.imageFallbacks-ne 0){throw 'New PNG image was not found automatically'}
[IO.File]::Delete($imagePath)
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $PSScriptRoot 'check-layout.ps1') -Name image-swap-removed -Width 390 -Height 844 -Page $pageName
if($LASTEXITCODE-ne 0){throw 'Removed image layout failed'}
$metrics=Get-Content -LiteralPath (Join-Path $projectRoot '.qa\image-swap-removed.json') -Raw -Encoding UTF8|ConvertFrom-Json
if($metrics.imageFallbacks-ne 1-or$metrics.managedImages.Count-ne 0){throw 'Deleting an image did not restore text cover'}
Write-Host 'PASS: adding a PNG and deleting it updates the cover automatically without HTML edits or indexing.'
}finally{[IO.File]::Delete($pagePath);[IO.File]::Delete($imagePath)}