"""
Test script to verify completed loans and overdue loans fixes
"""
import os
import django

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

from loans.models import Loan
from reports.simple_reports_service import SimpleReportsService
from decimal import Decimal

def test_completed_loans():
    """Test completed loans analytics"""
    print("=" * 60)
    print("TESTING COMPLETED LOANS ANALYTICS")
    print("=" * 60)
    
    # Check loans with 'paid' status
    paid_loans = Loan.objects.filter(status='paid', is_deleted=False)
    print(f"\n✓ Total loans with status='paid': {paid_loans.count()}")
    
    if paid_loans.exists():
        # Show sample data
        sample_loan = paid_loans.first()
        print(f"\nSample Completed Loan:")
        print(f"  - Loan Number: {sample_loan.loan_number}")
        print(f"  - Borrower: {sample_loan.borrower.get_full_name()}")
        print(f"  - Principal: KES {sample_loan.principal_amount:,.2f}")
        print(f"  - Amount Paid: KES {sample_loan.amount_paid:,.2f}")
        print(f"  - Status: {sample_loan.status}")
        print(f"  - Updated: {sample_loan.updated_at}")
    
    # Test the service
    service = SimpleReportsService()
    completed_data = service.get_completed_loans_analytics()
    
    print(f"\n✓ Service Results:")
    print(f"  - Total Completed: {completed_data['summary']['total_completed_loans']}")
    print(f"  - Completed This Month: {completed_data['summary']['completed_this_month']}")
    print(f"  - Completed This Year: {completed_data['summary']['completed_this_year']}")
    print(f"  - Total Principal: KES {completed_data['summary']['total_principal_completed']:,.2f}")
    print(f"  - Total Collected: KES {completed_data['summary']['total_amount_collected']:,.2f}")
    
    if completed_data['summary']['total_completed_loans'] > 0:
        print("\n✅ COMPLETED LOANS FIX: SUCCESS")
    else:
        print("\n⚠️  No completed loans found. This may be expected if no loans have been fully paid.")
    
    return completed_data

def test_overdue_loans():
    """Test overdue loans analytics"""
    print("\n" + "=" * 60)
    print("TESTING OVERDUE LOANS ANALYTICS")
    print("=" * 60)
    
    # Check active loans
    active_loans = Loan.objects.filter(status='active', is_deleted=False)
    print(f"\n✓ Total active loans: {active_loans.count()}")
    
    # Test the service
    service = SimpleReportsService()
    overdue_data = service.get_overdue_loans_analytics()
    
    print(f"\n✓ Service Results:")
    print(f"  - Total Overdue: {overdue_data['summary']['total_overdue_loans']}")
    print(f"  - Mild (1-30 days): {overdue_data['summary']['mild_overdue']}")
    print(f"  - Moderate (31-60 days): {overdue_data['summary']['moderate_overdue']}")
    print(f"  - Severe (60+ days): {overdue_data['summary']['severe_overdue']}")
    print(f"  - Total Overdue Amount: KES {overdue_data['summary']['total_overdue_amount']:,.2f}")
    
    if overdue_data['summary']['total_overdue_loans'] > 0:
        print("\n✅ OVERDUE LOANS ANALYTICS: SUCCESS")
    else:
        print("\n✅ No overdue loans found. All loans are current!")
    
    return overdue_data

def test_dashboard_data():
    """Test full dashboard data generation"""
    print("\n" + "=" * 60)
    print("TESTING FULL DASHBOARD DATA")
    print("=" * 60)
    
    service = SimpleReportsService()
    dashboard_data = service.generate_dashboard_data()
    
    print("\n✓ Dashboard Data Generated Successfully")
    print(f"\nKey Metrics:")
    print(f"  - Active Loans: {dashboard_data['summary_metrics']['total_active_loans']}")
    print(f"  - Portfolio Value: KES {dashboard_data['summary_metrics']['total_portfolio_value']:,.2f}")
    print(f"  - Outstanding: KES {dashboard_data['summary_metrics']['total_outstanding']:,.2f}")
    print(f"  - Collection Rate: {dashboard_data['summary_metrics']['collection_rate']:.1f}%")
    
    print(f"\nCompleted Loans:")
    print(f"  - Total: {dashboard_data['completed_loans']['summary']['total_completed_loans']}")
    print(f"  - This Month: {dashboard_data['completed_loans']['summary']['completed_this_month']}")
    print(f"  - Amount Collected: KES {dashboard_data['completed_loans']['summary']['total_amount_collected']:,.2f}")
    
    print(f"\nOverdue Loans:")
    print(f"  - Total: {dashboard_data['overdue_loans']['summary']['total_overdue_loans']}")
    print(f"  - 1-30 Days: {dashboard_data['overdue_loans']['summary']['mild_overdue']}")
    print(f"  - 31-60 Days: {dashboard_data['overdue_loans']['summary']['moderate_overdue']}")
    print(f"  - 60+ Days: {dashboard_data['overdue_loans']['summary']['severe_overdue']}")
    
    print("\n✅ DASHBOARD DATA GENERATION: SUCCESS")
    
    return dashboard_data

if __name__ == '__main__':
    try:
        # Run all tests
        completed_data = test_completed_loans()
        overdue_data = test_overdue_loans()
        dashboard_data = test_dashboard_data()
        
        print("\n" + "=" * 60)
        print("ALL TESTS COMPLETED SUCCESSFULLY")
        print("=" * 60)
        print("\n✅ Completed Loans Fix: Applied")
        print("✅ Overdue Loans Summary: Simplified")
        print("✅ Dashboard Data: Working")
        
        print("\n📝 Summary:")
        print(f"  - Completed loans are now correctly counted using status='paid'")
        print(f"  - Overdue Loans Summary shows simple breakdown by severity")
        print(f"  - Links updated to view full lists instead of duplicating reports")
        
    except Exception as e:
        print(f"\n❌ ERROR: {e}")
        import traceback
        traceback.print_exc()
