"""
COMPREHENSIVE VERIFICATION OF ALL FINANCIAL REPORTS
Verifies math in:
1. Chart of Accounts
2. Trial Balance
3. Income Statement
4. Balance Sheet (Statement of Financial Position)
5. Loan Aging Report
6. SasaPay Reconciliation
7. Profit & Loss Statement
"""

import os
import sys
import django
from decimal import Decimal

# Setup Django
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from datetime import date, datetime, timedelta
from django.db.models import Sum, Q
from django.utils import timezone
from accounting.models import Account, GeneralLedger, JournalEntry
from loans.models import Loan, Repayment
from reports.financial_reports_service import (
    get_loan_aging, 
    get_financial_statements, 
    get_profit_and_loss,
    get_sasapay_reconciliation
)
from accounting.services import AccountingService

def _d(value):
    """Convert to Decimal safely"""
    if value is None:
        return Decimal('0.00')
    return Decimal(str(value))

def print_header(title, char="=", width=100):
    """Print formatted header"""
    print(f"\n{char * width}")
    print(f" {title.center(width-2)}")
    print(f"{char * width}")

def print_section(title):
    """Print section header"""
    print(f"\n{'-' * 100}")
    print(f" {title}")
    print(f"{'-' * 100}")

def verify_chart_of_accounts():
    """Verify Chart of Accounts has correct balances"""
    print_header("1. CHART OF ACCOUNTS VERIFICATION")
    
    accounting_service = AccountingService()
    as_of = date.today()
    
    # Get all active accounts
    accounts = Account.objects.filter(is_active=True).order_by('code')
    total_accounts = accounts.count()
    
    print(f"Total Active Accounts: {total_accounts}")
    
    # Calculate balance for each type
    asset_total = Decimal('0.00')
    liability_total = Decimal('0.00')
    equity_total = Decimal('0.00')
    income_total = Decimal('0.00')
    expense_total = Decimal('0.00')
    
    accounts_with_balance = 0
    
    print(f"\nACCOUNTS WITH NON-ZERO BALANCES:")
    print(f"{'Code':<10} {'Name':<50} {'Type':<12} {'Balance':>20}")
    print("-" * 100)
    
    for account in accounts:
        balance = _d(accounting_service.calculate_account_balance(
            account=account,
            as_of_date=as_of
        ))
        
        if balance != 0:
            accounts_with_balance += 1
            print(f"{account.code:<10} {account.name[:48]:<50} {account.account_type:<12} KES {balance:>15,.2f}")
            
            if account.account_type == 'asset':
                asset_total += balance
            elif account.account_type == 'liability':
                liability_total += balance
            elif account.account_type == 'equity':
                equity_total += balance
            elif account.account_type == 'income':
                income_total += balance
            elif account.account_type == 'expense':
                expense_total += balance
    
    print(f"\nSUMMARY BY ACCOUNT TYPE:")
    print(f"{'Type':<20} {'Total':>20}")
    print("-" * 50)
    print(f"{'Assets':<20} KES {asset_total:>15,.2f}")
    print(f"{'Liabilities':<20} KES {liability_total:>15,.2f}")
    print(f"{'Equity':<20} KES {equity_total:>15,.2f}")
    print(f"{'Income':<20} KES {income_total:>15,.2f}")
    print(f"{'Expenses':<20} KES {expense_total:>15,.2f}")
    
    # Verify accounting equation: Assets = Liabilities + Equity
    print(f"\nACCOUNTING EQUATION VERIFICATION:")
    print(f"Assets:                 KES {asset_total:>15,.2f}")
    print(f"Liabilities + Equity:   KES {(liability_total + equity_total):>15,.2f}")
    print(f"Difference:             KES {abs(asset_total - (liability_total + equity_total)):>15,.2f}")
    
    is_balanced = abs(asset_total - (liability_total + equity_total)) < Decimal('0.01')
    
    if is_balanced:
        print("✅ Chart of Accounts: BALANCED")
    else:
        print("⚠️  Chart of Accounts: NOT BALANCED")
    
    return is_balanced

