#!/usr/bin/env python
"""
Test script to verify customer requests management system implementation
"""
import os
import sys
import django

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
from reports.enhanced_models import CustomerRequest
from reports.comprehensive_reports import ComprehensiveReportsService
import json

User = get_user_model()

def test_customer_request_functionality():
    """Test the customer request management system"""
    
    print("Testing Customer Request Management System Implementation...")
    print("=" * 60)
    
    # Test 1: Check if CustomerRequest model exists and has required fields
    print("1. Testing CustomerRequest model...")
    try:
        # Check model fields
        required_fields = [
            'request_number', 'customer', 'request_type', 'subject', 
            'description', 'priority', 'status', 'assigned_to', 
            'resolution_notes', 'resolved_by', 'resolved_at'
        ]
        
        model_fields = [field.name for field in CustomerRequest._meta.fields]
        missing_fields = [field for field in required_fields if field not in model_fields]
        
        if missing_fields:
            print(f"   ❌ Missing fields: {missing_fields}")
        else:
            print("   ✅ All required fields present")
        
        # Check model methods
        if hasattr(CustomerRequest, 'resolution_time'):
            print("   ✅ resolution_time property exists")
        else:
            print("   ❌ resolution_time property missing")
            
        if hasattr(CustomerRequest, 'age_hours'):
            print("   ✅ age_hours property exists")
        else:
            print("   ❌ age_hours property missing")
            
    except Exception as e:
        print(f"   ❌ Model test failed: {e}")
    
    # Test 2: Check if manager methods exist
    print("\n2. Testing CustomerRequest manager methods...")
    try:
        manager_methods = [
            'pending', 'in_progress', 'resolved', 'high_priority',
            'by_type', 'assigned_to_user', 'unassigned', 'overdue',
            'get_analytics'
        ]
        
        for method in manager_methods:
            if hasattr(CustomerRequest.objects, method):
                print(f"   ✅ {method} method exists")
            else:
                print(f"   ❌ {method} method missing")
                
    except Exception as e:
        print(f"   ❌ Manager methods test failed: {e}")
    
    # Test 3: Check if views exist
    print("\n3. Testing view functions...")
    try:
        from reports import views
        
        view_functions = [
            'customer_requests_list', 'customer_request_detail', 
            'create_customer_request', 'customer_requests_report',
            'customer_requests_analytics', 'customer_requests_search',
            'bulk_update_requests'
        ]
        
        for view_func in view_functions:
            if hasattr(views, view_func):
                print(f"   ✅ {view_func} view exists")
            else:
                print(f"   ❌ {view_func} view missing")
                
    except Exception as e:
        print(f"   ❌ Views test failed: {e}")
    
    # Test 4: Check if URL patterns exist
    print("\n4. Testing URL patterns...")
    try:
        from django.urls import reverse
        
        url_patterns = [
            'reports:customer_requests_list',
            'reports:create_customer_request', 
            'reports:customer_requests_report',
            'reports:customer_requests_analytics',
            'reports:customer_requests_search',
            'reports:bulk_update_requests'
        ]
        
        for pattern in url_patterns:
            try:
                url = reverse(pattern)
                print(f"   ✅ {pattern} URL pattern exists: {url}")
            except:
                print(f"   ❌ {pattern} URL pattern missing")
                
    except Exception as e:
        print(f"   ❌ URL patterns test failed: {e}")
    
    # Test 5: Check if templates exist
    print("\n5. Testing template files...")
    try:
        import os
        template_files = [
            'templates/reports/customer_requests_list.html',
            'templates/reports/customer_request_detail.html',
            'templates/reports/create_customer_request.html',
            'templates/reports/customer_requests_report.html',
            'templates/reports/customer_requests_analytics.html'
        ]
        
        for template in template_files:
            if os.path.exists(template):
                print(f"   ✅ {template} exists")
            else:
                print(f"   ❌ {template} missing")
                
    except Exception as e:
        print(f"   ❌ Template files test failed: {e}")
    
    # Test 6: Check comprehensive reports service
    print("\n6. Testing comprehensive reports service...")
    try:
        service = ComprehensiveReportsService()
        
        # Test the enhanced customer requests report method
        report = service.get_customer_requests_report()
        
        required_keys = ['report_type', 'period', 'summary', 'analytics', 'requests']
        missing_keys = [key for key in required_keys if key not in report]
        
        if missing_keys:
            print(f"   ❌ Missing report keys: {missing_keys}")
        else:
            print("   ✅ All required report keys present")
            
        # Check analytics keys
        if 'analytics' in report:
            analytics_keys = ['type_distribution', 'priority_distribution', 'staff_workload', 'monthly_trends']
            missing_analytics = [key for key in analytics_keys if key not in report['analytics']]
            
            if missing_analytics:
                print(f"   ❌ Missing analytics keys: {missing_analytics}")
            else:
                print("   ✅ All analytics keys present")
                
    except Exception as e:
        print(f"   ❌ Comprehensive reports service test failed: {e}")
    
    # Test 7: Check forms
    print("\n7. Testing forms...")
    try:
        from reports.forms import CustomerRequestForm
        
        form = CustomerRequestForm()
        required_fields = ['customer', 'request_type', 'subject', 'description', 'priority']
        
        form_fields = list(form.fields.keys())
        missing_form_fields = [field for field in required_fields if field not in form_fields]
        
        if missing_form_fields:
            print(f"   ❌ Missing form fields: {missing_form_fields}")
        else:
            print("   ✅ All required form fields present")
            
    except Exception as e:
        print(f"   ❌ Forms test failed: {e}")
    
    print("\n" + "=" * 60)
    print("Customer Request Management System Implementation Test Complete!")
    print("=" * 60)

if __name__ == '__main__':
    test_customer_request_functionality()