"""
COMPREHENSIVE FINANCIAL REPORTS VERIFICATION
Tests ALL reports and subpages to ensure math is correct
"""
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, GeneralLedger, JournalEntry
from django.db.models import Sum, Q
from reports.financial_reports_service import get_loan_aging

def test_header(title):
    print("\n" + "=" * 100)
    print(f" {title}")
    print("=" * 100)

def test_subsection(title):
    print(f"\n{title}")
    print("-" * 100)

# ============================================================================
# 1. LOAN AGING REPORT
# ============================================================================
def verify_loan_aging():
    test_header("1. LOAN AGING REPORT")
    
    aging_data = get_loan_aging(include_detail=True)
    
    print(f"\nAs of Date: {aging_data['as_of']}")
    print(f"Total Active Loans: {aging_data['total_active_loans']}")
    print(f"Total Portfolio: KES {aging_data['total_portfolio']:,.2f}")
    print(f"Total Overdue: KES {aging_data['total_overdue']:,.2f}")
    print(f"PAR Ratio: {aging_data['par_ratio']}%")
    
    test_subsection("AGING BUCKETS")
    
    total_from_buckets = Decimal('0')
    total_count_from_buckets = 0
    
    for bucket in aging_data['buckets']:
        print(f"{bucket['label']:<20} Count: {bucket['count']:<5} "
              f"Outstanding: KES {bucket['outstanding']:>12,.2f}  "
              f"Percentage: {bucket['percentage']:>5.1f}%")
        total_from_buckets += bucket['outstanding']
        total_count_from_buckets += bucket['count']
    
    print(f"\n{'TOTALS FROM BUCKETS':<20} Count: {total_count_from_buckets:<5} "
          f"Outstanding: KES {total_from_buckets:>12,.2f}")
    
    # Verify totals match
    issues = []
    
    if abs(total_from_buckets - aging_data['total_portfolio']) > Decimal('0.01'):
        issues.append(f"Bucket sum ({total_from_buckets:,.2f}) ≠ Total portfolio ({aging_data['total_portfolio']:,.2f})")
    
    if total_count_from_buckets != aging_data['total_active_loans']:
        issues.append(f"Bucket count ({total_count_from_buckets}) ≠ Total loans ({aging_data['total_active_loans']})")
    
    # Verify against database
    active_loans = Loan.objects.filter(status='active', is_deleted=False)
    db_outstanding = Decimal('0')
    for loan in active_loans:
        db_outstanding += loan.outstanding_amount
    
    if abs(db_outstanding - aging_data['total_portfolio']) > Decimal('1.00'):
        issues.append(f"DB outstanding ({db_outstanding:,.2f}) differs from report ({aging_data['total_portfolio']:,.2f}) by {abs(db_outstanding - aging_data['total_portfolio']):,.2f}")
    
    if issues:
        print("\n⚠️  ISSUES FOUND:")
        for issue in issues:
            print(f"  - {issue}")
        return False
    else:
        print("\n✅ Loan Aging Report: ALL MATH CORRECT")
        return True

# ============================================================================
# 2. TRIAL BALANCE
# ============================================================================
def verify_trial_balance():
    test_header("2. TRIAL BALANCE")
    
    accounts = Account.objects.all()
    
    total_debits = Decimal('0')
    total_credits = Decimal('0')
    
    account_balances = []
    
    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')
        
        balance = debits - credits
        
        if abs(balance) > Decimal('0.01'):  # Only show accounts with balance
            account_balances.append({
                'code': account.code,
                'name': account.name,
                'type': account.account_type,
                'debits': debits,
                'credits': credits,
                'balance': balance,
            })
        
        total_debits += debits
        total_credits += credits
    
    print(f"\nTotal GL Entries: {GeneralLedger.objects.count()}")
    print(f"Accounts with Balances: {len(account_balances)}/{accounts.count()}")
    
    test_subsection("ACCOUNT BALANCES (Top 10 by size)")
    
    # Show top 10 accounts by balance
    sorted_accounts = sorted(account_balances, key=lambda x: abs(x['balance']), reverse=True)[:10]
    
    for acc in sorted_accounts:
        print(f"{acc['code']:<10} {acc['name'][:40]:<40} "
              f"Dr: KES {acc['debits']:>12,.2f}  Cr: KES {acc['credits']:>12,.2f}  "
              f"Bal: KES {acc['balance']:>12,.2f}")
    
    test_subsection("TRIAL BALANCE TOTALS")
    
    print(f"Total Debits:  KES {total_debits:>15,.2f}")
    print(f"Total Credits: KES {total_credits:>15,.2f}")
    print(f"Difference:    KES {(total_debits - total_credits):>15,.2f}")
    
    issues = []
    
    difference = total_debits - total_credits
    if abs(difference) > Decimal('0.01'):
        issues.append(f"Trial Balance OUT OF BALANCE by KES {difference:,.2f}")
    
    if issues:
        print("\n⚠️  ISSUES FOUND:")
        for issue in issues:
            print(f"  - {issue}")
        return False
    else:
        print("\n✅ Trial Balance: BALANCED (Debits = Credits)")
        return True

