#!/usr/bin/env python3
"""
Validation Script for Permission-Based Navigation System

This script validates that the permission-based navigation system has been
deployed correctly and is working as expected.

Usage:
    python validate_permission_navigation.py [--project-root /path/to/project]
"""

import os
import sys
import argparse
from pathlib import Path

def validate_template_filters(project_root):
    """Validate that template filters are correctly deployed"""
    print("Validating template filters...")
    
    filters_file = project_root / 'users' / 'templatetags' / 'permission_filters.py'
    
    if not filters_file.exists():
        print("[FAIL] Template filters file not found")
        return False
    
    with open(filters_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    required_elements = [
        'def has_module_access(user, module):',
        'user.has_permission(module, \'access\')',
        'user.is_superuser or user.role == \'admin\''
    ]
    
    for element in required_elements:
        if element not in content:
            print(f"[FAIL] Missing required element: {element}")
            return False
    
    print("[PASS] Template filters validation passed")
    return True

def validate_base_template(project_root):
    """Validate that base template has permission checks"""
    print("Validating base template...")
    
    template_file = project_root / 'templates' / 'base.html'
    
    if not template_file.exists():
        print("[FAIL] Base template file not found")
        return False
    
    with open(template_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Check for permission_filters load
    if '{% load permission_filters %}' not in content:
        print("[FAIL] permission_filters template tag not loaded")
        return False
    
    # Check for permission checks in navigation
    required_checks = [
        'user|has_module_access:\'dashboard\'',
        'user|has_module_access:\'clients\'',
        'user|has_module_access:\'loans\'',
        'user|has_module_access:\'repayments\'',
        'user|has_module_access:\'reports_statements\'',
        'user|has_module_access:\'documents\'',
        'user|has_module_access:\'notifications\''
    ]
    
    missing_checks = []
    for check in required_checks:
        if check not in content:
            missing_checks.append(check)
    
    if missing_checks:
        print(f"[FAIL] Missing permission checks: {missing_checks}")
        return False
    
    print("[PASS] Base template validation passed")
    return True

def validate_decorators(project_root):
    """Validate that decorators are correctly deployed"""
    print("Validating decorators...")
    
    decorators_file = project_root / 'users' / 'decorators.py'
    
    if not decorators_file.exists():
        print("[FAIL] Decorators file not found")
        return False
    
    with open(decorators_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    required_elements = [
        'def module_access_required(module):',
        'user.has_permission(module, \'access\')',
        'messages.error(request, f\'You do not have permission to access'
    ]
    
    for element in required_elements:
        if element not in content:
            print(f"[FAIL] Missing required element: {element}")
            return False
    
    print("[PASS] Decorators validation passed")
    return True

def validate_project_structure(project_root):
    """Validate Django project structure"""
    print("Validating project structure...")
    
    required_dirs = [
        'users/templatetags',
        'templates',
        'users'
    ]
    
    for dir_path in required_dirs:
        full_path = project_root / dir_path
        if not full_path.exists():
            print(f"[FAIL] Required directory not found: {dir_path}")
            return False
    
    print("[PASS] Project structure validation passed")
    return True

def main():
    """Main validation function"""
    parser = argparse.ArgumentParser(description='Validate permission-based navigation deployment')
    parser.add_argument('--project-root', type=str, help='Path to Django project root')
    
    args = parser.parse_args()
    
    project_root = Path(args.project_root) if args.project_root else Path.cwd()
    
    print("=" * 60)
    print("PERMISSION-BASED NAVIGATION VALIDATION")
    print("=" * 60)
    print(f"Project root: {project_root}")
    print()
    
    validations = [
        validate_project_structure,
        validate_template_filters,
        validate_base_template,
        validate_decorators
    ]
    
    all_passed = True
    for validation in validations:
        if not validation(project_root):
            all_passed = False
        print()
    
    print("=" * 60)
    if all_passed:
        print("[PASS] ALL VALIDATIONS PASSED")
        print("Permission-based navigation system is correctly deployed!")
    else:
        print("[FAIL] VALIDATION FAILED")
        print("Please check the errors above and redeploy if necessary.")
    print("=" * 60)
    
    sys.exit(0 if all_passed else 1)

if __name__ == '__main__':
    main()
