import os
import shutil
import re

# 1. Create blogs-detail.html from blogs-detail-1.html
if os.path.exists('blogs-detail-1.html'):
    with open('blogs-detail-1.html', 'r', encoding='utf-8') as f:
        c = f.read()
    
    # Ensure title and canonical point cleanly
    c = re.sub(r'<title>.*?</title>', '<title>Blog Details | Franciscan Friars Ranchi</title>', c)
    c = re.sub(r'<link rel="canonical" href=".*?">', '<link rel="canonical" href="https://franciscansociety.org/blogs-detail.html">', c)
    
    # Write blogs-detail.html
    with open('blogs-detail.html', 'w', encoding='utf-8') as f:
        f.write(c)
    print("Created blogs-detail.html successfully!")

# 2. Update prev/next and related cards in all blogs-detail-*.html and blogs-detail.html
blog_files = [f for f in os.listdir('.') if f.startswith('blogs-detail') and f.endswith('.html')]

for b_file in blog_files:
    with open(b_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # Make prev/next links smart
    content = content.replace(
        'prevBtn.href = `blogs-detail.html?id=${prevArticle.id}`;',
        'prevBtn.href = `blogs-detail-${prevArticle.id}.html`;'
    )
    content = content.replace(
        'nextBtn.href = `blogs-detail.html?id=${nextArticle.id}`;',
        'nextBtn.href = `blogs-detail-${nextArticle.id}.html`;'
    )
    content = content.replace(
        'card.href = `blogs-detail.html?id=${article.id}`;',
        'card.href = `blogs-detail-${article.id}.html`;'
    )

    with open(b_file, 'w', encoding='utf-8') as f:
        f.write(content)

print(f"Updated internal blog links across {len(blog_files)} blog detail files!")
