#!/usr/bin/env python
"""
NexusMart i18n Translation Management Script
Helps generate, compile, and manage translations for the multilingual website
"""

import os
import sys
import subprocess
from pathlib import Path
from django.core.management import call_command
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nexusmart.settings')
django.setup()

from django.conf import settings


def print_header(text):
    """Print a formatted header"""
    print("\n" + "="*60)
    print(f" {text}")
    print("="*60)


def print_info(text):
    """Print info message"""
    print(f"ℹ️  {text}")


def print_success(text):
    """Print success message"""
    print(f"✅ {text}")


def print_warning(text):
    """Print warning message"""
    print(f"⚠️  {text}")


def print_error(text):
    """Print error message"""
    print(f"❌ {text}")


def get_available_languages():
    """Get list of available language codes"""
    return [lang[0] for lang in settings.LANGUAGES]


def get_locale_path():
    """Get the locale directory path"""
    return settings.LOCALE_PATHS[0] if settings.LOCALE_PATHS else Path(settings.BASE_DIR) / 'locale'


def generate_translations():
    """Generate translation template files (.po files)"""
    print_header("Generating Translation Templates")
    
    try:
        print_info("Creating .po files for all configured languages...")
        print_info(f"Languages: {', '.join(get_available_languages())}")
        
        # Generate messages for all languages
        call_command('makemessages', all=True, interactive=False, verbosity=2)
        
        print_success("Translation templates generated successfully!")
        print_info("Next step: Translate strings in .po files")
        
        # Show location of .po files
        locale_path = get_locale_path()
        print_info(f"Location: {locale_path}/")
        print_info("Files created:")
        
        for lang in get_available_languages():
            po_file = Path(locale_path) / lang / 'LC_MESSAGES' / 'django.po'
            if po_file.exists():
                print_info(f"  ✓ {po_file.relative_to(settings.BASE_DIR)}")
        
    except Exception as e:
        print_error(f"Error generating translations: {str(e)}")
        return False
    
    return True


def compile_translations():
    """Compile translation files (.po to .mo)"""
    print_header("Compiling Translations")
    
    try:
        print_info("Compiling .po files to .mo files...")
        
        call_command('compilemessages', verbosity=2)
        
        print_success("Translations compiled successfully!")
        print_info("Your website is now ready for multilingual content!")
        
        # Show location of .mo files
        locale_path = get_locale_path()
        print_info(f"Location: {locale_path}/")
        print_info("Files created:")
        
        for lang in get_available_languages():
            mo_file = Path(locale_path) / lang / 'LC_MESSAGES' / 'django.mo'
            if mo_file.exists():
                size_kb = mo_file.stat().st_size / 1024
                print_info(f"  ✓ {mo_file.relative_to(settings.BASE_DIR)} ({size_kb:.1f} KB)")
        
    except Exception as e:
        print_error(f"Error compiling translations: {str(e)}")
        return False
    
    return True


def show_translation_status():
    """Show current translation status"""
    print_header("Translation Status")
    
    locale_path = Path(get_locale_path())
    
    print_info("Language | .po File | .mo File | Status")
    print_info("-" * 50)
    
    for lang_code, lang_name in settings.LANGUAGES:
        po_file = locale_path / lang_code / 'LC_MESSAGES' / 'django.po'
        mo_file = locale_path / lang_code / 'LC_MESSAGES' / 'django.mo'
        
        po_status = "✓" if po_file.exists() else "✗"
        mo_status = "✓" if mo_file.exists() else "✗"
        
        if mo_file.exists():
            status = "Ready"
        elif po_file.exists():
            status = "Needs Compile"
        else:
            status = "Needs Generation"
        
        print_info(f"{lang_code:8} | {po_status:8} | {mo_status:8} | {status}")


def update_translations():
    """Update existing translation files"""
    print_header("Updating Translations")
    
    try:
        print_info("Updating .po files with new strings...")
        
        call_command('makemessages', all=True, update=True, interactive=False, verbosity=2)
        
        print_success("Translations updated successfully!")
        
    except Exception as e:
        print_error(f"Error updating translations: {str(e)}")
        return False
    
    return True


def show_usage():
    """Show usage information"""
    print("""
    
    NexusMart i18n Translation Management
    
    USAGE:
        python manage.py shell < i18n_manager.py
        
    Or use the following commands in Django shell:
    
    Commands:
        generate_translations()  - Create .po files for all languages
        compile_translations()   - Compile .po files to .mo files
        update_translations()    - Update existing .po files with new strings
        show_translation_status() - Show current translation status
    
    WORKFLOW:
        1. python manage.py shell
        2. exec(open('i18n_manager.py').read())
        3. generate_translations()      # Generate .po templates
        4. [Edit .po files with translations]
        5. compile_translations()       # Compile to .mo files
        6. Restart Django server
    
    """)


def main():
    """Main function"""
    print_header("NexusMart i18n Translation Manager")
    
    print("\nConfigured Languages:")
    for lang_code, lang_name in settings.LANGUAGES:
        print(f"  • {lang_code:5} - {lang_name}")
    
    print("\nLocale Path:", get_locale_path())
    
    print("\nAvailable Commands:")
    print("  1. generate_translations() - Create translation templates")
    print("  2. compile_translations()  - Compile translations")
    print("  3. update_translations()   - Update translation files")
    print("  4. show_translation_status() - Show current status")
    
    show_translation_status()


if __name__ == '__main__':
    main()
