#!/usr/bin/env python3
"""
Script to unify headers across all HTML pages.
English pages get the same English header, Arabic pages get the same Arabic header.
"""

import os
import re
from pathlib import Path

# Unified English header template
ENGLISH_HEADER = '''<!-- Mobile Sidebar Overlay -->
<div class="mobile-sidebar-overlay"></div>
<!-- Mobile Sidebar -->
<div class="mobile-sidebar">
<div class="mobile-sidebar-header">
<a href="home.html">
<img alt="El Seif Logo" src="assets/LOGO.png"/>
</a>
<button class="mobile-sidebar-close">
<svg fill="none" height="24" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<line x1="18" x2="6" y1="6" y2="18"></line>
<line x1="6" x2="18" y1="6" y2="18"></line>
</svg>
</button>
</div>
<nav class="mobile-sidebar-nav">
<ul>
<li><a {active_home} href="home.html">Home</a></li>
<li><a {active_about} href="about.html">Who We Are</a></li>
<li class="has-submenu">
<a href="ourService.html">Services</a>
<ul class="submenu">
<li><a href="ourServicedetail.html">Design and Build</a></li>
<li><a href="ourServicedetail.html">Infrastructure Projects</a></li>
<li><a href="ourServicedetail.html">Steel Building Projects</a></li>
<li><a href="ourServicedetail.html">Civil Works</a></li>
<li><a href="ourServicedetail.html">Electrical Projects</a></li>
<li><a href="ourServicedetail.html">Mechanical Projects</a></li>
<li><a href="ourServicedetail.html">Process Engineering & Execution</a></li>
<li><a href="ourServicedetail.html">Plant Machinery Engineering & Installation</a></li>
<li><a href="ourServicedetail.html">Special Metal Fabrication</a></li>
<li><a href="ourServicedetail.html">Project Management</a></li>
</ul>
</li>
<li class="has-submenu">
<a href="project.html">Projects</a>
<ul class="submenu">
<li><a href="projectDetail.html">Civil, MEP & Infrastructure Works for Welspun Ductile Iron Factory</a></li>
<li><a href="projectDetail.html">Arabian Drilling Company New Base Construction</a></li>
<li><a href="projectDetail.html">Oil Chemistry Industrial Factory Expansion</a></li>
<li><a href="projectDetail.html">ETP and ZLD Expansion Project</a></li>
<li><a href="projectDetail.html">Trojena Base Camp Facilities</a></li>
<li><a href="projectDetail.html">Sulaiman AL-Rasheed Mosque</a></li>
<li><a href="projectDetail.html">Spacemaker KSA Pods Factory</a></li>
<li><a href="projectDetail.html">Saudi Diesel Switch Gear Factory</a></li>
<li><a href="projectDetail.html">Saudi Yansab Warehouse</a></li>
<li><a href="projectDetail.html">Nesto Hyper Market</a></li>
<li><a href="projectDetail.html">Alfalak Gym Building</a></li>
<li><a href="projectDetail.html">ZEECO Factory Expansion</a></li>
<li><a href="projectDetail.html">EMDAD Drying Plant Project</a></li>
</ul>
</li>
<li><a {active_news} href="Latestnews.html">Latest News</a></li>
<li><a {active_join} href="join.html">Join Us</a></li>
<li><a {active_contact} href="contactUs.html">Contact Us</a></li>
</ul>
</nav>
<div class="mobile-sidebar-footer">
<a class="mobile-sidebar-lang" href="home-ar.html">
<svg fill="none" height="20" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24" width="20" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10"></circle>
<path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"></path>
<path d="M2 12h20"></path>
</svg>
<span>العربية</span>
</a>
</div>
</div>
<!-- Navigation Header -->
<div class="header-panel-btm">
<div class="container">
<div class="row">
<div class="hewader-panel-main">
<div class="header-logo">
<a href="home.html">
<img alt="El Seif Logo" src="assets/LOGO.png" style="max-height: 50px; width: auto;"/>
</a>
</div>
<!-- Hamburger Menu for Mobile -->
<button class="hamburger-menu">
<span></span>
<span></span>
<span></span>
</button>
<div class="header-menu">
<nav class="head_btm_menu" id="cssmenu">
<ul>
<li><a {active_home_nav} href="home.html">Home</a></li>
<li><a {active_about_nav} href="about.html">Who We Are</a></li>
<li>
<a href="ourService.html">Services</a>
<ul>
<li><a href="ourServicedetail.html">Design and Build</a></li>
<li><a href="ourServicedetail.html">Infrastructure Projects</a></li>
<li><a href="ourServicedetail.html">Steel Building Projects</a></li>
<li><a href="ourServicedetail.html">Civil Works</a></li>
<li><a href="ourServicedetail.html">Electrical Projects</a></li>
<li><a href="ourServicedetail.html">Mechanical Projects</a></li>
<li><a href="ourServicedetail.html">Process Engineering & Execution</a></li>
<li><a href="ourServicedetail.html">Plant Machinery Engineering & Installation</a></li>
<li><a href="ourServicedetail.html">Special Metal Fabrication</a></li>
<li><a href="ourServicedetail.html">Project Management</a></li>
</ul>
</li>
<li>
<a href="project.html">Projects</a>
<ul>
<li><a href="projectDetail.html">Civil, MEP & Infrastructure Works for Welspun Ductile Iron Factory</a></li>
<li><a href="projectDetail.html">Arabian Drilling Company New Base Construction</a></li>
<li><a href="projectDetail.html">Oil Chemistry Industrial Factory Expansion</a></li>
<li><a href="projectDetail.html">ETP and ZLD Expansion Project</a></li>
<li><a href="projectDetail.html">Trojena Base Camp Facilities</a></li>
<li><a href="projectDetail.html">Sulaiman AL-Rasheed Mosque</a></li>
<li><a href="projectDetail.html">Spacemaker KSA Pods Factory</a></li>
<li><a href="projectDetail.html">Saudi Diesel Switch Gear Factory</a></li>
<li><a href="projectDetail.html">Saudi Yansab Warehouse</a></li>
<li><a href="projectDetail.html">Nesto Hyper Market</a></li>
<li><a href="projectDetail.html">Alfalak Gym Building</a></li>
<li><a href="projectDetail.html">ZEECO Factory Expansion</a></li>
<li><a href="projectDetail.html">EMDAD Drying Plant Project</a></li>
</ul>
</li>
<li><a {active_news_nav} href="Latestnews.html">Latest News</a></li>
<li><a {active_join_nav} href="join.html">Join Us</a></li>
<li><a {active_contact_nav} href="contactUs.html">Contact Us</a></li>
<li class="navigation-textBlack" id="navigation-Ar">
<a href="home-ar.html">Home</a>
</li>
</ul>
</nav>
</div>
<div class="navigation-navbar--global-img">
<div>
<a href="search.html">
<svg class="lucide lucide-search" fill="none" height="24" stroke="#4A90E2" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<circle cx="11" cy="11" r="8"></circle>
<path d="m21 21-4.3-4.3"></path>
</svg>
</a>
</div>
<span class="span"></span>
<div>
<a class="lang-switcher navigation-navbar--global-img" href="home-ar.html" style="text-decoration: none;">
<svg class="lucide lucide-globe" fill="none" height="24" stroke="#4A90E2" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10"></circle>
<path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"></path>
<path d="M2 12h20"></path>
</svg>
<span class="ar">العربية</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>'''

