"""
Accounting Integration Verification Script

This script verifies that the Chart of Accounts is properly integrated
with all loan transactions and reports.

Run with: python manage.py shell < verify_accounting_integration.py
Or: python verify_accounting_integration.py (if Django setup)
"""

import django
import os
import sys
from decimal import Decimal
from datetime import date, timedelta

# Setup Django if running as standalone script
if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()

def print_section(title):
    print(f"\n{'='*70}")
    print(f"  {title}")
    print(f"{'='*70}\n")

def check_accounting_models():
    """Check if accounting models are available and have data"""
    print_section("1. ACCOUNTING MODELS CHECK")
    
    try:
        from accounting.models import Account, JournalEntry, GeneralLedger
        print("✅ Accounting models imported successfully")
        
        # Check accounts
        account_count = Account.objects.count()
        active_accounts = Account.objects.filter(is_active=True).count()
        print(f"   📊 Total accounts: {account_count}")
        print(f"   ✓  Active accounts: {active_accounts}")
        
        # Check system accounts (using organizational codes)
        critical_accounts = [
            ('202001', 'Loan Portfolio'),
            ('202003', 'Cash - Main Branch'),
            ('202005', 'M-Pesa Account'),
            ('401001', 'Interest Income - Loans'),
            ('401002', 'Fee Income'),
        ]
        
        print(f"\n   System Accounts Status:")
        for code, name in critical_accounts:
            exists = Account.objects.filter(code=code, is_active=True).exists()
            status = "✅" if exists else "⚠️ "
            print(f"   {status} {code} - {name}")
        
        # Check journal entries
        entry_count = JournalEntry.objects.count()
        posted_entries = JournalEntry.objects.filter(status='posted').count()
        print(f"\n   📝 Total journal entries: {entry_count}")
        print(f"   ✓  Posted entries: {posted_entries}")
        
        # Check general ledger
        gl_count = GeneralLedger.objects.count()
        print(f"   📚 General ledger entries: {gl_count}")
        
        if gl_count > 0:
            print(f"\n   ✅ Accounting system has data - ACTIVE")
            return True
        else:
            print(f"\n   ⚠️  Accounting system has no GL data yet")
            return False
            
    except ImportError as e:
        print(f"❌ Failed to import accounting models: {e}")
        return False
    except Exception as e:
        print(f"❌ Error checking accounting models: {e}")
        return False

def check_integration_service():
    """Check if integration service is available"""
    print_section("2. INTEGRATION SERVICE CHECK")
    
    try:
        from accounting.services.integration_service import IntegrationService
        print("✅ IntegrationService imported successfully")
        
        service = IntegrationService()
        print("✅ IntegrationService instantiated")
        
        # Check methods
        methods = [
            'create_loan_disbursement_entry',
            'create_loan_repayment_entry',
            'create_processing_fee_entry',
            'create_interest_accrual_entry',
            'create_expense_entry',
        ]
        
        print("\n   Available Methods:")
        for method in methods:
            has_method = hasattr(service, method)
            status = "✅" if has_method else "❌"
            print(f"   {status} {method}")
        
        return True
        
    except ImportError as e:
        print(f"❌ Failed to import IntegrationService: {e}")
        return False
    except Exception as e:
        print(f"❌ Error checking IntegrationService: {e}")
        return False

def check_signal_handlers():
    """Check if signal handlers are registered"""
    print_section("3. SIGNAL HANDLERS CHECK")
    
    try:
        import accounting.signals
        print("✅ Signal module imported successfully")
        
        # Check signal receivers
        from django.db.models.signals import post_save
        from loans.models import Loan, Repayment
        
        # Check if signals are connected
        loan_receivers = post_save._live_receivers(Loan)
        print(f"\n   Loan post_save receivers: {len(loan_receivers)}")
        
        repayment_receivers = post_save._live_receivers(Repayment)
        print(f"   Repayment post_save receivers: {len(repayment_receivers)}")
        
        try:
            from expenses.models import Expense
            expense_receivers = post_save._live_receivers(Expense)
            print(f"   Expense post_save receivers: {len(expense_receivers)}")
        except ImportError:
            print(f"   ⚠️  Expense model not available")
        
        print(f"\n   ✅ Signal handlers are registered")
        return True
        
    except Exception as e:
        print(f"❌ Error checking signal handlers: {e}")
        return False

