#!/usr/bin/env python3
"""
Production Deployment Package: Permission-Based Navigation System

This is the main production deployment script that handles the complete
permission-based navigation system deployment with comprehensive error handling,
logging, validation, and rollback capabilities.

Features:
- Complete permission-based navigation system
- Template filters for permission checking
- View-level security decorators
- Mobile and desktop navigation support
- Automatic backup and rollback
- Comprehensive validation
- Production-ready logging
- Non-interactive operation

Usage:
    python production_deploy.py [--dry-run] [--rollback] [--validate-only]

Author: AI Assistant
Date: 2024
"""

import os
import sys
import shutil
import logging
import argparse
import subprocess
from datetime import datetime
from pathlib import Path

# Configure comprehensive logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('production_deployment.log'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

class ProductionDeployer:
    """Production deployment class for complete permission-based navigation system"""
    
    def __init__(self, project_root=None, dry_run=False):
        self.project_root = Path(project_root) if project_root else Path.cwd()
        self.dry_run = dry_run
        self.backup_dir = self.project_root / 'backups' / f'permission_nav_{datetime.now().strftime("%Y%m%d_%H%M%S")}'
        self.deployment_log = []
        self.start_time = datetime.now()
        
        # File paths
        self.template_filters_file = self.project_root / 'users' / 'templatetags' / 'permission_filters.py'
        self.base_template_file = self.project_root / 'templates' / 'base.html'
        self.decorators_file = self.project_root / 'users' / 'decorators.py'
        
        # Validate project structure
        self._validate_project_structure()
    
    def _validate_project_structure(self):
        """Validate Django project structure"""
        required_paths = [
            self.template_filters_file.parent,
            self.base_template_file.parent,
            self.decorators_file.parent
        ]
        
        for path in required_paths:
            if not path.exists():
                raise FileNotFoundError(f"Required directory not found: {path}")
        
        logger.info("Project structure validation passed")
    
    def _create_backup(self):
        """Create comprehensive backup"""
        if self.dry_run:
            logger.info("[DRY RUN] Would create backup directory")
            return
        
        self.backup_dir.mkdir(parents=True, exist_ok=True)
        
        files_to_backup = [
            self.template_filters_file,
            self.base_template_file,
            self.decorators_file
        ]
        
        for file_path in files_to_backup:
            if file_path.exists():
                backup_path = self.backup_dir / file_path.name
                shutil.copy2(file_path, backup_path)
                logger.info(f"Backed up: {file_path} -> {backup_path}")
        
        # Create deployment info file
        info_file = self.backup_dir / 'deployment_info.txt'
        with open(info_file, 'w') as f:
            f.write(f"Deployment Date: {self.start_time}\n")
            f.write(f"Project Root: {self.project_root}\n")
            f.write(f"Dry Run: {self.dry_run}\n")
            f.write("Files Backed Up:\n")
            for file_path in files_to_backup:
                if file_path.exists():
                    f.write(f"  - {file_path}\n")
        
        logger.info(f"Backup created at: {self.backup_dir}")
    
    def _deploy_template_filters(self):
        """Deploy permission template filters"""
        logger.info("Deploying template filters...")
        
        template_filters_content = '''from django import template

register = template.Library()

@register.filter
def format_module_name(value):
    """Format module name for display"""
    return value.replace('_', ' ').title()

@register.filter
def module_to_code(value):
    """Convert module name to code format"""
    return value.lower().replace(' ', '_').replace('&', 'and').replace('-', '_')

@register.filter
def get_item(dictionary, key):
    """Get item from dictionary"""
    return dictionary.get(key)

@register.filter
def has_module_access(user, module):
    """Check if user has access permission for a specific module"""
    if not user or not user.is_authenticated:
        return False
    
    # Admin users have access to everything
    if user.is_superuser or user.role == 'admin':
        return True
    
    # Check if user has access permission for the module
    return user.has_permission(module, 'access')
'''
        
        if self.dry_run:
            logger.info("[DRY RUN] Would update template filters file")
            self.deployment_log.append("Template filters: Would be updated")
        else:
            with open(self.template_filters_file, 'w', encoding='utf-8') as f:
                f.write(template_filters_content)
            logger.info("Template filters deployed successfully")
            self.deployment_log.append("Template filters: Updated successfully")
    
    def _deploy_decorators(self):
        """Deploy module access decorator"""
        logger.info("Deploying decorators...")
        
        if self.decorators_file.exists():
            with open(self.decorators_file, 'r', encoding='utf-8') as f:
                existing_content = f.read()
        else:
            existing_content = ""
        
        if 'def module_access_required(module):' in existing_content:
            logger.info("Module access decorator already exists, skipping")
            self.deployment_log.append("Decorators: Already up to date")
            return
        
        new_decorator = '''
def module_access_required(module):
    """
    Decorator to check if user has access permission for a specific module
    """
    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            if not request.user.is_authenticated:
                return redirect('users:login')
            
            # Check if user has access permission for the module
            if not request.user.has_permission(module, 'access'):
                messages.error(request, f'You do not have permission to access {module.replace("_", " ").title()}.')
                return redirect('dashboard')
            
            return view_func(request, *args, **kwargs)
        return wrapper
    return decorator


'''
        
        if self.dry_run:
            logger.info("[DRY RUN] Would add module access decorator")
            self.deployment_log.append("Decorators: Would be updated")
        else:
            if 'def api_admin_required(view_func):' in existing_content:
                updated_content = existing_content.replace(
                    'def api_admin_required(view_func):',
                    new_decorator + 'def api_admin_required(view_func):'
                )
            else:
                updated_content = existing_content + new_decorator
            
            with open(self.decorators_file, 'w', encoding='utf-8') as f:
                f.write(updated_content)
            logger.info("Decorators deployed successfully")
            self.deployment_log.append("Decorators: Updated successfully")
    
    def _deploy_base_template(self):
        """Deploy updated base template with comprehensive permission checks"""
        logger.info("Deploying base template updates...")
        
        if self.dry_run:
            logger.info("[DRY RUN] Would update base template")
            self.deployment_log.append("Base template: Would be updated")
            return
        
        with open(self.base_template_file, 'r', encoding='utf-8') as f:
            template_content = f.read()
        
        # Add permission_filters load if not present
        if '{% load permission_filters %}' not in template_content:
            template_content = template_content.replace(
                '{% load static %}',
                '{% load static %}\n{% load permission_filters %}'
            )
            logger.info("Added permission_filters template tag load")
        
        # Comprehensive navigation updates
        navigation_updates = [
            # Dashboard
            {
                'old': '''                                <li>
                                    <a href="{% url 'dashboard' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'dashboard' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-chart-line h-6 w-6 shrink-0"></i>
                                        Dashboard
                                    </a>
                                </li>''',
                'new': '''                                {% if user|has_module_access:'dashboard' %}
                                <li>
                                    <a href="{% url 'dashboard' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'dashboard' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-chart-line h-6 w-6 shrink-0"></i>
                                        Dashboard
                                    </a>
                                </li>
                                {% endif %}'''
            },
            # Clients
            {
                'old': '''                                <li>
                                    <a href="{% url 'users:client_list' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'client_list' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-users h-6 w-6 shrink-0"></i>
                                        Clients
                                    </a>
                                </li>''',
                'new': '''                                {% if user|has_module_access:'clients' %}
                                <li>
                                    <a href="{% url 'users:client_list' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'client_list' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-users h-6 w-6 shrink-0"></i>
                                        Clients
                                    </a>
                                </li>
                                {% endif %}'''
            },
            # Loans
            {
                'old': '''                                <li>
                                    <a href="{% url 'loans:loans' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'loans' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-money-bill-wave h-6 w-6 shrink-0"></i>
                                        Loans
                                    </a>
                                </li>''',
                'new': '''                                {% if user|has_module_access:'loans' %}
                                <li>
                                    <a href="{% url 'loans:loans' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'loans' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-money-bill-wave h-6 w-6 shrink-0"></i>
                                        Loans
                                    </a>
                                </li>
                                {% endif %}'''
            },
            # Repayments
            {
                'old': '''                                <li>
                                    <a href="{% url 'loans:repayments' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'repayments' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-hand-holding-usd h-6 w-6 shrink-0"></i>
                                        All Repayments
                                    </a>
                                </li>''',
                'new': '''                                {% if user|has_module_access:'repayments' %}
                                <li>
                                    <a href="{% url 'loans:repayments' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'repayments' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-hand-holding-usd h-6 w-6 shrink-0"></i>
                                        All Repayments
                                    </a>
                                </li>
                                {% endif %}'''
            },
            # Portfolio
            {
                'old': '''                                {% if user.role in 'admin,team_leader,loan_officer' %}
                                <li>
                                    <a href="{% url 'users:portfolio_dashboard' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if 'portfolio' in request.resolver_match.url_name %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-briefcase h-6 w-6 shrink-0"></i>
                                        Portfolio
                                    </a>
                                </li>
                                {% endif %}''',
                'new': '''                                {% if user.role in 'admin,team_leader,loan_officer' and user|has_module_access:'portfolio' %}
                                <li>
                                    <a href="{% url 'users:portfolio_dashboard' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if 'portfolio' in request.resolver_match.url_name %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-briefcase h-6 w-6 shrink-0"></i>
                                        Portfolio
                                    </a>
                                </li>
                                {% endif %}'''
            },
            # Reports & Statements
            {
                'old': '''                                <li>
                                    <a href="{% url 'reports:reports_dashboard' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'reports_dashboard' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-chart-bar h-6 w-6 shrink-0"></i>
                                        Reports & Statements
                                    </a>
                                </li>''',
                'new': '''                                {% if user|has_module_access:'reports_statements' %}
                                <li>
                                    <a href="{% url 'reports:reports_dashboard' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'reports_dashboard' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-chart-bar h-6 w-6 shrink-0"></i>
                                        Reports & Statements
                                    </a>
                                </li>
                                {% endif %}'''
            },
            # Documents
            {
                'old': '''                                <li>
                                    <a href="{% url 'utils:documents' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'documents' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-file-alt h-6 w-6 shrink-0"></i>
                                        Documents
                                    </a>
                                </li>''',
                'new': '''                                {% if user|has_module_access:'documents' %}
                                <li>
                                    <a href="{% url 'utils:documents' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'documents' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-file-alt h-6 w-6 shrink-0"></i>
                                        Documents
                                    </a>
                                </li>
                                {% endif %}'''
            },
            # Customer Documents
            {
                'old': '''                                <li>
                                    <a href="{% url 'utils:all_customer_documents' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'all_customer_documents' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-users-cog h-6 w-6 shrink-0"></i>
                                        Customer Documents
                                    </a>
                                </li>''',
                'new': '''                                {% if user|has_module_access:'customer_documents' %}
                                <li>
                                    <a href="{% url 'utils:all_customer_documents' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'all_customer_documents' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-users-cog h-6 w-6 shrink-0"></i>
                                        Customer Documents
                                    </a>
                                </li>
                                {% endif %}'''
            },
            # Payment Receipts
            {
                'old': '''                                <li>
                                    <a href="{% url 'utils:receipts_list' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'receipts_list' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-receipt h-6 w-6 shrink-0"></i>
                                        Payment Receipts
                                    </a>
                                </li>''',
                'new': '''                                {% if user|has_module_access:'payment_receipts' %}
                                <li>
                                    <a href="{% url 'utils:receipts_list' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'receipts_list' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-receipt h-6 w-6 shrink-0"></i>
                                        Payment Receipts
                                    </a>
                                </li>
                                {% endif %}'''
            },
            # Notifications
            {
                'old': '''                                <li>
                                    <a href="{% url 'utils:notifications' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'notifications' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-bell h-6 w-6 shrink-0"></i>
                                        Notifications
                                        <span
                                            class="notification-badge ml-auto text-white text-xs px-2 py-0.5 rounded-full hidden">0</span>
                                    </a>
                                </li>''',
                'new': '''                                {% if user|has_module_access:'notifications' %}
                                <li>
                                    <a href="{% url 'utils:notifications' %}"
                                        class="sidebar-item group flex gap-x-3 rounded-xl p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'notifications' %}active bg-secondary text-white shadow-lg{% else %}text-text-light hover:bg-secondary/20 hover:text-white{% endif %}">
                                        <i class="fas fa-bell h-6 w-6 shrink-0"></i>
                                        Notifications
                                        <span
                                            class="notification-badge ml-auto text-white text-xs px-2 py-0.5 rounded-full hidden">0</span>
                                    </a>
                                </li>
                                {% endif %}'''
            }
        ]
        
        # Apply all navigation updates
        for update in navigation_updates:
            if update['old'] in template_content:
                template_content = template_content.replace(update['old'], update['new'])
                logger.info(f"Applied navigation permission check")
            else:
                logger.warning(f"Navigation pattern not found, skipping")
        
        # Update Settings section
        settings_old = '''                                <li>
                                    <div
                                        class="text-xs font-semibold leading-6 text-gray-400 uppercase tracking-wider mb-2">
                                        Settings</div>
                                    <ul class="space-y-1">'''
        
        settings_new = '''                                {% if user|has_module_access:'settings' or user|has_module_access:'branch_settings' or user|has_module_access:'system_settings' %}
                                <li>
                                    <div
                                        class="text-xs font-semibold leading-6 text-gray-400 uppercase tracking-wider mb-2">
                                        Settings</div>
                                    <ul class="space-y-1">'''
        
        if settings_old in template_content:
            template_content = template_content.replace(settings_old, settings_new)
            logger.info("Applied Settings section permission check")
        
        # Add closing endif for Settings section
        settings_close_old = '''                                        <!-- Removed Registration Fees Settings entry here -->
                                    </ul>
                                </li>'''
        
        settings_close_new = '''                                        <!-- Removed Registration Fees Settings entry here -->
                                    </ul>
                                </li>
                                {% endif %}'''
        
        if settings_close_old in template_content and settings_close_new not in template_content:
            template_content = template_content.replace(settings_close_old, settings_close_new)
            logger.info("Added Settings section closing endif")
        
        # Write updated template
        with open(self.base_template_file, 'w', encoding='utf-8') as f:
            f.write(template_content)
        
        logger.info("Base template deployed successfully")
        self.deployment_log.append("Base template: Updated successfully")
    
    def _validate_deployment(self):
        """Validate the deployment"""
        logger.info("Validating deployment...")
        
        try:
            # Run validation script
            result = subprocess.run([
                sys.executable, 'validate_permission_navigation.py'
            ], capture_output=True, text=True, cwd=self.project_root)
            
            if result.returncode == 0:
                logger.info("Deployment validation passed")
                self.deployment_log.append("Validation: Passed")
                return True
            else:
                logger.error(f"Deployment validation failed: {result.stderr}")
                self.deployment_log.append("Validation: Failed")
                return False
                
        except Exception as e:
            logger.error(f"Validation error: {str(e)}")
            self.deployment_log.append("Validation: Error")
            return False
    
    def deploy(self):
        """Main deployment method"""
        logger.info("=" * 80)
        logger.info("PRODUCTION DEPLOYMENT: PERMISSION-BASED NAVIGATION SYSTEM")
        logger.info("=" * 80)
        logger.info(f"Project root: {self.project_root}")
        logger.info(f"Dry run: {self.dry_run}")
        logger.info(f"Start time: {self.start_time}")
        logger.info("=" * 80)
        
        try:
            # Create backup
            self._create_backup()
            
            # Deploy components
            self._deploy_template_filters()
            self._deploy_decorators()
            self._deploy_base_template()
            
            # Validate deployment
            if not self.dry_run:
                validation_passed = self._validate_deployment()
                if not validation_passed:
                    logger.error("Deployment validation failed")
                    return False
            
            # Calculate deployment time
            end_time = datetime.now()
            deployment_time = end_time - self.start_time
            
            # Log deployment summary
            logger.info("=" * 80)
            logger.info("DEPLOYMENT SUMMARY")
            logger.info("=" * 80)
            for log_entry in self.deployment_log:
                logger.info(f"  {log_entry}")
            logger.info("=" * 80)
            logger.info(f"Deployment time: {deployment_time}")
            logger.info(f"End time: {end_time}")
            
            if self.dry_run:
                logger.info("DRY RUN COMPLETED - No files were actually modified")
            else:
                logger.info("DEPLOYMENT COMPLETED SUCCESSFULLY!")
                logger.info(f"Backup created at: {self.backup_dir}")
            
            return True
            
        except Exception as e:
            logger.error(f"Deployment failed: {str(e)}")
            return False
    
    def rollback(self):
        """Rollback to previous version"""
        if not self.backup_dir.exists():
            logger.error(f"Backup directory not found: {self.backup_dir}")
            return False
        
        logger.info("Starting rollback...")
        
        try:
            files_to_restore = [
                self.template_filters_file,
                self.base_template_file,
                self.decorators_file
            ]
            
            for file_path in files_to_restore:
                backup_path = self.backup_dir / file_path.name
                if backup_path.exists():
                    shutil.copy2(backup_path, file_path)
                    logger.info(f"Restored: {file_path}")
                else:
                    logger.warning(f"Backup not found for: {file_path}")
            
            logger.info("Rollback completed successfully")
            return True
            
        except Exception as e:
            logger.error(f"Rollback failed: {str(e)}")
            return False