# Unified Arabic header template
ARABIC_HEADER = '''<!-- Mobile Sidebar Overlay -->
<div class="mobile-sidebar-overlay"></div>
<!-- Mobile Sidebar -->
<div class="mobile-sidebar">
<div class="mobile-sidebar-header">
<a href="home-ar.html">
<img alt="شعار السيف" src="assets/LOGO.png"/>
</a>
<button class="mobile-sidebar-close">
<svg fill="none" height="24" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<line x1="18" x2="6" y1="6" y2="18"></line>
<line x1="6" x2="18" y1="6" y2="18"></line>
</svg>
</button>
</div>
<nav class="mobile-sidebar-nav">
<ul>
<li><a {active_home} href="home-ar.html">الرئيسية</a></li>
<li><a {active_about} href="about-ar.html">من نحن</a></li>
<li class="has-submenu">
<a href="ourService-ar.html">خدماتنا</a>
<ul class="submenu">
<li><a href="ourServicedetail-ar.html">التصميم والبناء</a></li>
<li><a href="ourServicedetail-ar.html">مشاريع البنية التحتية</a></li>
<li><a href="ourServicedetail-ar.html">مشاريع المباني الفولاذية</a></li>
<li><a href="ourServicedetail-ar.html">الأعمال المدنية</a></li>
<li><a href="ourServicedetail-ar.html">المشاريع الكهربائية</a></li>
<li><a href="ourServicedetail-ar.html">المشاريع الميكانيكية</a></li>
<li><a href="ourServicedetail-ar.html">هندسة العمليات والتنفيذ</a></li>
<li><a href="ourServicedetail-ar.html">هندسة وتثبيت آلات المصانع</a></li>
<li><a href="ourServicedetail-ar.html">تصنيع المعادن الخاصة</a></li>
<li><a href="ourServicedetail-ar.html">إدارة المشاريع</a></li>
</ul>
</li>
<li class="has-submenu">
<a href="project-ar.html">المشاريع</a>
<ul class="submenu">
<li><a href="projectDetail-ar.html">أعمال مدنية وميكانيكية وكهربائية وبنية تحتية لمصنع ويلسبون للحديد المطيل</a></li>
<li><a href="projectDetail-ar.html">بناء القاعدة الجديدة لشركة الحفر العربية</a></li>
<li><a href="projectDetail-ar.html">توسعة مصنع كيمياء النفط الصناعي</a></li>
<li><a href="projectDetail-ar.html">مشروع توسعة محطة معالجة المياه الصفراء والصفراء</a></li>
<li><a href="projectDetail-ar.html">مرافق معسكر قاعدة تروجينا</a></li>
<li><a href="projectDetail-ar.html">مسجد سليمان الرشيد</a></li>
<li><a href="projectDetail-ar.html">مصنع بودات سبيس ميكر السعودية</a></li>
<li><a href="projectDetail-ar.html">مصنع معدات التبديل السعودي للديزل</a></li>
<li><a href="projectDetail-ar.html">مستودع ينساب السعودي</a></li>
<li><a href="projectDetail-ar.html">هايبر ماركت نيستو</a></li>
<li><a href="projectDetail-ar.html">مبنى نادي الفلق الرياضي</a></li>
<li><a href="projectDetail-ar.html">توسعة مصنع زيكو</a></li>
<li><a href="projectDetail-ar.html">مشروع محطة تجفيف إمداد</a></li>
</ul>
</li>
<li><a {active_news} href="Latest news-ar.html">آخر الأخبار</a></li>
<li><a {active_join} href="join-ar.html">انضم إلينا</a></li>
<li><a {active_contact} href="contactUs-ar.html">اتصل بنا</a></li>
</ul>
</nav>
<div class="mobile-sidebar-footer">
<a class="mobile-sidebar-lang" href="home.html">
<svg fill="none" height="20" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24" width="20" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10"></circle>
<path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"></path>
<path d="M2 12h20"></path>
</svg>
<span>English</span>
</a>
</div>
</div>
<!-- Navigation Header -->
<div class="header-panel-btm">
<div class="container">
<div class="row">
<div class="hewader-panel-main">
<div class="header-logo">
<a href="home-ar.html">
<img alt="شعار السيف" src="assets/LOGO.png" style="max-height: 50px; width: auto;"/>
</a>
</div>
<!-- Hamburger Menu for Mobile -->
<button class="hamburger-menu">
<span></span>
<span></span>
<span></span>
</button>
<div class="header-menu">
<nav class="head_btm_menu" id="cssmenu">
<ul>
<li><a {active_home_nav} href="home-ar.html">الرئيسية</a></li>
<li><a {active_about_nav} href="about-ar.html">عن السيف</a></li>
<li>
<a href="ourService-ar.html">خدماتنا</a>
<ul>
<li><a href="ourServicedetail-ar.html">التصميم والبناء</a></li>
<li><a href="ourServicedetail-ar.html">مشاريع البنية التحتية</a></li>
<li><a href="ourServicedetail-ar.html">مشاريع المباني الفولاذية</a></li>
<li><a href="ourServicedetail-ar.html">الأعمال المدنية</a></li>
<li><a href="ourServicedetail-ar.html">المشاريع الكهربائية</a></li>
<li><a href="ourServicedetail-ar.html">المشاريع الميكانيكية</a></li>
<li><a href="ourServicedetail-ar.html">هندسة العمليات والتنفيذ</a></li>
<li><a href="ourServicedetail-ar.html">هندسة وتثبيت آلات المصانع</a></li>
<li><a href="ourServicedetail-ar.html">تصنيع المعادن الخاصة</a></li>
<li><a href="ourServicedetail-ar.html">إدارة المشاريع</a></li>
</ul>
</li>
<li>
<a href="project-ar.html">المشاريع</a>
<ul>
<li><a href="projectDetail-ar.html">أعمال مدنية وميكانيكية وكهربائية وبنية تحتية لمصنع ويلسبون للحديد المطيل</a></li>
<li><a href="projectDetail-ar.html">بناء القاعدة الجديدة لشركة الحفر العربية</a></li>
<li><a href="projectDetail-ar.html">توسعة مصنع كيمياء النفط الصناعي</a></li>
<li><a href="projectDetail-ar.html">مشروع توسعة محطة معالجة المياه الصفراء والصفراء</a></li>
<li><a href="projectDetail-ar.html">مرافق معسكر قاعدة تروجينا</a></li>
<li><a href="projectDetail-ar.html">مسجد سليمان الرشيد</a></li>
<li><a href="projectDetail-ar.html">مصنع بودات سبيس ميكر السعودية</a></li>
<li><a href="projectDetail-ar.html">مصنع معدات التبديل السعودي للديزل</a></li>
<li><a href="projectDetail-ar.html">مستودع ينساب السعودي</a></li>
<li><a href="projectDetail-ar.html">هايبر ماركت نيستو</a></li>
<li><a href="projectDetail-ar.html">مبنى نادي الفلق الرياضي</a></li>
<li><a href="projectDetail-ar.html">توسعة مصنع زيكو</a></li>
<li><a href="projectDetail-ar.html">مشروع محطة تجفيف إمداد</a></li>
</ul>
</li>
<li><a {active_news_nav} href="Latest news-ar.html">آخر الأخبار</a></li>
<li><a {active_join_nav} href="join-ar.html">انضم إلينا</a></li>
<li><a {active_contact_nav} href="contactUs-ar.html">اتصل بنا</a></li>
<li class="navigation-textBlack" id="navigation-Ar">
<a href="home.html">الرئيسية</a>
</li>
</ul>
</nav>
</div>
<div class="navigation-navbar--global-img">
<div>
<a href="search-ar.html">
<svg class="lucide lucide-search" fill="none" height="24" stroke="#4A90E2" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<circle cx="11" cy="11" r="8"></circle>
<path d="m21 21-4.3-4.3"></path>
</svg>
</a>
</div>
<span class="span"></span>
<div>
<a class="lang-switcher navigation-navbar--global-img" href="home.html" style="text-decoration: none;">
<svg class="lucide lucide-globe" fill="none" height="24" stroke="#4A90E2" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewbox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="10"></circle>
<path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"></path>
<path d="M2 12h20"></path>
</svg>
<span class="en">English</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>'''