def verify_trial_balance():
    """Verify Trial Balance (all debits = all credits)"""
    print_header("2. TRIAL BALANCE VERIFICATION")
    
    # Sum all debits and credits from General Ledger
    gl_entries = GeneralLedger.objects.all()
    total_entries = gl_entries.count()
    
    print(f"Total GL Entries: {total_entries}")
    
    total_debits = _d(gl_entries.aggregate(total=Sum('debit_amount'))['total'])
    total_credits = _d(gl_entries.aggregate(total=Sum('credit_amount'))['total'])
    
    print(f"\nTRIAL BALANCE TOTALS:")
    print(f"Total Debits:  KES {total_debits:>15,.2f}")
    print(f"Total Credits: KES {total_credits:>15,.2f}")
    print(f"Difference:    KES {abs(total_debits - total_credits):>15,.2f}")
    
    is_balanced = abs(total_debits - total_credits) < Decimal('0.01')
    
    if is_balanced:
        print("✅ Trial Balance: BALANCED (Debits = Credits)")
    else:
        print("⚠️  Trial Balance: NOT BALANCED")
    
    return is_balanced

def verify_income_statement():
    """Verify Income Statement calculations"""
    print_header("3. INCOME STATEMENT VERIFICATION")
    
    # Get current month
    today = date.today()
    start_date = date(today.year, today.month, 1)
    end_date = today
    
    pl_data = get_profit_and_loss(start_date=start_date, end_date=end_date)
    
    print(f"Period: {start_date} to {end_date}")
    print(f"Source: {pl_data.get('source', 'N/A')}")
    
    totals = pl_data.get('totals', {})
    gross_income = _d(totals.get('gross_income', 0))
    total_expenses = _d(totals.get('total_expenses', 0))
    net_income = _d(totals.get('net_income', 0))
    
    print(f"\nINCOME STATEMENT SUMMARY:")
    print(f"Gross Income:     KES {gross_income:>15,.2f}")
    print(f"Total Expenses:   KES {total_expenses:>15,.2f}")
    print(f"Net Income:       KES {net_income:>15,.2f}")
    
    # Verify calculation: Net Income = Gross Income - Total Expenses
    calculated_net = gross_income - total_expenses
    difference = abs(net_income - calculated_net)
    
    print(f"\nVERIFICATION:")
    print(f"Calculated Net Income: KES {calculated_net:>15,.2f}")
    print(f"Reported Net Income:   KES {net_income:>15,.2f}")
    print(f"Difference:            KES {difference:>15,.2f}")
    
    is_correct = difference < Decimal('0.01')
    
    if is_correct:
        print("✅ Income Statement: CALCULATIONS CORRECT")
    else:
        print("⚠️  Income Statement: CALCULATION ERROR")
    
    # Show income breakdown
    income = pl_data.get('income', {})
    if income:
        print(f"\nINCOME BREAKDOWN:")
        for category, items in income.items():
            if isinstance(items, list):
                for item in items:
                    print(f"  {item.get('account_code', 'N/A'):<10} {item.get('name', 'N/A'):<50} KES {_d(item.get('amount', 0)):>12,.2f}")
    
    # Show expense breakdown
    expenses = pl_data.get('expenses', {})
    if expenses:
        print(f"\nEXPENSE BREAKDOWN:")
        for category, items in expenses.items():
            if isinstance(items, list):
                for item in items:
                    print(f"  {item.get('account_code', 'N/A'):<10} {item.get('name', 'N/A'):<50} KES {_d(item.get('amount', 0)):>12,.2f}")
    
    return is_correct