# ============================================================================
# 3. LOAN PORTFOLIO CALCULATION
# ============================================================================
def verify_loan_portfolio():
    test_header("3. LOAN PORTFOLIO CALCULATIONS")
    
    active_loans = Loan.objects.filter(status='active', is_deleted=False)
    
    total_principal = Decimal('0')
    total_total_amount = Decimal('0')
    total_disbursed = Decimal('0')
    total_outstanding = Decimal('0')
    total_paid = Decimal('0')
    
    for loan in active_loans:
        total_principal += loan.principal_amount
        total_total_amount += loan.total_amount
        total_disbursed += loan.original_disbursed_amount or loan.principal_amount
        total_outstanding += loan.outstanding_amount
        total_paid += loan.amount_paid
    
    print(f"\nActive Loans: {active_loans.count()}")
    print(f"Rolled-Over Loans: {active_loans.filter(is_rolled_over=True).count()}")
    
    test_subsection("PORTFOLIO TOTALS")
    
    print(f"Total Principal Amount:    KES {total_principal:>15,.2f}")
    print(f"Total Amount (+ Interest): KES {total_total_amount:>15,.2f}")
    print(f"Total Original Disbursed:  KES {total_disbursed:>15,.2f}")
    print(f"Total Amount Paid:         KES {total_paid:>15,.2f}")
    print(f"Total Outstanding:         KES {total_outstanding:>15,.2f}")
    
    test_subsection("VERIFICATION")
    
    # Verify: Total Amount Paid + Outstanding should approximately equal Total Amount
    calculated_total = total_paid + total_outstanding
    difference = calculated_total - total_total_amount
    
    print(f"\nTotal Paid + Outstanding:  KES {calculated_total:>15,.2f}")
    print(f"Should Equal Total Amount: KES {total_total_amount:>15,.2f}")
    print(f"Difference:                KES {difference:>15,.2f}")
    
    issues = []
    
    if abs(difference) > Decimal('100.00'):  # Allow for penalties/fees
        issues.append(f"Paid + Outstanding ≠ Total Amount (diff: KES {difference:,.2f})")
    
    if issues:
        print("\n⚠️  ISSUES FOUND:")
        for issue in issues:
            print(f"  - {issue}")
        return False
    else:
        print("\n✅ Loan Portfolio: ALL CALCULATIONS CORRECT")
        return True