def get_active_class(page_name, menu_item):
    """Determine if a menu item should have the active class based on the current page."""
    page_lower = page_name.lower()
    
    # Map pages to menu items
    if menu_item == 'home':
        return 'class="active"' if any(x in page_lower for x in ['home', 'index']) else ''
    elif menu_item == 'about':
        return 'class="active"' if 'about' in page_lower else ''
    elif menu_item == 'services':
        return 'class="active"' if 'service' in page_lower else ''
    elif menu_item == 'projects':
        return 'class="active"' if 'project' in page_lower else ''
    elif menu_item == 'news':
        return 'class="active"' if any(x in page_lower for x in ['news', 'latest']) else ''
    elif menu_item == 'join':
        return 'class="active"' if 'join' in page_lower else ''
    elif menu_item == 'contact':
        return 'class="active"' if 'contact' in page_lower else ''
    return ''


def replace_header_in_file(file_path, is_arabic=False):
    """Replace the header in a single HTML file."""
    # Try different encodings
    encodings = ['utf-8', 'latin-1', 'cp1252', 'iso-8859-1']
    content = None
    
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                content = f.read()
            break
        except UnicodeDecodeError:
            continue
        except Exception as e:
            print(f"Error reading {file_path} with {encoding}: {e}")
            continue
    
    if content is None:
        print(f"Could not read {file_path} with any encoding")
        return False
    
    page_name = os.path.basename(file_path)
    
    # Determine active classes
    active_home = get_active_class(page_name, 'home')
    active_about = get_active_class(page_name, 'about')
    active_projects = get_active_class(page_name, 'projects')
    active_news = get_active_class(page_name, 'news')
    active_join = get_active_class(page_name, 'join')
    active_contact = get_active_class(page_name, 'contact')
    
    active_home_nav = active_home
    active_about_nav = active_about
    active_projects_nav = active_projects
    active_news_nav = active_news
    active_join_nav = active_join
    active_contact_nav = active_contact
    
    # Format the header template
    if is_arabic:
        header = ARABIC_HEADER.format(
            active_home=active_home,
            active_about=active_about,
            active_projects=active_projects,
            active_news=active_news,
            active_join=active_join,
            active_contact=active_contact,
            active_home_nav=active_home_nav,
            active_about_nav=active_about_nav,
            active_projects_nav=active_projects_nav,
            active_news_nav=active_news_nav,
            active_join_nav=active_join_nav,
            active_contact_nav=active_contact_nav
        )
    else:
        header = ENGLISH_HEADER.format(
            active_home=active_home,
            active_about=active_about,
            active_projects=active_projects,
            active_news=active_news,
            active_join=active_join,
            active_contact=active_contact,
            active_home_nav=active_home_nav,
            active_about_nav=active_about_nav,
            active_projects_nav=active_projects_nav,
            active_news_nav=active_news_nav,
            active_join_nav=active_join_nav,
            active_contact_nav=active_contact_nav
        )
    
    # Find the body tag and extract body class
    body_match = re.search(r'<body([^>]*)>', content)
    if not body_match:
        print(f"Could not find <body> tag in {file_path}")
        return False
    
    body_attrs = body_match.group(1)
    
    # Find where the header starts (after body tag)
    body_end_pos = body_match.end()
    
    # Find the mobile sidebar overlay start - try multiple patterns
    mobile_start = content.find('<!-- Mobile Sidebar Overlay -->', body_end_pos)
    if mobile_start == -1:
        mobile_start = content.find('<div class="mobile-sidebar-overlay">', body_end_pos)
    if mobile_start == -1:
        # Some files don't have the overlay div, start directly with mobile-sidebar
        mobile_start = content.find('<div class="mobile-sidebar">', body_end_pos)
    if mobile_start == -1:
        # Some files have just the mobile-sidebar-header
        mobile_start = content.find('<div class="mobile-sidebar-header">', body_end_pos)
    if mobile_start == -1:
        # Last resort: look for Navigation Header comment
        nav_start = content.find('<!-- Navigation Header -->', body_end_pos)
        if nav_start != -1:
            # Go back to find mobile sidebar start
            before_nav = content[body_end_pos:nav_start]
            mobile_start_match = re.search(r'<div class="mobile-sidebar', before_nav)
            if mobile_start_match:
                mobile_start = body_end_pos + mobile_start_match.start()
    
    if mobile_start == -1:
        # File might not have a header at all - look for nav or main tag to insert before
        nav_match = re.search(r'<nav[^>]*>', content[body_end_pos:], re.IGNORECASE)
        main_match = re.search(r'<main[^>]*>', content[body_end_pos:], re.IGNORECASE)
        
        if nav_match:
            mobile_start = body_end_pos + nav_match.start()
            # Insert header before nav
            header = '\n' + header + '\n'
            new_content = content[:mobile_start] + header + content[mobile_start:]
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(new_content)
                print(f"✓ Inserted header in {file_path}")
                return True
            except Exception as e:
                print(f"Error writing {file_path}: {e}")
                return False
        elif main_match:
            mobile_start = body_end_pos + main_match.start()
            # Insert header before main
            header = '\n' + header + '\n'
            new_content = content[:mobile_start] + header + content[mobile_start:]
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(new_content)
                print(f"✓ Inserted header in {file_path}")
                return True
            except Exception as e:
                print(f"Error writing {file_path}: {e}")
                return False
        else:
            print(f"Could not find header start or insertion point in {file_path}")
            return False
    
    # Find where header ends using regex - match from Mobile Sidebar to end of header-panel-btm
    search_content = content[mobile_start:]
    
    # Pattern 1: With Navigation Header comment (5 closing divs, optional extra div/header)
    header_pattern1 = r'(.*?<!-- Navigation Header -->.*?</div>\s*</div>\s*</div>\s*</div>\s*</div>\s*</div>)(?:\s*</div>)?(?:\s*</header>)?(?=\s*<main|\s*<div id="pagepiling"|\s*<div id="dynamicNewsSection|\s*<section|\s*<nav[^>]*></nav>)'
    
    # Pattern 2: With Navigation comment (different wording)
    header_pattern1b = r'(.*?<!-- Navigation -->.*?</div>\s*</div>\s*</div>\s*</div>\s*</div>\s*</div>)(?:\s*</div>)?(?:\s*</header>)?(?=\s*<main|\s*<div id="pagepiling"|\s*<div id="dynamicNewsSection|\s*<section|\s*<nav[^>]*></nav>)'
    
    # Pattern 3: Without Navigation Header comment, but with header-panel-btm (5 closing divs)
    header_pattern2 = r'(.*?<div class="header-panel-btm">.*?</div>\s*</div>\s*</div>\s*</div>\s*</div>\s*</div>)(?:\s*</div>)?(?:\s*</header>)?(?=\s*<main|\s*<div id="pagepiling"|\s*<div id="dynamicNewsSection|\s*<section|\s*<nav[^>]*></nav>)'
    
    # Pattern 4: Just mobile sidebar and navigation menu (variable closing divs, handle extra divs/whitespace)
    header_pattern3 = r'(.*?</div>\s*</div>\s*</div>\s*</div>\s*</div>\s*</div>)(?:\s*\n\s*</div>)?(?:\s*</header>)?(?=\s*<main|\s*<div id="pagepiling"|\s*<div id="dynamicNewsSection|\s*<section|\s*<nav[^>]*></nav>)'
    
    match = re.search(header_pattern1, search_content, re.DOTALL | re.MULTILINE | re.IGNORECASE)
    if not match:
        match = re.search(header_pattern1b, search_content, re.DOTALL | re.MULTILINE | re.IGNORECASE)
    if not match:
        match = re.search(header_pattern2, search_content, re.DOTALL | re.MULTILINE | re.IGNORECASE)
    if not match:
        match = re.search(header_pattern3, search_content, re.DOTALL | re.MULTILINE | re.IGNORECASE)
    
    if match:
        header_end = mobile_start + match.end()
        # Check if there's a </header> tag right after (skip whitespace)
        remaining = content[header_end:header_end+30].strip()
        if remaining.startswith('</header>'):
            header_end = content.find('</header>', header_end) + 9
    else:
        print(f"Failed to find header boundaries in {file_path}")
        return False
    
    # Extract the old header
    old_header = content[mobile_start:header_end].strip()
    
    # Replace old header with new header
    new_content = content[:mobile_start] + '\n' + header + '\n' + content[header_end:]
    
    # Write back
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
        print(f"✓ Updated {file_path}")
        return True
    except Exception as e:
        print(f"Error writing {file_path}: {e}")
        return False


def main():
    """Main function to process all HTML files."""
    base_dir = Path(__file__).parent
    
    # Find all HTML files
    html_files = list(base_dir.glob('*.html'))
    
    # Filter out files in subdirectories and special files
    html_files = [f for f in html_files if f.name != 'index.html' and 'slick' not in str(f)]
    
    english_files = []
    arabic_files = []
    
    for html_file in html_files:
        if '-ar.html' in html_file.name or html_file.name.endswith('-ar.html'):
            arabic_files.append(html_file)
        else:
            english_files.append(html_file)
    
    print(f"Found {len(english_files)} English files and {len(arabic_files)} Arabic files")
    
    # Process English files
    print("\nProcessing English files...")
    for file_path in english_files:
        replace_header_in_file(file_path, is_arabic=False)
    
    # Process Arabic files
    print("\nProcessing Arabic files...")
    for file_path in arabic_files:
        replace_header_in_file(file_path, is_arabic=True)
    
    print("\nDone!")


if __name__ == '__main__':
    main()