def check_recent_journal_entries():
    """Check recent loan journal entries"""
    print_section("4. RECENT JOURNAL ENTRIES CHECK")
    
    try:
        from accounting.models import JournalEntry
        from loans.models import Loan
        
        # Get recent active loans
        recent_loans = Loan.objects.filter(status='active').order_by('-disbursement_date')[:10]
        
        if not recent_loans:
            print("ℹ️  No active loans found")
            return True
        
        print(f"Checking last {recent_loans.count()} active loans:\n")
        
        for loan in recent_loans:
            entries = JournalEntry.objects.filter(loan=loan)
            entry_count = entries.count()
            
            if entry_count > 0:
                print(f"✅ Loan {loan.loan_number}: {entry_count} journal entry/entries")
                for entry in entries:
                    print(f"   - {entry.reference_number} ({entry.status})")
            else:
                print(f"⚠️  Loan {loan.loan_number}: No journal entries")
        
        return True
        
    except Exception as e:
        print(f"❌ Error checking journal entries: {e}")
        return False

def check_report_integration():
    """Check if reports use accounting system"""
    print_section("5. REPORT INTEGRATION CHECK")
    
    try:
        from reports.financial_reports_service import get_profit_and_loss, get_financial_statements
        
        end_date = date.today()
        start_date = end_date - timedelta(days=30)
        
        print("Testing Profit & Loss Report...")
        pl_report = get_profit_and_loss(start_date, end_date)
        pl_source = pl_report.get('source', 'unknown')
        
        print(f"   Data source: {pl_source}")
        print(f"   Total income: KES {pl_report['income']['total']:,.2f}")
        print(f"   Total expenses: KES {pl_report['expenses']['total_operational']:,.2f}")
        print(f"   Net profit: KES {pl_report['net_profit']:,.2f}")
        
        if pl_source == 'accounting_system':
            print(f"   ✅ Using accounting system data")
        else:
            print(f"   ℹ️  Using direct calculation (fallback)")
        
        print("\nTesting Financial Statements...")
        fs_report = get_financial_statements(as_of_date=end_date)
        fs_source = fs_report.get('source', 'unknown')
        
        print(f"   Data source: {fs_source}")
        
        if 'assets' in fs_report:
            if 'total_assets' in fs_report['assets']:
                print(f"   Total assets: KES {fs_report['assets']['total_assets']:,.2f}")
            else:
                print(f"   Loan portfolio: KES {fs_report['assets']['active_loan_portfolio_gross']:,.2f}")
        
        if fs_source == 'accounting_system':
            print(f"   ✅ Using accounting system data")
        else:
            print(f"   ℹ️  Using direct calculation (fallback)")
        
        return True
        
    except Exception as e:
        print(f"❌ Error checking report integration: {e}")
        import traceback
        traceback.print_exc()
        return False

def print_summary(results):
    """Print overall summary"""
    print_section("INTEGRATION VERIFICATION SUMMARY")
    
    all_passed = all(results.values())
    
    print("Check Results:")
    for check, passed in results.items():
        status = "✅ PASS" if passed else "❌ FAIL"
        print(f"   {status}: {check}")
    
    print()
    if all_passed:
        print("🎉 ALL CHECKS PASSED!")
        print("\nThe Chart of Accounts is properly integrated with the system.")
        print("New loan transactions will automatically create journal entries.")
        print("Reports will use accounting system data when available.")
    else:
        print("⚠️  SOME CHECKS FAILED")
        print("\nPlease review the errors above and:")
        print("1. Ensure accounting app is in INSTALLED_APPS")
        print("2. Run migrations: python manage.py migrate accounting")
        print("3. Load initial accounts: python manage.py load_initial_accounts")
        print("4. Check that signals are registered in accounting/apps.py")
    
    print()

def main():
    """Run all verification checks"""
    print("\n" + "="*70)
    print("  ACCOUNTING INTEGRATION VERIFICATION")
    print("  Verifying Chart of Accounts → Reports Integration")
    print("="*70)
    
    results = {
        'Accounting Models': check_accounting_models(),
        'Integration Service': check_integration_service(),
        'Signal Handlers': check_signal_handlers(),
        'Journal Entries': check_recent_journal_entries(),
        'Report Integration': check_report_integration(),
    }
    
    print_summary(results)

if __name__ == '__main__':
    main()
