$articles = Get-ChildItem -Path "site\blog\articles\*.html"

foreach ($article in $articles) {
    $content = Get-Content $article.FullName -Raw
    
    # 1. Extract the Title from <meta property="og:title" content="...">
    $titleMatch = [regex]::Match($content, '<meta property="og:title" content="([^"]+)">')
    if (-not $titleMatch.Success) { continue }
    $title = $titleMatch.Groups[1].Value
    $urlTitle = [uri]::EscapeDataString($title)
    
    $imgUrlPath = "../../assets/blog-images/generate-image.php?title=$urlTitle"
    $imgUrlFull = "https://www.crawlie.app/assets/blog-images/generate-image.php?title=$urlTitle"
    
    # 2. Update og:image and twitter:image
    $content = $content -replace '<meta property="og:image" content="[^"]+">', "<meta property=`"og:image`" content=`"$imgUrlFull`">"
    $content = $content -replace '<meta name="twitter:image" content="[^"]+">', "<meta name=`"twitter:image`" content=`"$imgUrlFull`">"
    
    # 3. Update JSON-LD BlogPosting image
    # We use a regex to replace "image": "..."
    $content = [regex]::Replace($content, '"image":\s*"[^"]+"', "`"image`": `"$imgUrlFull`"")
    
    # 4. Remove all existing <img> tags
    $content = $content -replace '(?i)<img[^>]+>', ''
    
    # 5. Inject the new dynamic image tag immediately after the </h1> tag
    $newImgTag = "<img src=`"$imgUrlPath`" alt=`"$title`" title=`"$title`" width=`"1200`" height=`"630`" loading=`"lazy`" style=`"width:100%;height:auto;border-radius:16px;margin:28px 0;display:block;box-shadow:0 12px 32px rgba(0,0,0,0.08);`">"
    $content = [regex]::Replace($content, '(?i)(</h1>)', "`$1`n  $newImgTag")
    
    Set-Content -Path $article.FullName -Value $content -Encoding UTF8
}
Write-Host "Blog images and SEO completely updated."
