#!/usr/bin/env python
"""
Debug script to identify issues with Documents, Reports & Statements, Payment Receipts, and System Alerts
"""
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.contrib.auth import get_user_model
from utils.models import Document, Notification, SystemSetting
from loans.models import Repayment
from users.models import Branch

User = get_user_model()

def check_documents():
    """Check documents and related issues"""
    print("🔍 CHECKING DOCUMENTS...")
    print("=" * 50)
    
    # Check total documents
    total_docs = Document.objects.count()
    print(f"Total Documents in database: {total_docs}")
    
    if total_docs > 0:
        # Check documents by type
        doc_types = Document.objects.values_list('document_type', flat=True).distinct()
        print(f"Document types found: {list(doc_types)}")
        
        # Check recent documents
        recent_docs = Document.objects.order_by('-created_at')[:5]
        print("\nRecent 5 documents:")
        for doc in recent_docs:
            print(f"  - {doc.name} ({doc.document_type}) by {doc.uploaded_by.get_full_name()}")
    else:
        print("❌ No documents found in database!")
    
    # Check branch filtering
    branches = Branch.objects.all()
    print(f"\nBranches in system: {branches.count()}")
    for branch in branches:
        branch_docs = Document.objects.filter(uploaded_by__branch=branch).count()
        print(f"  - {branch.name}: {branch_docs} documents")
    
    print()

def check_notifications():
    """Check notifications and system alerts"""
    print("🔔 CHECKING NOTIFICATIONS...")
    print("=" * 50)
    
    # Check total notifications
    total_notifications = Notification.objects.count()
    print(f"Total Notifications: {total_notifications}")
    
    # Check notification types
    notification_types = Notification.objects.values_list('notification_type', flat=True).distinct()
    print(f"Notification types: {list(notification_types)}")
    
    # Check system alerts (notifications without specific user)
    system_alerts = Notification.objects.filter(user__isnull=True).count()
    print(f"System Alerts (user=null): {system_alerts}")
    
    # Check by priority
    for priority in ['urgent', 'high', 'medium', 'low']:
        count = Notification.objects.filter(priority=priority).count()
        print(f"  - {priority.title()} priority: {count}")
    
    # Check recent notifications
    recent_notifications = Notification.objects.order_by('-created_at')[:5]
    print("\nRecent 5 notifications:")
    for notif in recent_notifications:
        user_info = notif.user.get_full_name() if notif.user else "System Alert"
        print(f"  - {notif.title} ({notif.notification_type}) for {user_info}")
    
    print()

def check_payment_receipts():
    """Check payment receipts"""
    print("🧾 CHECKING PAYMENT RECEIPTS...")
    print("=" * 50)
    
    # Check total repayments (which generate receipts)
    total_repayments = Repayment.objects.count()
    print(f"Total Repayments: {total_repayments}")
    
    if total_repayments > 0:
        # Check recent repayments
        recent_repayments = Repayment.objects.order_by('-payment_date')[:5]
        print("\nRecent 5 repayments:")
        for repayment in recent_repayments:
            borrower_name = repayment.loan.borrower.get_full_name() if repayment.loan and repayment.loan.borrower else "Unknown"
            receipt_number = getattr(repayment, 'receipt_number', 'N/A')
            amount = getattr(repayment, 'amount_paid', getattr(repayment, 'amount', 'N/A'))
            print(f"  - {receipt_number}: KES {amount} by {borrower_name}")
        
        # Check by branch
        branches = Branch.objects.all()
        for branch in branches:
            branch_receipts = Repayment.objects.filter(loan__borrower__branch=branch).count()
            print(f"  - {branch.name}: {branch_receipts} receipts")
    else:
        print("❌ No repayments/receipts found!")
    
    print()

def check_reports_statements():
    """Check reports and statements functionality"""
    print("📊 CHECKING REPORTS & STATEMENTS...")
    print("=" * 50)
    
    # Check if reports module is accessible
    try:
        from utils.reports import OptimizedReportGenerator
        print("✅ Reports module imported successfully")
        
        # Check if we can create a report generator instance
        generator = OptimizedReportGenerator()
        print("✅ Report generator instance created")
        
    except ImportError as e:
        print(f"❌ Reports module import error: {e}")
    except Exception as e:
        print(f"❌ Report generator error: {e}")
    
    # Check system settings for reports
    report_settings = SystemSetting.objects.filter(category='system').count()
    print(f"System settings available: {report_settings}")
    
    print()

def check_branch_filtering():
    """Check branch filtering setup"""
    print("🏢 CHECKING BRANCH FILTERING...")
    print("=" * 50)
    
    # Check users and their branches
    users = User.objects.all()
    print(f"Total users: {users.count()}")
    
    users_with_branch = User.objects.filter(branch__isnull=False).count()
    users_without_branch = User.objects.filter(branch__isnull=True).count()
    
    print(f"Users with branch: {users_with_branch}")
    print(f"Users without branch: {users_without_branch}")
    
    # Check superusers
    superusers = User.objects.filter(is_superuser=True).count()
    print(f"Superusers: {superusers}")
    
    print()

def main():
    """Main diagnostic function"""
    print("🔧 HAVEN GRAZURI INVESTMENT LIMITED- DIAGNOSTIC REPORT")
    print("=" * 60)
    print()
    
    check_documents()
    check_notifications()
    check_payment_receipts()
    check_reports_statements()
    check_branch_filtering()
    
    print("🏁 DIAGNOSTIC COMPLETE")
    print("=" * 60)

if __name__ == "__main__":
    main()