#!/usr/bin/env python3
"""
Script to add i18n tags to all Django templates
"""
import os
import re
from pathlib import Path

def add_i18n_load(content):
    """Add {% load i18n %} at the top if not present"""
    if '{% load i18n %}' in content or '{%load i18n%}' in content:
        return content
    
    # Check if it extends a template
    if content.strip().startswith('{% extends'):
        # Add after extends
        lines = content.split('\n')
        for i, line in enumerate(lines):
            if '{% extends' in line:
                lines.insert(i + 1, '{% load i18n %}')
                return '\n'.join(lines)
    
    # Add at the very top
    return '{% load i18n %}\n' + content

def wrap_text_in_trans(content):
    """Wrap user-facing text in {% trans %} tags"""
    
    # Common patterns to translate
    patterns = [
        # Headings and titles in HTML tags
        (r'<h[1-6][^>]*>([^<{]+)</h[1-6]>', r'<h\1>{% trans "\2" %}</h\1>'),
        (r'<title>([^<{]+)</title>', r'<title>{% trans "\1" %}</title>'),
        
        # Button text
        (r'<button[^>]*>([^<{]+)</button>', r'<button>{% trans "\1" %}</button>'),
        
        # Labels
        (r'<label[^>]*>([^<{]+)</label>', r'<label>{% trans "\1" %}</label>'),
        
        # Placeholders (already handled in topbar)
        # Table headers
        (r'<th[^>]*>([^<{]+)</th>', r'<th>{% trans "\1" %}</th>'),
        
        # Paragraphs with simple text
        (r'<p[^>]*>([^<{]+)</p>', r'<p>{% trans "\1" %}</p>'),
        
        # Span with simple text
        (r'<span[^>]*>([^<{]+)</span>', r'<span>{% trans "\1" %}</span>'),
    ]
    
    for pattern, replacement in patterns:
        content = re.sub(pattern, replacement, content)
    
    return content

def process_template(filepath):
    """Process a single template file"""
    print(f"Processing: {filepath}")
    
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # Add i18n load tag
        content = add_i18n_load(content)
        
        # Note: We'll do manual translation wrapping for better control
        # The automatic wrapping can be too aggressive
        
        if content != original_content:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"  ✓ Updated: {filepath}")
            return True
        else:
            print(f"  - No changes needed: {filepath}")
            return False
            
    except Exception as e:
        print(f"  ✗ Error processing {filepath}: {e}")
        return False

def main():
    """Main function to process all templates"""
    base_dir = Path(__file__).parent
    templates_dir = base_dir / 'templates'
    
    if not templates_dir.exists():
        print(f"Templates directory not found: {templates_dir}")
        return
    
    # Find all HTML files
    html_files = list(templates_dir.rglob('*.html'))
    
    print(f"Found {len(html_files)} template files")
    print("=" * 60)
    
    updated_count = 0
    for html_file in html_files:
        if process_template(html_file):
            updated_count += 1
    
    print("=" * 60)
    print(f"Completed! Updated {updated_count} out of {len(html_files)} files")

if __name__ == '__main__':
    main()