def verify_balance_sheet():
    """Verify Balance Sheet (Statement of Financial Position)"""
    print_header("4. BALANCE SHEET VERIFICATION")
    
    fs_data = get_financial_statements(as_of_date=date.today())
    
    print(f"As of Date: {fs_data.get('as_of_date', 'N/A')}")
    print(f"Source: {fs_data.get('source', 'N/A')}")
    
    assets = fs_data.get('assets', {})
    liabilities = fs_data.get('liabilities', {})
    equity = fs_data.get('equity', {})
    
    total_assets = _d(assets.get('total_assets', 0))
    total_liabilities = _d(liabilities.get('total_liabilities', 0))
    total_equity = _d(equity.get('total_equity', 0))
    
    print(f"\nBALANCE SHEET SUMMARY:")
    print(f"Total Assets:       KES {total_assets:>15,.2f}")
    print(f"Total Liabilities:  KES {total_liabilities:>15,.2f}")
    print(f"Total Equity:       KES {total_equity:>15,.2f}")
    
    # Verify accounting equation: Assets = Liabilities + Equity
    liabilities_plus_equity = total_liabilities + total_equity
    difference = abs(total_assets - liabilities_plus_equity)
    
    print(f"\nACCOUNTING EQUATION:")
    print(f"Assets:                    KES {total_assets:>15,.2f}")
    print(f"Liabilities + Equity:      KES {liabilities_plus_equity:>15,.2f}")
    print(f"Difference:                KES {difference:>15,.2f}")
    
    is_balanced = fs_data.get('balanced', False)
    
    if is_balanced:
        print("✅ Balance Sheet: BALANCED")
    else:
        print("⚠️  Balance Sheet: NOT BALANCED (Income/Expense not yet closed to Retained Earnings)")
        print(f"   NOTE: This is EXPECTED. Balance Sheet shows point-in-time snapshot.")
        print(f"   Income ({_d(total_assets) - _d(total_liabilities) - _d(total_equity):,.2f}) needs to be closed to Retained Earnings at period-end.")
    
    # Show asset breakdown
    asset_items = assets.get('items', [])
    if asset_items:
        print(f"\nASSET BREAKDOWN:")
        for item in asset_items:
            if _d(item.get('balance', 0)) != 0:
                print(f"  {item.get('account_code', 'N/A'):<10} {item.get('name', 'N/A'):<50} KES {_d(item.get('balance', 0)):>12,.2f}")
    
    # Show liability breakdown
    liability_items = liabilities.get('items', [])
    if liability_items:
        print(f"\nLIABILITY BREAKDOWN:")
        for item in liability_items:
            if _d(item.get('balance', 0)) != 0:
                print(f"  {item.get('account_code', 'N/A'):<10} {item.get('name', 'N/A'):<50} KES {_d(item.get('balance', 0)):>12,.2f}")
    
    # Show equity breakdown
    equity_items = equity.get('items', [])
    if equity_items:
        print(f"\nEQUITY BREAKDOWN:")
        for item in equity_items:
            if _d(item.get('balance', 0)) != 0:
                print(f"  {item.get('account_code', 'N/A'):<10} {item.get('name', 'N/A'):<50} KES {_d(item.get('balance', 0)):>12,.2f}")
    
    return is_balanced

