#!/usr/bin/env python3
"""
Fix specific pages mentioned by the user that have broken CSS/layout.
"""
import os
import re

ROOT = "/Applications/XAMPP/xamppfiles/htdocs/aaa"

PAGES = [
    "agile-management/cspo-certification-c.php",
    "agile-management/safe40scrum-master-course.php",
    "agile-management/safe40popm-certification-training.php",
    "agile-management/kanban-development-with-atlassian-jira-agile.php",
    "it-service-management/itil-foundation-certification-training.php",
    "online.php",
    "meetups.php",
    "master-classes.php",
    "counselling.php",
    "corporate-training.php",
    "tutorials.php",
    "interview-questions.php",
    "faqs.php",
    "agile-management/gen-ai-for-scrum-masters.php",
    "project-management-certifications.php",
    "web-development/fullstack-development-bootcamp-training/schedule.php",
    "web-development/front-end-development-bootcamp-training/schedule.php",
    "web-development/back-end-development-bootcamp-training/schedule.php",
]

def ensure_proper_structure(content, filename):
    """Ensure page has proper header/footer structure and line breaks."""
    # Check if it's a massive single line
    line_count = content.count('\n')
    total_len = len(content)
    
    # Add line breaks after major tags if it's mostly one line
    if line_count < 10 and total_len > 30000:
        content = content.replace('<?php include __DIR__ . \'/../header.php\'; ?>', '<?php include __DIR__ . \'/../header.php\'; ?>\n')
        content = content.replace('<?php include __DIR__ . \'/header.php\'; ?>', '<?php include __DIR__ . \'/header.php\'; ?>\n')
        content = content.replace('<?php include __DIR__ . \'/../footer.php\'; ?>', '\n<?php include __DIR__ . \'/../footer.php\'; ?>\n')
        content = content.replace('<?php include __DIR__ . \'/footer.php\'; ?>', '\n<?php include __DIR__ . \'/footer.php\'; ?>\n')
        content = content.replace('</section>', '</section>\n')
        content = content.replace('<section ', '\n<section ')
        content = content.replace('</div>', '</div>\n')
        content = content.replace('<div>', '\n<div>')
        content = content.replace('<div ', '\n<div ')
        content = re.sub(r'\n{3,}', '\n\n', content)
    
    # Ensure footer include exists
    has_footer = 'footer.php' in content
    has_header = 'header.php' in content
    
    if not has_header:
        content = '<?php include __DIR__ . \'/../header.php\'; ?>\n' + content
    if not has_footer:
        content = content.rstrip() + '\n<?php include __DIR__ . \'/../footer.php\'; ?>\n'
    
    # Remove duplicated mega menu blocks
    content = re.sub(r'<!-- Desktop Mega Menu -->.*?<div class="all-courses-menu mega-menu">.*?</div>\s*</div>\s*</div>\s*</div>', '', content, flags=re.IGNORECASE | re.DOTALL, count=1)
    content = re.sub(r'<div class="all-courses-menu mega-menu">.*?</div>\s*</div>\s*</div>\s*</div>', '', content, flags=re.IGNORECASE | re.DOTALL, count=1)
    
    # Remove stray closing tags at start
    content = re.sub(r'^\s*(</div>\s*)+\s*', '', content)
    
    return content

def fix_page(filename):
    fpath = os.path.join(ROOT, filename)
    if not os.path.exists(fpath):
        print(f"SKIP: {fpath} does not exist")
        return False
    try:
        with open(fpath, "r", encoding="utf-8", errors="ignore") as f:
            content = f.read()
    except Exception as e:
        print(f"ERROR reading {fpath}: {e}")
        return False
    
    original = content
    content = ensure_proper_structure(content, filename)
    
    if content != original:
        try:
            with open(fpath, "w", encoding="utf-8") as f:
                f.write(content)
            print(f"FIXED: {fpath}")
            return True
        except Exception as e:
            print(f"ERROR writing {fpath}: {e}")
    else:
        print(f"NO CHANGE: {fpath}")
    return False

def main():
    changed = 0
    for page in PAGES:
        if fix_page(page):
            changed += 1
    print(f"\nDone. Fixed {changed} specific pages.")

if __name__ == "__main__":
    main()