# ============================================================================
# 4. REPAYMENTS VERIFICATION
# ============================================================================
def verify_repayments():
    test_header("4. REPAYMENTS VERIFICATION")
    
    # Total from Repayment table
    total_repayments = Repayment.objects.aggregate(
        total=Sum('amount')
    )['total'] or Decimal('0')
    
    # Total from summing loan.amount_paid
    total_from_loans = Decimal('0')
    for loan in Loan.objects.filter(is_deleted=False):
        total_from_loans += loan.amount_paid
    
    print(f"\nTotal Repayments (Repayment table): KES {total_repayments:>15,.2f}")
    print(f"Total Paid (sum of loan.amount_paid): KES {total_from_loans:>15,.2f}")
    print(f"Difference:                            KES {(total_repayments - total_from_loans):>15,.2f}")
    
    test_subsection("REPAYMENT DETAILS")
    
    repayment_count = Repayment.objects.count()
    loans_with_repayments = Repayment.objects.values('loan').distinct().count()
    
    print(f"Total Repayment Records: {repayment_count}")
    print(f"Loans with Repayments: {loans_with_repayments}")
    print(f"Average Repayment: KES {(total_repayments / repayment_count if repayment_count > 0 else 0):,.2f}")
    
    issues = []
    
    # Note: Some difference is expected due to LoanCalculationService filtering
    difference = abs(total_repayments - total_from_loans)
    if difference > total_repayments * Decimal('0.1'):  # More than 10% difference
        issues.append(f"Large discrepancy between repayments table and loan totals")
    
    if issues:
        print("\n⚠️  ISSUES FOUND:")
        for issue in issues:
            print(f"  - {issue}")
        print("\nNote: Small differences expected due to calculation service filtering")
        return False
    else:
        print("\n✅ Repayments: TOTALS REASONABLE")
        print("(Note: Small differences exist due to LoanCalculationService)")
        return True

# ============================================================================
# 5. INCOME CALCULATION
# ============================================================================
def verify_income():
    test_header("5. INCOME CALCULATIONS")
    
    # Find income accounts (4xxx)
    income_accounts = Account.objects.filter(code__startswith='4')
    
    print(f"\nIncome Accounts Found: {income_accounts.count()}")
    
    total_income = Decimal('0')
    
    test_subsection("INCOME BY ACCOUNT")
    
    for account in income_accounts:
        # Income accounts have credit balance
        credits = GeneralLedger.objects.filter(account=account).aggregate(
            total=Sum('credit_amount')
        )['total'] or Decimal('0')
        
        debits = GeneralLedger.objects.filter(account=account).aggregate(
            total=Sum('debit_amount')
        )['total'] or Decimal('0')
        
        balance = credits - debits  # For income, credits increase balance
        
        if abs(balance) > Decimal('0.01'):
            print(f"{account.code:<10} {account.name[:45]:<45} KES {balance:>12,.2f}")
            total_income += balance
    
    print(f"\n{'TOTAL INCOME':<56} KES {total_income:>12,.2f}")
    
    issues = []
    
    if total_income == Decimal('0'):
        issues.append("No income recorded in GL - verify journal entries are created")
    
    if issues:
        print("\n⚠️  ISSUES FOUND:")
        for issue in issues:
            print(f"  - {issue}")
        return False
    else:
        print("\n✅ Income: CALCULATIONS CORRECT")
        return True

# ============================================================================
# MAIN EXECUTION
# ============================================================================
def run_comprehensive_verification():
    print("\n" + "=" * 100)
    print(" " * 25 + "COMPREHENSIVE FINANCIAL REPORTS VERIFICATION")
    print("=" * 100)
    print("\nThis script verifies ALL math in ALL financial reports")
    print("Testing: Loan Aging, Trial Balance, Portfolio, Repayments, Income")
    
    results = {}
    
    try:
        results['loan_aging'] = verify_loan_aging()
        results['trial_balance'] = verify_trial_balance()
        results['loan_portfolio'] = verify_loan_portfolio()
        results['repayments'] = verify_repayments()
        results['income'] = verify_income()
        
        # Summary
        test_header("FINAL SUMMARY")
        
        print("\nReport Verification Results:")
        print("-" * 100)
        
        all_passed = True
        for report, passed in results.items():
            status = "✅ PASS" if passed else "⚠️  NEEDS ATTENTION"
            print(f"{report.replace('_', ' ').title():<30} {status}")
            if not passed:
                all_passed = False
        
        print("\n" + "=" * 100)
        
        if all_passed:
            print("\n🎉 ALL REPORTS VERIFIED - ALL MATH IS CORRECT!")
            print("\nAll financial reports are calculating correctly.")
            print("Safe to use in production.")
        else:
            print("\n⚠️  SOME REPORTS NEED ATTENTION")
            print("\nSee details above for specific issues.")
            print("Most issues are minor or expected.")
        
        print("\n" + "=" * 100 + "\n")
        
    except Exception as e:
        print(f"\n❌ ERROR DURING VERIFICATION: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    run_comprehensive_verification()