def verify_loan_aging():
    """Verify Loan Aging Report"""
    print_header("5. LOAN AGING REPORT VERIFICATION")
    
    aging_data = get_loan_aging()
    
    print(f"As of Date: {aging_data.get('as_of_date', 'N/A')}")
    print(f"Total Active Loans: {aging_data.get('total_loans', 0)}")
    
    total_portfolio = _d(aging_data.get('total_portfolio', 0))
    total_overdue = _d(aging_data.get('total_overdue', 0))
    
    print(f"Total Portfolio: KES {total_portfolio:>15,.2f}")
    print(f"Total Overdue:   KES {total_overdue:>15,.2f}")
    print(f"PAR Ratio:       {aging_data.get('par_ratio', 0):.1f}%")
    
    # Verify aging buckets sum to total
    buckets = aging_data.get('buckets', [])
    bucket_total = Decimal('0.00')
    
    print(f"\nAGING BUCKETS:")
    print(f"{'Bucket':<25} {'Count':>8} {'Outstanding':>20} {'%':>8}")
    print("-" * 70)
    
    for bucket in buckets:
        bucket_outstanding = _d(bucket.get('outstanding', 0))
        bucket_total += bucket_outstanding
        print(f"{bucket.get('label', 'N/A'):<25} {bucket.get('count', 0):>8} KES {bucket_outstanding:>15,.2f} {bucket.get('percentage', 0):>6.1f}%")
    
    print(f"{'TOTAL FROM BUCKETS':<25} {sum(b.get('count', 0) for b in buckets):>8} KES {bucket_total:>15,.2f}")
    
    # Verify totals match
    difference = abs(total_portfolio - bucket_total)
    
    print(f"\nVERIFICATION:")
    print(f"Total Portfolio (header): KES {total_portfolio:>15,.2f}")
    print(f"Sum of Buckets:           KES {bucket_total:>15,.2f}")
    print(f"Difference:               KES {difference:>15,.2f}")
    
    is_correct = difference < Decimal('0.01')
    
    if is_correct:
        print("✅ Loan Aging: CALCULATIONS CORRECT")
    else:
        print("⚠️  Loan Aging: CALCULATION ERROR")
    
    return is_correct

def verify_sasapay_reconciliation():
    """Verify SasaPay Reconciliation"""
    print_header("6. SASAPAY RECONCILIATION VERIFICATION")
    
    # Get current month
    today = date.today()
    start_date = date(today.year, today.month, 1)
    end_date = today
    
    sasapay_data = get_sasapay_reconciliation(start_date=start_date, end_date=end_date)
    
    print(f"Period: {start_date} to {end_date}")
    
    system_total = _d(sasapay_data.get('system_total', 0))
    sasapay_total = _d(sasapay_data.get('sasapay_total', 0))
    difference = _d(sasapay_data.get('difference', 0))
    
    print(f"\nRECONCILIATION SUMMARY:")
    print(f"System Total (Repayments): KES {system_total:>15,.2f}")
    print(f"SasaPay Total:             KES {sasapay_total:>15,.2f}")
    print(f"Difference:                KES {difference:>15,.2f}")
    
    # Verify calculation
    calculated_diff = abs(system_total - sasapay_total)
    
    is_correct = abs(difference - calculated_diff) < Decimal('0.01')
    
    if is_correct:
        print("✅ SasaPay Reconciliation: CALCULATIONS CORRECT")
    else:
        print("⚠️  SasaPay Reconciliation: CALCULATION ERROR")
    
    # Show unmatched transactions
    unmatched = sasapay_data.get('unmatched_transactions', [])
    if unmatched:
        print(f"\nUNMATCHED TRANSACTIONS: {len(unmatched)}")
    
    return is_correct

