#!/usr/bin/env python
"""
Run this on production via cPanel Python console to diagnose why dashboard shows zeros.
Usage: python diagnose_dashboard_production.py
"""
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

print("=" * 60)
print("PRODUCTION DASHBOARD DIAGNOSTICS")
print("=" * 60)

# 1. Check basic loan counts
from loans.models import Loan, LoanApplication, Repayment
from users.models import CustomUser

print("\n--- DATABASE COUNTS ---")
print(f"Total loans: {Loan.objects.count()}")
print(f"Active loans: {Loan.objects.filter(status='active').count()}")
print(f"Active + not deleted: {Loan.objects.filter(status='active', is_deleted=False).count()}")
print(f"Active + not deleted + not rolled over: {Loan.objects.filter(status='active', is_deleted=False, is_rolled_over=False).count()}")
print(f"Paid loans: {Loan.objects.filter(status='paid').count()}")
print(f"Total borrowers: {CustomUser.objects.filter(role='borrower').count()}")
print(f"Active borrowers: {CustomUser.objects.filter(role='borrower', status='active').count()}")

# 2. Check if is_rolled_over field exists
print("\n--- FIELD CHECK ---")
try:
    Loan.objects.filter(is_rolled_over=False).count()
    print("is_rolled_over field: OK")
except Exception as e:
    print(f"is_rolled_over field ERROR: {e}")

try:
    Loan.objects.filter(is_deleted=False).count()
    print("is_deleted field: OK")
except Exception as e:
    print(f"is_deleted field ERROR: {e}")

# 3. Test each service method individually
print("\n--- SERVICE METHOD TESTS ---")
from reports.simple_reports_service import SimpleReportsService
svc = SimpleReportsService()

methods = [
    ('get_summary_metrics', lambda: svc.get_summary_metrics()),
    ('get_loans_due_today', lambda: svc.get_loans_due_today()),
    ('get_delinquent_loans', lambda: svc.get_delinquent_loans()),
    ('get_processing_fees_current_month', lambda: svc.get_processing_fees_current_month()),
    ('get_interest_income_current_month', lambda: svc.get_interest_income_current_month()),
    ('get_completed_loans_analytics', lambda: svc.get_completed_loans_analytics()),
    ('get_overdue_loans_analytics', lambda: svc.get_overdue_loans_analytics()),
    ('get_client_growth_analytics', lambda: svc.get_client_growth_analytics()),
    ('get_missed_payments_summary', lambda: svc.get_missed_payments_summary()),
]

for name, fn in methods:
    try:
        result = fn()
        print(f"  {name}: OK")
    except Exception as e:
        import traceback
        print(f"  {name}: FAILED — {e}")
        traceback.print_exc()

# 4. Full generate_dashboard_data
print("\n--- FULL DASHBOARD DATA (no branch filter) ---")
try:
    data = svc.generate_dashboard_data(branch_id=None)
    err = data.get('error')
    if err:
        print(f"ERROR in data: {err}")
    else:
        sm = data['summary_metrics']
        print(f"Active loans: {sm['total_active_loans']}")
        print(f"Portfolio value: {sm['total_portfolio_value']}")
        print(f"Processing fees: {data['processing_fees_current_month']['summary']['total_processing_fees']}")
        print(f"Interest income: {data['interest_income_current_month']['summary']['total_interest_income']}")
        print(f"Completed loans: {data['completed_loans']['summary']['total_completed_loans']}")
        print(f"Total clients: {data['client_growth']['summary']['total_clients']}")
except Exception as e:
    import traceback
    print(f"EXCEPTION: {e}")
    traceback.print_exc()

# 5. Check repayment_scheduler import
print("\n--- REPAYMENT SCHEDULER CHECK ---")
try:
    from loans.repayment_scheduler import RepaymentScheduler
    print("RepaymentScheduler import: OK")
    # Test on first active loan
    loan = Loan.objects.filter(status='active', is_deleted=False).first()
    if loan:
        print(f"Testing on loan: {loan.loan_number}")
        try:
            method = RepaymentScheduler.get_repayment_method(loan)
            print(f"  get_repayment_method: {method}")
        except Exception as e:
            print(f"  get_repayment_method FAILED: {e}")
        try:
            arrears = RepaymentScheduler.calculate_arrears_amount(loan)
            print(f"  calculate_arrears_amount: {arrears}")
        except Exception as e:
            print(f"  calculate_arrears_amount FAILED: {e}")
    else:
        print("No active loans to test scheduler on")
except Exception as e:
    import traceback
    print(f"RepaymentScheduler FAILED: {e}")
    traceback.print_exc()

print("\n" + "=" * 60)
print("DIAGNOSTICS COMPLETE")
print("=" * 60)
