"""
Comprehensive test script for all financial reports
Tests accuracy after rolled-over loans implementation
"""
import os
import sys
import django

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from decimal import Decimal
from datetime import date, timedelta
from loans.models import Loan, Repayment
from accounting.models import Account, JournalEntry, JournalEntryLine, GeneralLedger
from django.db.models import Sum, Q

def test_loan_portfolio_calculations():
    """Test that loan portfolio is calculated correctly"""
    print("=" * 100)
    print("1. TESTING LOAN PORTFOLIO CALCULATIONS")
    print("=" * 100)
    
    # Active loans (not deleted, status=active)
    active_loans = Loan.objects.filter(
        status='active',
        is_deleted=False
    )
    
    total_principal = active_loans.aggregate(
        total=Sum('principal_amount')
    )['total'] or Decimal('0')
    
    total_disbursed = active_loans.aggregate(
        total=Sum('original_disbursed_amount')
    )['total'] or Decimal('0')
    
    total_outstanding = Decimal('0')
    for loan in active_loans:
        outstanding = loan.total_amount - loan.amount_paid
        total_outstanding += outstanding
    
    print(f"\nActive Loans: {active_loans.count()}")
    print(f"Total Principal: KES {total_principal:,.2f}")
    print(f"Total Disbursed (original): KES {total_disbursed:,.2f}")
    print(f"Total Outstanding: KES {total_outstanding:,.2f}")
    
    # Check for rolled-over loans
    rolled_loans = active_loans.filter(is_rolled_over=True)
    print(f"\nRolled-Over Loans: {rolled_loans.count()}")
    
    if rolled_loans.exists():
        rolled_principal = rolled_loans.aggregate(total=Sum('principal_amount'))['total']
        print(f"  Principal (after rollover): KES {rolled_principal:,.2f}")
    
    return {
        'total_principal': total_principal,
        'total_outstanding': total_outstanding,
        'active_count': active_loans.count(),
    }

def test_income_calculations():
    """Test income statement calculations"""
    print("\n" + "=" * 100)
    print("2. TESTING INCOME CALCULATIONS")
    print("=" * 100)
    
    # Interest income from repayments
    interest_income_account = Account.objects.filter(
        code__startswith='4',  # Revenue accounts
        name__icontains='interest'
    ).first()
    
    if interest_income_account:
        interest_income = GeneralLedger.objects.filter(
            account=interest_income_account
        ).aggregate(total=Sum('credit_amount'))['total'] or Decimal('0')
        
        print(f"\nInterest Income Account: {interest_income_account.code} - {interest_income_account.name}")
        print(f"Total Interest Income: KES {interest_income:,.2f}")
    else:
        print("\n⚠️  Interest Income account not found")
        interest_income = Decimal('0')
    
    # Processing fee income
    fee_income_account = Account.objects.filter(
        code__startswith='4',
        name__icontains='fee'
    ).first()
    
    if fee_income_account:
        fee_income = GeneralLedger.objects.filter(
            account=fee_income_account
        ).aggregate(total=Sum('credit_amount'))['total'] or Decimal('0')
        
        print(f"\nProcessing Fee Account: {fee_income_account.code} - {fee_income_account.name}")
        print(f"Total Fee Income: KES {fee_income:,.2f}")
    else:
        print("\n⚠️  Fee Income account not found")
        fee_income = Decimal('0')
    
    total_income = interest_income + fee_income
    print(f"\n{'=' * 50}")
    print(f"TOTAL INCOME: KES {total_income:,.2f}")
    print(f"{'=' * 50}")
    
    return {
        'interest_income': interest_income,
        'fee_income': fee_income,
        'total_income': total_income,
    }

def test_repayment_totals():
    """Test that repayment totals match loan amounts paid"""
    print("\n" + "=" * 100)
    print("3. TESTING REPAYMENT TOTALS")
    print("=" * 100)
    
    # Total repayments from Repayment model
    total_repayments = Repayment.objects.aggregate(
        total=Sum('amount')
    )['total'] or Decimal('0')
    
    print(f"\nTotal Repayments (Repayment table): KES {total_repayments:,.2f}")
    
    # Total amount_paid from Loan model
    total_loan_paid = Loan.objects.filter(
        is_deleted=False
    ).aggregate(
        total=Sum('amount_paid')
    )['total'] or Decimal('0')
    
    print(f"Total Amount Paid (Loan table): KES {total_loan_paid:,.2f}")
    
    difference = total_repayments - total_loan_paid
    
    if abs(difference) < Decimal('0.01'):
        print(f"\n✅ Repayments match! Difference: KES {difference:,.2f}")
    else:
        print(f"\n⚠️  MISMATCH! Difference: KES {difference:,.2f}")
    
    return {
        'total_repayments': total_repayments,
        'total_loan_paid': total_loan_paid,
        'difference': difference,
    }

