#!/usr/bin/env python3
"""
Move inline style injection to AFTER the qbpos.css link
This ensures it has final say on font sizes
"""
import os
import re
from pathlib import Path

def move_style_after_css_link(file_path):
    """Move the FORCE ALL FONTS style tag to after qbpos.css link."""
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        original_content = content
        
        # Find the FORCE ALL FONTS style block
        style_pattern = r'<style type="text/css">\s*/\* FORCE ALL FONTS TO 12PT \*/.*?</style>\s*'
        style_match = re.search(style_pattern, content, re.DOTALL)
        
        if not style_match:
            return False
        
        style_block = style_match.group(0)
        
        # Remove the style block from its current position
        content = content.replace(style_block, '', 1)
        
        # Find the qbpos.css link and insert AFTER it
        css_link_pattern = r'(<link[^>]*qbpos\.css[^>]*>)'
        
        if re.search(css_link_pattern, content):
            # Insert the style block right after the CSS link
            content = re.sub(
                css_link_pattern,
                r'\1\n' + style_block,
                content,
                count=1
            )
        else:
            # If no qbpos.css link found, put it after </head>
            content = re.sub(
                r'(</head>)',
                style_block + r'\1',
                content,
                flags=re.IGNORECASE
            )
        
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8', errors='ignore') as f:
                f.write(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')
    
    if not base_dir.exists():
        print(f"Error: Directory {base_dir} not found")
        return
    
    # Find all .htm files
    htm_files = list(base_dir.rglob('*.htm'))
    
    print(f"Found {len(htm_files)} HTML files")
    print("Moving inline styles to after CSS links...")
    
    modified_count = 0
    for htm_file in htm_files:
        if move_style_after_css_link(htm_file):
            modified_count += 1
            if modified_count % 100 == 0:
                print(f"  Processed {modified_count} files...")
    
    print(f"\nComplete! Modified {modified_count} files")
    print("Inline styles now come AFTER external CSS links for proper priority.")

if __name__ == "__main__":
    main()
