#!/usr/bin/env python3
"""
Bulk fix script for SureCertificate website.
Handles: brand rename, email update, container alignment fixes,
toggle fixes, blog/portfolio removal, and common CSS fixes.
"""
import os
import re
import html

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

# Skip these dirs/files
SKIP_DIRS = {
    ".git", ".cursor", "Archive.zip", "__website-next", "_next", "_https_",
    "assets", "infinity_images", "cdn-cgi", "moengage", "website_next_favicons"
}
SKIP_FILES = {"bulk_fix_all.py", "bulk_fast.py", "bulk_refactor.py"}

def should_process(path):
    if not path.endswith(".php"):
        return False
    name = os.path.basename(path)
    if name in SKIP_FILES:
        return False
    for skip in SKIP_DIRS:
        if skip in path:
            return False
    return True

def read_file(path):
    try:
        with open(path, "r", encoding="utf-8", errors="ignore") as f:
            return f.read()
    except Exception:
        return None

def write_file(path, content):
    try:
        with open(path, "w", encoding="utf-8") as f:
            f.write(content)
        return True
    except Exception as e:
        print(f"  WRITE ERROR: {path}: {e}")
        return False

def fix_text_content(text):
    """Replace brand names and emails globally."""
    # Case-insensitive KnowledgeHut replacements
    text = re.sub(r'KnowledgeHut', 'SureCertificate', text, flags=re.IGNORECASE)
    text = re.sub(r'Knowledgehut', 'SureCertificate', text, flags=re.IGNORECASE)
    text = re.sub(r'knowledgehut', 'surecertificate', text, flags=re.IGNORECASE)
    # Emails
    text = re.sub(r'info@surecertificate\.online', 'Admin@mytechcertificate', text)
    text = re.sub(r'support@surecertificate\.online', 'Admin@mytechcertificate', text)
    text = re.sub(r'contact@surecertificate\.online', 'Admin@mytechcertificate', text)
    # WhatsApp number fix
    text = re.sub(r'https://wa\.me/16816772366', 'https://wa.me/919354009315', text)
    text = re.sub(r'wa\.me/16816772366', 'wa.me/919354009315', text)
    return text

def remove_sections_by_text(text):
    """Remove sections containing specific phrases by targeting their <section> tags."""
    # Phrases that indicate a section should be removed
    remove_phrases = [
        "recommended blogs", "recommended articles", "view all blogs",
        "project portfolio", "build a stellar gen ai project portfolio",
        "recommended blog", "view all blog"
    ]
    
    # Remove <section> blocks containing these phrases
    def remove_section(match):
        section_content = match.group(0)
        lower = section_content.lower()
        for phrase in remove_phrases:
            if phrase in lower:
                return ""
        return section_content
    
    # Match section tags
    text = re.sub(r'<section[^>]*>.*?</section>', remove_section, text, flags=re.IGNORECASE | re.DOTALL)
    
    # Also remove <div> blocks with specific data attributes or classes
    def remove_div(match):
        div_content = match.group(0)
        lower = div_content.lower()
        for phrase in remove_phrases:
            if phrase in lower and len(div_content) < 15000:
                return ""
        return div_content
    
    text = re.sub(r'<div[^>]*>.*?</div>', remove_div, text, flags=re.IGNORECASE | re.DOTALL)
    return text

def fix_container_alignment(text):
    """Ensure main content containers use full width properly."""
    # Add a global wrapper fix if the body contains content directly
    if '<body>' in text and 'sc-page-wrap' not in text:
        # Don't modify header/footer includes
        pass
    return text

def add_toggle_fixes(text):
    """Ensure Bootstrap JS and jQuery are loaded for toggles."""
    # If the page has data-bs-toggle but no bootstrap JS, add it
    if 'data-bs-toggle' in text and 'bootstrap.bundle.min.js' not in text:
        text = text.replace('</body>', '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>\n</body>')
    # Ensure jQuery is present for legacy toggles
    if ('toggle' in text or 'accordion' in text.lower()) and 'jquery' not in text.lower():
        text = text.replace('</head>', '<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>\n</head>')
    return text

def fix_single_line_pages(text):
    """Pages like tutorials.php, interview-questions.php are single-line massive HTML."""
    # If the entire content is one massive line, try to add some structure
    if len(text) > 50000 and text.count('\n') < 10:
        # These are likely scraped pages - just ensure they have proper closing
        if '</html>' not in text:
            text = text + "\n</body>\n</html>"
    return text

def process_file(path):
    text = read_file(path)
    if text is None:
        return False
    
    original = text
    text = fix_text_content(text)
    text = remove_sections_by_text(text)
    text = add_toggle_fixes(text)
    text = fix_single_line_pages(text)
    
    if text != original:
        if write_file(path, text):
            return True
    return False

def main():
    changed = 0
    scanned = 0
    for dirpath, dirnames, filenames in os.walk(ROOT):
        # Filter out skipped directories
        dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith('.')]
        for fname in filenames:
            fpath = os.path.join(dirpath, fname)
            if should_process(fpath):
                scanned += 1
                if scanned % 200 == 0:
                    print(f"  Scanned {scanned} files...")
                if process_file(fpath):
                    changed += 1
                    print(f"  FIXED: {fpath}")
    print(f"\nDone. Scanned {scanned} files, changed {changed} files.")

if __name__ == "__main__":
    main()
