#!/usr/bin/env python3
"""
Simple test to check if utils pages are showing data
"""

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 Client
from django.contrib.auth import get_user_model
from utils.models import Document, Notification

User = get_user_model()

def test_pages():
    """Test if pages are accessible and showing data"""
    
    print("🔍 Testing Utils Pages Data Display")
    print("=" * 40)
    
    # Check if we have any data
    total_documents = Document.objects.count()
    total_notifications = Notification.objects.count()
    
    print(f"📊 Database Status:")
    print(f"   Documents: {total_documents}")
    print(f"   Notifications: {total_notifications}")
    
    if total_documents == 0:
        print("⚠️ No documents found in database")
        # Create a test document
        try:
            user = User.objects.first()
            if user:
                doc = Document.objects.create(
                    name="Test Document",
                    uploaded_by=user,
                    document_type="other"
                )
                print(f"✅ Created test document: {doc.name}")
            else:
                print("❌ No users found to create test document")
        except Exception as e:
            print(f"❌ Error creating test document: {e}")
    
    if total_notifications == 0:
        print("⚠️ No notifications found in database")
        # Create a test notification
        try:
            user = User.objects.first()
            if user:
                notif = Notification.objects.create(
                    user=user,
                    title="Test Notification",
                    message="This is a test notification",
                    notification_type="system_maintenance"
                )
                print(f"✅ Created test notification: {notif.title}")
            else:
                print("❌ No users found to create test notification")
        except Exception as e:
            print(f"❌ Error creating test notification: {e}")
    
    # Test with a user
    client = Client()
    
    # Get or create a test user
    try:
        user = User.objects.filter(is_active=True).first()
        if not user:
            user = User.objects.create_user(
                username='testuser',
                email='test@example.com',
                password='testpass123'
            )
            print(f"✅ Created test user: {user.username}")
        
        # Login
        client.login(username=user.username, password='testpass123' if user.username == 'testuser' else 'admin')
        print(f"✅ Logged in as: {user.username}")
        
        # Test documents page
        print(f"\n📄 Testing Documents Page:")
        response = client.get('/utils/documents/')
        if response.status_code == 200:
            print(f"✅ Documents page accessible (status: {response.status_code})")
            content = response.content.decode()
            if "Total Documents:" in content:
                print("✅ Documents page shows document count")
            else:
                print("❌ Documents page missing document count")
        else:
            print(f"❌ Documents page error (status: {response.status_code})")
        
        # Test notifications page
        print(f"\n🔔 Testing Notifications Page:")
        response = client.get('/utils/notifications/')
        if response.status_code == 200:
            print(f"✅ Notifications page accessible (status: {response.status_code})")
            content = response.content.decode()
            if "notifications" in content.lower():
                print("✅ Notifications page shows notifications")
            else:
                print("❌ Notifications page missing notifications")
        else:
            print(f"❌ Notifications page error (status: {response.status_code})")
        
        # Test receipts page
        print(f"\n🧾 Testing Receipts Page:")
        response = client.get('/utils/receipts/')
        if response.status_code == 200:
            print(f"✅ Receipts page accessible (status: {response.status_code})")
        else:
            print(f"❌ Receipts page error (status: {response.status_code})")
        
    except Exception as e:
        print(f"❌ Error during testing: {e}")
    
    print(f"\n🎯 Summary:")
    print(f"   Check the Django console output for DEBUG messages")
    print(f"   Visit the pages manually to see if data is displayed")

if __name__ == '__main__':
    test_pages()