#!/usr/bin/env python3
"""
Fix specific broken pages on SureCertificate website.
1. Remove duplicated mega menu from master-classes.php and counselling.php
2. Fix structure of tutorials.php, interview-questions.php
3. Fix toggle functionality on faqs.php
4. Add proper container alignment
"""
import os
import re

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

def remove_duplicated_megamenu(content):
    """Remove the duplicated Desktop Mega Menu that appears after header include."""
    # Pattern: after header include, there's a <!-- Desktop Mega Menu --> block
    pattern = r'(<!-- Desktop Mega Menu -->.*?<div class="view-trending.*?</div>\s*</li>\s*</ul>\s*</div>\s*</div>\s*</div>)'
    # Actually, the mega menu is huge. Let's use a simpler approach:
    # Find from <!-- Desktop Mega Menu --> to the first closing </div></div></div> after the submenu
    lines = content.split('\n')
    result = []
    skip_until = -1
    for i, line in enumerate(lines):
        if skip_until >= 0 and i < skip_until:
            continue
        if '<!-- Desktop Mega Menu -->' in line or '<div class="all-courses-menu mega-menu">' in line:
            # Skip until we find a significant content change
            # Look for the end of the mega menu - typically after many </div></li></ul></div></div></div>
            j = i + 1
            depth = 0
            while j < len(lines):
                l = lines[j]
                # Count opening and closing divs roughly
                depth += l.count('<div') - l.count('</div>')
                if depth <= 0 and j > i + 50:
                    skip_until = j + 1
                    break
                # Alternative: look for obvious start of real content
                if '</section>' in l and j > i + 100:
                    skip_until = j + 1
                    break
                j += 1
                if j > i + 2000:  # Safety break
                    skip_until = j
                    break
            continue
        result.append(line)
    return '\n'.join(result)

def fix_master_classes(content):
    """Fix master-classes.php by removing duplicated mega menu and adding structure."""
    content = remove_duplicated_megamenu(content)
    # Ensure proper closing tags
    if '</body>' not in content and '</html>' not in content:
        content = content.rstrip() + '\n<?php include __DIR__ . \'/footer.php\'; ?>\n'
    return content

def fix_counselling(content):
    """Fix counselling.php by removing duplicated mega menu and adding structure."""
    content = remove_duplicated_megamenu(content)
    if '</body>' not in content and '</html>' not in content:
        content = content.rstrip() + '\n<?php include __DIR__ . \'/footer.php\'; ?>\n'
    return content

def fix_single_line_page(content, page_name):
    """Fix tutorials.php and interview-questions.php which are single-line HTML dumps."""
    # These pages have content like:
    # <?php include __DIR__ . '/header.php'; ?>
    # <div><div><div>...</div></div></div><!--$--><div>...massive html...</div><!--$--><div>...
    # <?php include __DIR__ . '/footer.php'; ?>
    
    # Add line breaks after major tags
    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')
    
    # Add line breaks after section tags
    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 ')
    
    # Remove excessive line breaks
    content = re.sub(r'\n{3,}', '\n\n', content)
    
    # Fix the container issue - add a wrapper div with proper class
    # Find the main content area and ensure it's wrapped properly
    if '<main' not in content:
        # Wrap the body content in a main tag after header
        parts = content.split('<?php include __DIR__ . \'/header.php\'; ?>\n')
        if len(parts) == 2:
            before = parts[0]
            after = parts[1]
            # Split at footer include
            footer_parts = after.split('<?php include __DIR__ . \'/footer.php\'; ?>')
            if len(footer_parts) == 2:
                middle = footer_parts[0]
                after_footer = footer_parts[1]
                middle = '<main class="sc-main-content">\n' + middle.strip() + '\n</main>\n'
                content = before + '<?php include __DIR__ . \'/header.php\'; ?>\n' + middle + '<?php include __DIR__ . \'/footer.php\'; ?>\n' + after_footer
    
    return content

def fix_faqs(content):
    """Fix faqs.php toggle functionality."""
    content = remove_duplicated_megamenu(content)
    # Add Bootstrap JS if missing
    if 'bootstrap.bundle.min.js' not in content and 'data-bs-toggle' in content:
        content = content.replace('</body>', '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>\n</body>')
    # Add jQuery if missing for legacy toggles
    if 'jquery' not in content.lower() and ('toggle' in content.lower() or 'accordion' in content.lower()):
        content = content.replace('</head>', '<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>\n</head>')
    
    # Fix the accordion/collapse mechanism - ensure all collapsible items have proper attributes
    # Find elements with data-bs-toggle="collapse" and ensure they have proper targets
    content = re.sub(
        r'<button([^>]*)data-bs-toggle="collapse"([^>]*)>',
        r'<button\1data-bs-toggle="collapse"\2>',
        content
    )
    
    if '</body>' not in content and '</html>' not in content:
        content = content.rstrip() + '\n<?php include __DIR__ . \'/footer.php\'; ?>\n'
    
    return content

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

def main():
    process_file("master-classes.php", fix_master_classes)
    process_file("counselling.php", fix_counselling)
    process_file("tutorials.php", lambda c: fix_single_line_page(c, "tutorials"))
    process_file("interview-questions.php", lambda c: fix_single_line_page(c, "interview-questions"))
    process_file("faqs.php", fix_faqs)

if __name__ == "__main__":
    main()
