#!/usr/bin/env python3
"""
Inject responsive.css into all content HTML pages for mobile font sizing
Only targets content pages, not navigation pages
"""

import os
import re
from pathlib import Path

def inject_responsive_css(file_path):
    """Inject responsive.css link into HTML file if not already present"""
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        # Skip if responsive.css already linked
        if 'responsive.css' in content:
            return False
        
        # Skip navigation files
        file_name = str(file_path.name)
        if '___left.htm' in file_name or '___dtree' in file_name:
            return False
        
        # Look for existing qbpos.css link and add responsive.css after it
        pattern = r'(<link\s+rel=["\']StyleSheet["\']\s+href=["\'][^"\']*qbpos\.css["\'][^>]*>)'
        
        if re.search(pattern, content, re.IGNORECASE):
            # Add responsive.css right after qbpos.css
            replacement = r'\1\n<link rel="stylesheet" href="../responsive.css?v=20260110072000" type="text/css">'
            new_content = re.sub(pattern, replacement, content, flags=re.IGNORECASE)
            
            # Write back
            with open(file_path, 'w', encoding='utf-8', errors='ignore') as f:
                f.write(new_content)
            return True
        else:
            # If no qbpos.css found, try to add in <head> section
            head_pattern = r'(</title>\s*)'
            if re.search(head_pattern, content, re.IGNORECASE):
                replacement = r'\1\n<link rel="stylesheet" href="../responsive.css?v=20260110072000" type="text/css">'
                new_content = re.sub(head_pattern, replacement, content, count=1, flags=re.IGNORECASE)
                
                with open(file_path, 'w', encoding='utf-8', errors='ignore') as f:
                    f.write(new_content)
                return True
        
        return False
        
    except Exception as e:
        print(f"Error processing {file_path}: {e}")
        return False

def main():
    base_dir = Path('/home/pts/Documents/QBPOS_Help_Web/QB_Help_Web/POS_Help')
    
    # Find all .htm and .html files except navigation files
    content_files = []
    for pattern in ['**/*.htm', '**/*.html']:
        content_files.extend(base_dir.glob(pattern))
    
    # Filter out navigation and tree files
    content_files = [
        f for f in content_files 
        if '___' not in f.name and 'POS_Help.html' not in str(f)
    ]
    
    print(f"Found {len(content_files)} content files to process")
    
    updated = 0
    for file_path in content_files:
        if inject_responsive_css(file_path):
            updated += 1
            if updated % 50 == 0:
                print(f"Processed {updated} files...")
    
    print(f"\n✅ Complete! Updated {updated} out of {len(content_files)} files")
    print("Mobile and tablet devices will now display 16px fonts on all content pages")

if __name__ == '__main__':
    main()
