#!/usr/bin/env python3
"""
Direct test of view functions
"""

import os
import sys
import django
from django.conf import settings

# Add the project root to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

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

from django.test import RequestFactory
from django.contrib.auth import get_user_model
from django.contrib.sessions.middleware import SessionMiddleware
from utils.views import documents, notifications
from utils.models import Document, Notification

User = get_user_model()

def test_views_directly():
    """Test view functions directly"""
    
    print("🔍 Testing Views Directly")
    print("=" * 30)
    
    # Create request factory
    factory = RequestFactory()
    
    # Get a user
    user = User.objects.filter(is_active=True).first()
    if not user:
        print("❌ No active users found")
        return
    
    print(f"✅ Using user: {user.username}")
    
    # Test documents view
    print(f"\n📄 Testing Documents View:")
    try:
        request = factory.get('/utils/documents/')
        request.user = user
        
        # Add session middleware
        middleware = SessionMiddleware(lambda x: None)
        middleware.process_request(request)
        request.session.save()
        
        response = documents(request)
        print(f"✅ Documents view returned status: {response.status_code}")
        
        if hasattr(response, 'context_data'):
            context = response.context_data
            total_docs = context.get('total_documents', 0)
            print(f"   Total documents in context: {total_docs}")
        
    except Exception as e:
        print(f"❌ Documents view error: {e}")
    
    # Test notifications view
    print(f"\n🔔 Testing Notifications View:")
    try:
        request = factory.get('/utils/notifications/')
        request.user = user
        
        # Add session middleware
        middleware = SessionMiddleware(lambda x: None)
        middleware.process_request(request)
        request.session.save()
        
        response = notifications(request)
        print(f"✅ Notifications view returned status: {response.status_code}")
        
        if hasattr(response, 'context_data'):
            context = response.context_data
            notifications_obj = context.get('notifications')
            if notifications_obj:
                print(f"   Notifications in context: {notifications_obj.paginator.count if hasattr(notifications_obj, 'paginator') else 'Unknown'}")
        
    except Exception as e:
        print(f"❌ Notifications view error: {e}")
    
    # Check database counts
    print(f"\n📊 Database Counts:")
    print(f"   Documents: {Document.objects.count()}")
    print(f"   Notifications: {Notification.objects.count()}")

if __name__ == '__main__':
    test_views_directly()