def main():
    """Main function with comprehensive argument parsing"""
    parser = argparse.ArgumentParser(
        description='Production deployment for permission-based navigation system',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='''
Examples:
  python production_deploy.py                    # Deploy with backup and validation
  python production_deploy.py --dry-run          # Test deployment without changes
  python production_deploy.py --rollback         # Rollback to previous version
  python production_deploy.py --validate-only    # Only validate current deployment
  python production_deploy.py --project-root /path/to/project
        '''
    )
    
    parser.add_argument('--dry-run', action='store_true',
                       help='Show what would be done without making changes')
    parser.add_argument('--rollback', action='store_true',
                       help='Rollback to previous version')
    parser.add_argument('--validate-only', action='store_true',
                       help='Only validate current deployment')
    parser.add_argument('--project-root', type=str,
                       help='Path to Django project root (default: current directory)')
    
    args = parser.parse_args()
    
    try:
        deployer = ProductionDeployer(
            project_root=args.project_root,
            dry_run=args.dry_run
        )
        
        if args.validate_only:
            success = deployer._validate_deployment()
        elif args.rollback:
            success = deployer.rollback()
        else:
            success = deployer.deploy()
        
        sys.exit(0 if success else 1)
        
    except Exception as e:
        logger.error(f"Script failed: {str(e)}")
        sys.exit(1)


if __name__ == '__main__':
    main()
