#!/usr/bin/env python3
"""
Simple test script to verify branch filtering fixes for Reports & Statements, 
Payment Receipts, and Notifications pages.
"""

import os
import sys
import django
from datetime import datetime

# Setup Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.test import RequestFactory
from django.contrib.sessions.middleware import SessionMiddleware
from users.models import Branch, CustomUser
from utils.views import payment_receipts, notifications
from reports.views import reports_dashboard
from reports.comprehensive_reports import reports_service

def log_message(message, level='INFO'):
    """Log messages with timestamp"""
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f"[{timestamp}] {level}: {message}")

def test_branch_filtering():
    """Test branch filtering functionality"""
    log_message("Testing branch filtering functionality...")
    
    try:
        # Get existing branches and users
        branches = Branch.objects.filter(is_active=True)[:2]
        if len(branches) < 2:
            log_message("❌ Need at least 2 active branches for testing", 'ERROR')
            return False
        
        # Get an admin user
        admin_users = CustomUser.objects.filter(is_staff=True, is_active=True)[:1]
        if not admin_users:
            log_message("❌ Need at least 1 active admin user for testing", 'ERROR')
            return False
        
        admin_user = admin_users[0]
        branch1, branch2 = branches[0], branches[1]
        
        log_message(f"✅ Using branches: {branch1.name}, {branch2.name}")
        log_message(f"✅ Using admin user: {admin_user.email}")
        
        factory = RequestFactory()
        
        # Test 1: Payment Receipts
        log_message("Testing Payment Receipts branch filtering...")
        request = factory.get('/utils/payment-receipts/')
        request.user = admin_user
        
        # Add session middleware
        middleware = SessionMiddleware(lambda req: None)
        middleware.process_request(request)
        request.session.save()
        request.session['selected_branch_id'] = str(branch1.id)
        
        try:
            response = payment_receipts(request)
            if response.status_code == 200:
                log_message("✅ Payment Receipts view works with branch filtering")
            else:
                log_message(f"❌ Payment Receipts failed with status {response.status_code}", 'ERROR')
        except Exception as e:
            log_message(f"❌ Payment Receipts error: {e}", 'ERROR')
        
        # Test 2: Notifications
        log_message("Testing Notifications branch filtering...")
        request = factory.get('/utils/notifications/')
        request.user = admin_user
        
        middleware = SessionMiddleware(lambda req: None)
        middleware.process_request(request)
        request.session.save()
        request.session['selected_branch_id'] = str(branch1.id)
        
        try:
            response = notifications(request)
            if response.status_code == 200:
                log_message("✅ Notifications view works with branch filtering")
            else:
                log_message(f"❌ Notifications failed with status {response.status_code}", 'ERROR')
        except Exception as e:
            log_message(f"❌ Notifications error: {e}", 'ERROR')
        
        # Test 3: Reports Dashboard
        log_message("Testing Reports Dashboard branch filtering...")
        request = factory.get('/reports/dashboard/')
        request.user = admin_user
        
        middleware = SessionMiddleware(lambda req: None)
        middleware.process_request(request)
        request.session.save()
        request.session['selected_branch_id'] = str(branch1.id)
        
        try:
            response = reports_dashboard(request)
            if response.status_code == 200:
                log_message("✅ Reports Dashboard view works with branch filtering")
            else:
                log_message(f"❌ Reports Dashboard failed with status {response.status_code}", 'ERROR')
        except Exception as e:
            log_message(f"❌ Reports Dashboard error: {e}", 'ERROR')
        
        # Test 4: Reports Service Branch Filtering
        log_message("Testing Reports Service branch filtering...")
        try:
            dashboard_data = reports_service.generate_comprehensive_dashboard_data(branch_id=branch1.id)
            if dashboard_data and 'generated_at' in dashboard_data:
                log_message("✅ Reports service supports branch filtering")
            else:
                log_message("❌ Reports service branch filtering failed", 'ERROR')
        except Exception as e:
            log_message(f"❌ Reports service error: {e}", 'ERROR')
        
        return True
        
    except Exception as e:
        log_message(f"❌ General error: {e}", 'ERROR')
        return False

def test_admin_update_view():
    """Test admin update view functionality"""
    log_message("Testing Admin Update view...")
    
    try:
        from users.views import admin_update
        
        # Get a staff user to test with
        staff_users = CustomUser.objects.filter(is_staff=True, is_active=True)[:1]
        if not staff_users:
            log_message("❌ Need at least 1 staff user for testing", 'ERROR')
            return False
        
        staff_user = staff_users[0]
        admin_user = staff_user  # Use same user as admin for simplicity
        
        factory = RequestFactory()
        
        # Test GET request
        request = factory.get(f'/users/admins/{staff_user.id}/update/')
        request.user = admin_user
        
        middleware = SessionMiddleware(lambda req: None)
        middleware.process_request(request)
        request.session.save()
        
        try:
            response = admin_update(request, staff_user.id)
            if response.status_code == 200:
                log_message("✅ Admin Update GET request successful")
            else:
                log_message(f"❌ Admin Update GET failed with status {response.status_code}", 'ERROR')
        except Exception as e:
            log_message(f"❌ Admin Update GET error: {e}", 'ERROR')
        
        return True
        
    except Exception as e:
        log_message(f"❌ Admin Update test error: {e}", 'ERROR')
        return False

def main():
    """Run all tests"""
    log_message("Starting branch filtering and admin update tests...")
    
    tests = [
        ("Branch Filtering", test_branch_filtering),
        ("Admin Update View", test_admin_update_view)
    ]
    
    results = {}
    
    for test_name, test_func in tests:
        log_message(f"\n--- Running {test_name} Test ---")
        try:
            results[test_name] = test_func()
        except Exception as e:
            log_message(f"❌ {test_name} test failed with exception: {e}", 'ERROR')
            results[test_name] = False
    
    # Summary
    log_message("\n" + "="*50)
    log_message("TEST RESULTS SUMMARY")
    log_message("="*50)
    
    passed = 0
    total = len(results)
    
    for test_name, result in results.items():
        status = "✅ PASSED" if result else "❌ FAILED"
        log_message(f"{test_name}: {status}")
        if result:
            passed += 1
    
    log_message(f"\nOverall: {passed}/{total} tests passed")
    
    if passed == total:
        log_message("🎉 All tests passed! Branch filtering fixes are working correctly.")
    else:
        log_message("⚠️  Some tests failed. Please review the errors above.")
    
    return passed == total

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)