"""
Deployment script for Completed Loans & Overdue Loans Dashboard Fixes
This script verifies the fixes are working correctly
"""
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 django.utils import timezone

def verify_fixes():
    """Verify that the fixes are working correctly"""
    print("=" * 70)
    print("VERIFYING COMPLETED LOANS & OVERDUE LOANS DASHBOARD FIXES")
    print("=" * 70)
    
    service = SimpleReportsService()
    
    # Test 1: Verify completed loans uses correct status
    print("\n[TEST 1] Verifying Completed Loans Fix...")
    paid_loans_count = Loan.objects.filter(status='paid', is_deleted=False).count()
    completed_data = service.get_completed_loans_analytics()
    
    if completed_data['summary']['total_completed_loans'] == paid_loans_count:
        print(f"✅ PASS: Completed loans correctly counts {paid_loans_count} paid loans")
    else:
        print(f"❌ FAIL: Expected {paid_loans_count}, got {completed_data['summary']['total_completed_loans']}")
        return False
    
    # Test 2: Verify overdue loans analytics
    print("\n[TEST 2] Verifying Overdue Loans Analytics...")
    overdue_data = service.get_overdue_loans_analytics()
    
    required_keys = ['total_overdue_loans', 'mild_overdue', 'moderate_overdue', 'severe_overdue', 'total_overdue_amount']
    missing_keys = [key for key in required_keys if key not in overdue_data['summary']]
    
    if not missing_keys:
        print(f"✅ PASS: All required overdue analytics keys present")
        print(f"   - Total Overdue: {overdue_data['summary']['total_overdue_loans']}")
        print(f"   - 1-30 Days: {overdue_data['summary']['mild_overdue']}")
        print(f"   - 31-60 Days: {overdue_data['summary']['moderate_overdue']}")
        print(f"   - 60+ Days: {overdue_data['summary']['severe_overdue']}")
    else:
        print(f"❌ FAIL: Missing keys: {missing_keys}")
        return False
    
    # Test 3: Verify dashboard data generation
    print("\n[TEST 3] Verifying Dashboard Data Generation...")
    try:
        dashboard_data = service.generate_dashboard_data()
        
        if 'completed_loans' in dashboard_data and 'overdue_loans' in dashboard_data:
            print(f"✅ PASS: Dashboard data includes both completed and overdue loans")
            print(f"   - Completed Loans: {dashboard_data['completed_loans']['summary']['total_completed_loans']}")
            print(f"   - Overdue Loans: {dashboard_data['overdue_loans']['summary']['total_overdue_loans']}")
        else:
            print(f"❌ FAIL: Dashboard data missing required sections")
            return False
    except Exception as e:
        print(f"❌ FAIL: Error generating dashboard data: {e}")
        return False
    
    # Test 4: Verify data consistency
    print("\n[TEST 4] Verifying Data Consistency...")
    
    # Check that completed loans have amount_paid
    paid_loans = Loan.objects.filter(status='paid', is_deleted=False)
    if paid_loans.exists():
        sample_loan = paid_loans.first()
        if sample_loan.amount_paid and sample_loan.amount_paid > 0:
            print(f"✅ PASS: Completed loans have amount_paid data")
            print(f"   - Sample: {sample_loan.loan_number} - KES {sample_loan.amount_paid:,.2f}")
        else:
            print(f"⚠️  WARNING: Sample completed loan has no amount_paid")
    else:
        print(f"ℹ️  INFO: No completed loans in database (this is OK)")
    
    # Check active loans count
    active_loans = Loan.objects.filter(status='active', is_deleted=False).count()
    print(f"ℹ️  INFO: {active_loans} active loans in database")
    
    return True

def print_deployment_summary():
    """Print deployment summary"""
    print("\n" + "=" * 70)
    print("DEPLOYMENT SUMMARY")
    print("=" * 70)
    
    print("\n✅ Files Modified:")
    print("   1. reports/simple_reports_service.py")
    print("      - Fixed get_completed_loans_analytics() to use status='paid'")
    print("\n   2. templates/reports/standalone_dashboard.html")
    print("      - Updated 'Overdue Loans Details' to 'Overdue Loans Summary'")
    print("      - Changed link to simple loan list view")
    print("      - Enhanced display with totals")
    
    print("\n✅ Changes Applied:")
    print("   - Completed loans now correctly counted using status='paid'")
    print("   - Overdue Loans Summary simplified and distinct from Arrears report")
    print("   - Better user experience with clear data display")
    
    print("\n📝 Next Steps:")
    print("   1. Restart Django development server")
    print("   2. Navigate to Reports Dashboard")
    print("   3. Verify Completed Loans section shows correct data")
    print("   4. Verify Overdue Loans Summary shows breakdown")
    print("   5. Test links to ensure they navigate correctly")
    
    print("\n🔗 Dashboard URL:")
    print("   http://localhost:8000/reports/dashboard/")
    
    print("\n" + "=" * 70)

if __name__ == '__main__':
    try:
        if verify_fixes():
            print("\n" + "=" * 70)
            print("✅ ALL VERIFICATION TESTS PASSED")
            print("=" * 70)
            print_deployment_summary()
        else:
            print("\n" + "=" * 70)
            print("❌ VERIFICATION FAILED")
            print("=" * 70)
            print("\nPlease check the error messages above and fix any issues.")
    except Exception as e:
        print(f"\n❌ CRITICAL ERROR: {e}")
        import traceback
        traceback.print_exc()