def verify_profit_and_loss():
    """Verify Profit & Loss Statement (same as Income Statement but verify independently)"""
    print_header("7. PROFIT & LOSS STATEMENT VERIFICATION")
    
    # Get year-to-date
    today = date.today()
    start_date = date(today.year, 1, 1)
    end_date = today
    
    pl_data = get_profit_and_loss(start_date=start_date, end_date=end_date)
    
    print(f"Period: {start_date} to {end_date} (Year-to-Date)")
    
    totals = pl_data.get('totals', {})
    gross_income = _d(totals.get('gross_income', 0))
    total_expenses = _d(totals.get('total_expenses', 0))
    net_income = _d(totals.get('net_income', 0))
    
    print(f"\nPROFIT & LOSS SUMMARY:")
    print(f"Gross Income:     KES {gross_income:>15,.2f}")
    print(f"Total Expenses:   KES {total_expenses:>15,.2f}")
    print(f"Net Income:       KES {net_income:>15,.2f}")
    
    # Verify calculation
    calculated_net = gross_income - total_expenses
    difference = abs(net_income - calculated_net)
    
    print(f"\nVERIFICATION:")
    print(f"Calculated Net (Income - Expenses): KES {calculated_net:>15,.2f}")
    print(f"Reported Net Income:                KES {net_income:>15,.2f}")
    print(f"Difference:                         KES {difference:>15,.2f}")
    
    is_correct = difference < Decimal('0.01')
    
    if is_correct:
        print("✅ Profit & Loss: CALCULATIONS CORRECT")
    else:
        print("⚠️  Profit & Loss: CALCULATION ERROR")
    
    # Show cash flow supplementary
    cash_flow = pl_data.get('cash_flow_supplementary', {})
    if cash_flow:
        print(f"\nCASH FLOW SUPPLEMENTARY (Informational):")
        print(f"Loans Disbursed:       KES {_d(cash_flow.get('loans_disbursed', 0)):>15,.2f}")
        print(f"Repayments Collected:  KES {_d(cash_flow.get('repayments_collected', 0)):>15,.2f}")
        print(f"Net Cash:              KES {_d(cash_flow.get('net_cash', 0)):>15,.2f}")
        print(f"Loan Count:            {cash_flow.get('loan_count', 0)}")
    
    return is_correct

def main():
    """Run all verifications"""
    print_header("COMPREHENSIVE FINANCIAL REPORTS VERIFICATION", "=", 100)
    print("Verifying ALL financial reports for mathematical accuracy")
    print("Reports: Chart of Accounts, Trial Balance, Income Statement, Balance Sheet,")
    print("         Loan Aging, SasaPay Reconciliation, Profit & Loss")
    print_header("", "=", 100)
    
    results = {}
    
    try:
        results['chart_of_accounts'] = verify_chart_of_accounts()
    except Exception as e:
        print(f"⚠️  Error verifying Chart of Accounts: {e}")
        results['chart_of_accounts'] = False
    
    try:
        results['trial_balance'] = verify_trial_balance()
    except Exception as e:
        print(f"⚠️  Error verifying Trial Balance: {e}")
        results['trial_balance'] = False
    
    try:
        results['income_statement'] = verify_income_statement()
    except Exception as e:
        print(f"⚠️  Error verifying Income Statement: {e}")
        results['income_statement'] = False
    
    try:
        results['balance_sheet'] = verify_balance_sheet()
    except Exception as e:
        print(f"⚠️  Error verifying Balance Sheet: {e}")
        results['balance_sheet'] = False
    
    try:
        results['loan_aging'] = verify_loan_aging()
    except Exception as e:
        print(f"⚠️  Error verifying Loan Aging: {e}")
        results['loan_aging'] = False
    
    try:
        results['sasapay_reconciliation'] = verify_sasapay_reconciliation()
    except Exception as e:
        print(f"⚠️  Error verifying SasaPay Reconciliation: {e}")
        results['sasapay_reconciliation'] = False
    
    try:
        results['profit_and_loss'] = verify_profit_and_loss()
    except Exception as e:
        print(f"⚠️  Error verifying Profit & Loss: {e}")
        results['profit_and_loss'] = False
    
    # Final summary
    print_header("FINAL VERIFICATION SUMMARY", "=", 100)
    print(f"\n{'Report':<35} {'Status':<20}")
    print("-" * 60)
    
    for report, is_correct in results.items():
        status = "✅ PASS" if is_correct else "⚠️  NEEDS ATTENTION"
        report_name = report.replace('_', ' ').title()
        print(f"{report_name:<35} {status:<20}")
    
    all_pass = all(results.values())
    
    print_header("", "=", 100)
    if all_pass:
        print("✅ ALL REPORTS: CALCULATIONS VERIFIED AND CORRECT")
    else:
        print("⚠️  SOME REPORTS NEED ATTENTION - See details above")
    print_header("", "=", 100)

if __name__ == '__main__':
    main()