def test_loan_aging():
    """Test loan aging buckets"""
    print("\n" + "=" * 100)
    print("4. TESTING LOAN AGING")
    print("=" * 100)
    
    today = date.today()
    active_loans = Loan.objects.filter(status='active', is_deleted=False)
    
    aging_buckets = {
        'current': 0,
        '1-30': 0,
        '31-60': 0,
        '61-90': 0,
        '91-180': 0,
        '181-365': 0,
        'over_365': 0,
    }
    
    aging_amounts = {k: Decimal('0') for k in aging_buckets.keys()}
    
    for loan in active_loans:
        if loan.due_date:
            days_overdue = (today - loan.due_date.date() if hasattr(loan.due_date, 'date') else today - loan.due_date).days
        else:
            days_overdue = 0
        
        outstanding = loan.total_amount - loan.amount_paid
        
        if days_overdue <= 0:
            bucket = 'current'
        elif days_overdue <= 30:
            bucket = '1-30'
        elif days_overdue <= 60:
            bucket = '31-60'
        elif days_overdue <= 90:
            bucket = '61-90'
        elif days_overdue <= 180:
            bucket = '91-180'
        elif days_overdue <= 365:
            bucket = '181-365'
        else:
            bucket = 'over_365'
        
        aging_buckets[bucket] += 1
        aging_amounts[bucket] += outstanding
    
    print(f"\n{'Bucket':<15} {'Count':<10} {'Amount'}")
    print("-" * 50)
    for bucket in ['current', '1-30', '31-60', '61-90', '91-180', '181-365', 'over_365']:
        print(f"{bucket:<15} {aging_buckets[bucket]:<10} KES {aging_amounts[bucket]:>12,.2f}")
    
    total_aging_amount = sum(aging_amounts.values())
    print("-" * 50)
    print(f"{'TOTAL':<15} {sum(aging_buckets.values()):<10} KES {total_aging_amount:>12,.2f}")
    
    return aging_buckets, aging_amounts

def test_trial_balance():
    """Test that trial balance debits equal credits"""
    print("\n" + "=" * 100)
    print("5. TESTING TRIAL BALANCE")
    print("=" * 100)
    
    accounts = Account.objects.all()
    
    total_debits = Decimal('0')
    total_credits = Decimal('0')
    
    for account in accounts:
        debits = GeneralLedger.objects.filter(account=account).aggregate(
            total=Sum('debit_amount')
        )['total'] or Decimal('0')
        
        credits = GeneralLedger.objects.filter(account=account).aggregate(
            total=Sum('credit_amount')
        )['total'] or Decimal('0')
        
        total_debits += debits
        total_credits += credits
    
    print(f"\nTotal Debits: KES {total_debits:,.2f}")
    print(f"Total Credits: KES {total_credits:,.2f}")
    
    difference = total_debits - total_credits
    
    if abs(difference) < Decimal('0.01'):
        print(f"\n✅ Trial Balance! Difference: KES {difference:,.2f}")
    else:
        print(f"\n⚠️  OUT OF BALANCE! Difference: KES {difference:,.2f}")
    
    return {
        'total_debits': total_debits,
        'total_credits': total_credits,
        'difference': difference,
    }

def run_all_tests():
    """Run all financial report tests"""
    print("\n" + "=" * 100)
    print(" " * 30 + "FINANCIAL REPORTS TEST SUITE")
    print("=" * 100)
    
    results = {}
    
    try:
        results['portfolio'] = test_loan_portfolio_calculations()
        results['income'] = test_income_calculations()
        results['repayments'] = test_repayment_totals()
        results['aging'] = test_loan_aging()
        results['trial_balance'] = test_trial_balance()
        
        print("\n" + "=" * 100)
        print("SUMMARY")
        print("=" * 100)
        
        # Check for critical issues
        issues = []
        
        if results['repayments']['difference'] > Decimal('0.01'):
            issues.append(f"Repayment mismatch: KES {results['repayments']['difference']:,.2f}")
        
        if results['trial_balance']['difference'] > Decimal('0.01'):
            issues.append(f"Trial balance out: KES {results['trial_balance']['difference']:,.2f}")
        
        if issues:
            print("\n⚠️  ISSUES FOUND:")
            for issue in issues:
                print(f"  - {issue}")
        else:
            print("\n✅ ALL TESTS PASSED!")
        
        print(f"\nActive Loans: {results['portfolio']['active_count']}")
        print(f"Total Outstanding: KES {results['portfolio']['total_outstanding']:,.2f}")
        print(f"Total Income: KES {results['income']['total_income']:,.2f}")
        
    except Exception as e:
        print(f"\n❌ ERROR: {e}")
        import traceback
        traceback.print_exc()
    
    print("\n" + "=" * 100 + "\n")

if __name__ == '__main__':
    run_all_tests()
