"""
Simple verification that financial reports are working correctly
"""
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
from loans.models import Loan
from reports.financial_reports_service import get_loan_aging

print("=" * 80)
print("SIMPLE FINANCIAL REPORTS VERIFICATION")
print("=" * 80)

# 1. Check Loan Portfolio
print("\n1. LOAN PORTFOLIO")
print("-" * 80)
active_loans = Loan.objects.filter(status='active', is_deleted=False)
print(f"Active Loans: {active_loans.count()}")

total_principal = sum([loan.principal_amount for loan in active_loans])
print(f"Total Principal: KES {total_principal:,.2f}")

total_outstanding = Decimal('0')
for loan in active_loans:
    outstanding = loan.outstanding_amount
    total_outstanding += outstanding

print(f"Total Outstanding: KES {total_outstanding:,.2f}")

rolled_count = active_loans.filter(is_rolled_over=True).count()
print(f"Rolled-Over Loans: {rolled_count}/{active_loans.count()}")

# 2. Check Loan Aging Report
print("\n2. LOAN AGING REPORT")
print("-" * 80)
aging_data = get_loan_aging(include_detail=False)

print(f"As of: {aging_data['as_of']}")
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']}%")

print(f"\n{'Bucket':<15} {'Count':<10} {'Outstanding':<20} {'%'}")
print("-" * 60)
for bucket in aging_data['buckets']:
    print(f"{bucket['label']:<15} {bucket['count']:<10} "
          f"KES {bucket['outstanding']:>12,.2f}  {bucket['percentage']:>5.1f}%")

# 3. Verify calculations match
print("\n3. VERIFICATION")
print("-" * 80)

# Check if aging total matches our calculation
difference = aging_data['total_portfolio'] - total_outstanding

if abs(difference) < Decimal('1.00'):  # Allow for rounding
    print(f"✅ Aging Report Outstanding matches: KES {aging_data['total_portfolio']:,.2f}")
else:
    print(f"⚠️  MISMATCH:")
    print(f"   Direct calculation: KES {total_outstanding:,.2f}")
    print(f"   Aging report: KES {aging_data['total_portfolio']:,.2f}")
    print(f"   Difference: KES {difference:,.2f}")

print("\n" + "=" * 80)
print("CONCLUSION")
print("=" * 80)

if abs(difference) < Decimal('1.00'):
    print("\n✅ Reports are calculating correctly!")
    print("   The loan aging report matches direct database calculations.")
    print("   Other reports likely working fine too.")
else:
    print("\n⚠️  There may be calculation issues to investigate.")

print("\n" + "=" * 80 + "\n")
