"""
Debug the dashboard service to see what's happening
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from reports.simple_reports_service import simple_reports_service
from loans.models import Loan
from django.db.models import Q

print("=" * 60)
print("DEBUGGING DASHBOARD SERVICE")
print("=" * 60)

# Test with no branch filter (should show all data)
print("\n🔍 Testing dashboard data generation with branch_id=None...")
try:
    dashboard_data = simple_reports_service.generate_dashboard_data(
        branch_id=None, 
        portfolio_manager_id=None
    )
    
    print("\n📊 Dashboard Data Results:")
    print(f"  Active Loans: {dashboard_data['summary_metrics']['total_active_loans']}")
    print(f"  Portfolio Value: {dashboard_data['summary_metrics']['total_portfolio_value']}")
    print(f"  Outstanding: {dashboard_data['summary_metrics']['total_outstanding']}")
    print(f"  Collection Rate: {dashboard_data['summary_metrics']['collection_rate']}")
    
    if 'error' in dashboard_data:
        print(f"\n❌ Error in dashboard_data: {dashboard_data['error']}")
    
except Exception as e:
    print(f"\n❌ Exception occurred: {e}")
    import traceback
    traceback.print_exc()

# Now let's manually check what the query should return
print("\n" + "=" * 60)
print("MANUAL QUERY CHECK")
print("=" * 60)

# Check active loans directly
active_loans = Loan.objects.filter(
    status__in=['active', 'approved', 'disbursed'],
    is_deleted=False
)
print(f"\n💰 Active Loans (manual query): {active_loans.count()}")

# Check what get_summary_metrics returns
print("\n🔍 Testing get_summary_metrics directly...")
try:
    summary = simple_reports_service.get_summary_metrics(branch_id=None, portfolio_manager_id=None)
    print(f"  Result: {summary}")
except Exception as e:
    print(f"  ❌ Error: {e}")
    import traceback
    traceback.print_exc()

print("\n" + "=" * 60)
