#!/usr/bin/env python3
"""
i18n Message Extractor for Thymeleaf Templates

Extracts message keys from Thymeleaf templates for internationalization.
Usage: python i18n_extractor.py <template_file> [output_file]
"""

import sys
import re
import os
from pathlib import Path
from collections import defaultdict

class I18nExtractor:
    def __init__(self, file_path):
        self.file_path = Path(file_path)
        self.content = self.file_path.read_text(encoding='utf-8')
        self.message_keys = set()
        self.parameterized_keys = set()
    
    def extract_messages(self):
        """Extract all message keys from template"""
        lines = self.content.split('\n')
        
        for line in lines:
            self.extract_hash_messages(line)
            self.extract_parameterized_messages(line)
        
        return sorted(self.message_keys)
    
    def extract_hash_messages(self, line):
        """Extract #{...} message keys"""
        # Pattern for #{message.key}
        pattern = r'#\{([^}]+)\}'
        matches = re.findall(pattern, line)
        
        for match in matches:
            self.message_keys.add(match)
    
    def extract_parameterized_messages(self, line):
        """Extract parameterized message keys like #{key(param1, param2)}"""
        # Pattern for #{key(param1, param2)}
        pattern = r'#\{([^}]+)\([^}]*\)'
        matches = re.findall(pattern, line)
        
        for match in matches:
            # Extract just the key part before the parenthesis
            key_part = match.split('(')[0]
            self.parameterized_keys.add(key_part)
            self.message_keys.add(key_part)
    
    def generate_properties_file(self, output_file=None):
        """Generate properties file with extracted keys"""
        if output_file is None:
            output_file = 'messages_extracted.properties'
        
        properties_content = []
        properties_content.append("# Extracted message keys from {}".format(self.file_path))
        properties_content.append("# Generated on: {}".format(self._get_timestamp()))
        properties_content.append("")
        
        # Add all keys with placeholder values
        for key in sorted(self.message_keys):
            if key in self.parameterized_keys:
                properties_content.append("{}={}".format(key))
            else:
                properties_content.append("{}={}".format(key))
        
        content = '\n'.join(properties_content)
        
        Path(output_file).write_text(content, encoding='utf-8')
        print("Generated properties file: {}".format(output_file))
        print("Total message keys extracted: {}".format(len(self.message_keys)))
        print("Parameterized keys: {}".format(len(self.parameterized_keys)))
        
        return output_file
    
    def generate_missing_report(self, existing_file=None):
        """Generate report of missing keys compared to existing file"""
        if existing_file and os.path.exists(existing_file):
            existing_keys = self._load_existing_keys(existing_file)
            missing_keys = self.message_keys - existing_keys
            
            if missing_keys:
                print("\nMissing keys (in template but not in {}):".format(existing_file))
                for key in sorted(missing_keys):
                    print("  - {}".format(key))
            else:
                print("\n✅ All template keys exist in properties file")
            
            return missing_keys
        
        return set()
    
    def _load_existing_keys(self, file_path):
        """Load existing keys from properties file"""
        keys = set()
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith('#') and '=' in line:
                        key = line.split('=')[0].strip()
                        if key:
                            keys.add(key)
        except Exception as e:
            print("Warning: Could not read existing file: {}".format(e))
        
        return keys
    
    def _get_timestamp(self):
        """Get current timestamp"""
        from datetime import datetime
        return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    def print_summary(self):
        """Print extraction summary"""
        print("Message Key Extraction Summary")
        print("=" * 40)
        print("Template file: {}".format(self.file_path))
        print("Total unique keys: {}".format(len(self.message_keys)))
        print("Parameterized keys: {}".format(len(self.parameterized_keys)))
        print()
        
        if self.message_keys:
            print("Extracted keys:")
            for key in sorted(self.message_keys):
                param_marker = " (parameterized)" if key in self.parameterized_keys else ""
                print("  - {}{}".format(key, param_marker))

def main():
    if len(sys.argv) < 2:
        print("Usage: python i18n_extractor.py <template_file> [output_file] [--compare existing.properties]")
        sys.exit(1)
    
    template_file = sys.argv[1]
    output_file = None
    compare_file = None
    
    # Parse optional arguments
    for arg in sys.argv[2:]:
        if arg.startswith('--compare='):
            compare_file = arg[10:]  # Remove '--compare=' prefix
        elif not arg.startswith('--'):
            output_file = arg
    
    if not os.path.exists(template_file):
        print("Error: Template file '{}' not found".format(template_file))
        sys.exit(1)
    
    extractor = I18nExtractor(template_file)
    message_keys = extractor.extract_messages()
    
    # Generate properties file
    if output_file:
        extractor.generate_properties_file(output_file)
    
    # Compare with existing file
    if compare_file:
        extractor.generate_missing_report(compare_file)
    else:
        extractor.print_summary()
    
    return 0

if __name__ == "__main__":
    sys.exit(main())