#!/usr/bin/env python3
"""
Production Deployment Script: Permission-Based Navigation System

This script implements the complete permission-based navigation functionality
that dynamically shows/hides navigation items based on user access permissions.

Features:
- Template filter for checking module access permissions
- Updated base.html with conditional navigation rendering
- View-level security decorator for additional protection
- Comprehensive error handling and logging
- Production-ready with rollback capability

Usage:
    python deploy_permission_navigation.py [--dry-run] [--backup] [--rollback]

Author: AI Assistant
Date: 2024
"""

import os
import sys
import shutil
import logging
import argparse
from datetime import datetime
from pathlib import Path

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('permission_navigation_deployment.log'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

class PermissionNavigationDeployer:
    """Production deployment class for 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 = []
        
        # 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 that we're in a Django project with the expected 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 backup of files that will be modified"""
        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}")
        
        logger.info(f"Backup created at: {self.backup_dir}")
    
    def _deploy_template_filters(self):
        """Deploy the 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 the module access decorator"""
        logger.info("Deploying decorators...")
        
        # Read existing decorators file
        if self.decorators_file.exists():
            with open(self.decorators_file, 'r', encoding='utf-8') as f:
                existing_content = f.read()
        else:
            existing_content = ""
        
        # Check if module_access_required already exists
        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
        
        # Add the new decorator
        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:
            # Find the right place to insert the decorator
            if 'def api_admin_required(view_func):' in existing_content:
                # Insert before api_admin_required
                updated_content = existing_content.replace(
                    'def api_admin_required(view_func):',
                    new_decorator + 'def api_admin_required(view_func):'
                )
            else:
                # Append at the end
                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 the updated base template with 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
        
        # Read existing base template
        with open(self.base_template_file, 'r', encoding='utf-8') as f:
            template_content = f.read()
        
        # Check if permission_filters is already loaded
        if '{% load permission_filters %}' not in template_content:
            # Add the load statement after the static load
            template_content = template_content.replace(
                '{% load static %}',
                '{% load static %}\n{% load permission_filters %}'
            )
            logger.info("Added permission_filters template tag load")
        
        # Apply navigation permission checks
        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 for: {update['old'][:50]}...")
            else:
                logger.warning(f"Navigation pattern not found: {update['old'][:50]}...")
        
        # 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 _apply_mobile_navigation_updates(self):
        """Apply permission checks to mobile navigation"""
        logger.info("Applying mobile navigation permission checks...")
        
        if self.dry_run:
            logger.info("[DRY RUN] Would update mobile navigation")
            return
        
        # Read the template again to apply mobile updates
        with open(self.base_template_file, 'r', encoding='utf-8') as f:
            template_content = f.read()
        
        # Mobile navigation updates (similar patterns but for mobile sidebar)
        mobile_updates = [
            # Mobile Dashboard
            {
                'old': '''                                        <li>
                                            <a href="{% url 'dashboard' %}"
                                                class="sidebar-item group flex gap-x-3 rounded-lg p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'dashboard' %}active bg-secondary text-white{% 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-lg p-3 text-sm font-semibold leading-6 focus-ring {% if request.resolver_match.url_name == 'dashboard' %}active bg-secondary text-white{% 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 %}'''
            },
            # Mobile Reports section
            {
                'old': '''                                        <li>
                                            <div
                                                class="text-xs font-semibold leading-6 text-gray-400 uppercase tracking-wider mb-2">
                                                Reports & Analytics</div>
                                            <ul class="space-y-1">''',
                'new': '''                                        {% if user|has_module_access:'reports_statements' %}
                                        <li>
                                            <div
                                                class="text-xs font-semibold leading-6 text-gray-400 uppercase tracking-wider mb-2">
                                                Reports & Analytics</div>
                                            <ul class="space-y-1">'''
            }
        ]
        
        # Apply mobile updates
        for update in mobile_updates:
            if update['old'] in template_content:
                template_content = template_content.replace(update['old'], update['new'])
                logger.info(f"Applied mobile navigation permission check")
        
        # Close mobile Reports section
        mobile_reports_close_old = '''                                            </ul>
                                        </li>'''
        mobile_reports_close_new = '''                                            </ul>
                                        </li>
                                        {% endif %}'''
        
        if mobile_reports_close_old in template_content and mobile_reports_close_new not in template_content:
            template_content = template_content.replace(mobile_reports_close_old, mobile_reports_close_new)
            logger.info("Added mobile Reports section closing endif")
        
        # Write updated template
        with open(self.base_template_file, 'w', encoding='utf-8') as f:
            f.write(template_content)
        
        logger.info("Mobile navigation updates applied successfully")
    
    def deploy(self):
        """Main deployment method"""
        logger.info("Starting permission-based navigation deployment...")
        logger.info(f"Project root: {self.project_root}")
        logger.info(f"Dry run: {self.dry_run}")
        
        try:
            # Create backup
            self._create_backup()
            
            # Deploy components
            self._deploy_template_filters()
            self._deploy_decorators()
            self._deploy_base_template()
            self._apply_mobile_navigation_updates()
            
            # Log deployment summary
            logger.info("=" * 60)
            logger.info("DEPLOYMENT SUMMARY")
            logger.info("=" * 60)
            for log_entry in self.deployment_log:
                logger.info(f"  {log_entry}")
            logger.info("=" * 60)
            
            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 using backup"""
        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 command line argument parsing"""
    parser = argparse.ArgumentParser(
        description='Deploy permission-based navigation system',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='''
Examples:
  python deploy_permission_navigation.py                    # Deploy with backup
  python deploy_permission_navigation.py --dry-run          # Test deployment
  python deploy_permission_navigation.py --rollback         # Rollback changes
  python deploy_permission_navigation.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('--backup', action='store_true', default=True,
                       help='Create backup before deployment (default: True)')
    parser.add_argument('--rollback', action='store_true',
                       help='Rollback to previous version')
    parser.add_argument('--project-root', type=str,
                       help='Path to Django project root (default: current directory)')
    
    args = parser.parse_args()
    
    try:
        deployer = PermissionNavigationDeployer(
            project_root=args.project_root,
            dry_run=args.dry_run
        )
        
        if 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()
