#!/usr/bin/env python
"""
Test script for Accounting PDF Report Generation
Validates that PDF reports can be generated successfully
"""

import os
import sys
import django

# Setup Django environment
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from datetime import date, timedelta
from decimal import Decimal
from accounting.pdf_reports import AccountingPDFGenerator


def test_chart_of_accounts_pdf():
    """Test Chart of Accounts PDF generation"""
    print("\n[1/3] Testing Chart of Accounts PDF...")
    
    # Sample data
    accounts_by_type = {
        'asset': [
            {'code': '101001', 'name': 'Cash and Bank Balances', 'subtype': 'current_asset', 'balance': Decimal('150000.00'), 'description': 'Main operating cash'},
            {'code': '101002', 'name': 'Loan Portfolio', 'subtype': 'current_asset', 'balance': Decimal('5000000.00'), 'description': 'Outstanding loans to clients'},
        ],
        'liability': [
            {'code': '201001', 'name': 'Client Savings Deposits', 'subtype': 'current_liability', 'balance': Decimal('250000.00'), 'description': 'Client deposits'},
        ],
        'equity': [
            {'code': '301001', 'name': 'Share Capital', 'subtype': 'equity', 'balance': Decimal('1000000.00'), 'description': 'Paid-up share capital'},
        ],
        'income': [
            {'code': '401001', 'name': 'Interest Income', 'subtype': 'operating_income', 'balance': Decimal('750000.00'), 'description': 'Interest earned on loans'},
            {'code': '401002', 'name': 'Processing Fees', 'subtype': 'operating_income', 'balance': Decimal('125000.00'), 'description': 'Loan processing fees'},
        ],
        'expense': [
            {'code': '501001', 'name': 'Staff Salaries', 'subtype': 'operating_expense', 'balance': Decimal('180000.00'), 'description': 'Employee salaries'},
            {'code': '501002', 'name': 'Office Rent', 'subtype': 'operating_expense', 'balance': Decimal('45000.00'), 'description': 'Monthly office rent'},
        ]
    }
    
    try:
        pdf_generator = AccountingPDFGenerator()
        pdf_buffer = pdf_generator.generate_chart_of_accounts_pdf(
            accounts_by_type=accounts_by_type,
            as_of_date=date.today(),
            include_balances=True
        )
        
        # Save test PDF
        test_filename = f"test_chart_of_accounts_{date.today()}.pdf"
        with open(test_filename, 'wb') as f:
            f.write(pdf_buffer.read())
        
        file_size = os.path.getsize(test_filename)
        print(f"   ✅ SUCCESS: Chart of Accounts PDF generated ({file_size:,} bytes)")
        print(f"   📄 File saved: {test_filename}")
        return True
        
    except Exception as e:
        print(f"   ❌ FAILED: {str(e)}")
        return False


def test_account_ledger_pdf():
    """Test Account Ledger PDF generation"""
    print("\n[2/3] Testing Account Ledger PDF...")
    
    # Sample account
    account = {
        'code': '101001',
        'name': 'Cash and Bank Balances',
        'type': 'asset',
        'subtype': 'current_asset'
    }
    
    # Sample transactions
    today = date.today()
    transactions = [
        {
            'date': today - timedelta(days=30),
            'description': 'Opening Balance',
            'debit': Decimal('100000.00'),
            'credit': None,
            'balance': Decimal('100000.00')
        },
        {
            'date': today - timedelta(days=25),
            'description': 'Loan disbursement to client',
            'debit': None,
            'credit': Decimal('50000.00'),
            'balance': Decimal('50000.00')
        },
        {
            'date': today - timedelta(days=20),
            'description': 'Loan repayment received',
            'debit': Decimal('15000.00'),
            'credit': None,
            'balance': Decimal('65000.00')
        },
        {
            'date': today - timedelta(days=15),
            'description': 'Processing fee income',
            'debit': Decimal('5000.00'),
            'credit': None,
            'balance': Decimal('70000.00')
        },
        {
            'date': today - timedelta(days=10),
            'description': 'Office rent payment',
            'debit': None,
            'credit': Decimal('25000.00'),
            'balance': Decimal('45000.00')
        },
    ]
    
    try:
        pdf_generator = AccountingPDFGenerator()
        pdf_buffer = pdf_generator.generate_account_ledger_pdf(
            account=account,
            transactions=transactions,
            start_date=today - timedelta(days=30),
            end_date=today
        )
        
        # Save test PDF
        test_filename = f"test_account_ledger_{account['code']}_{date.today()}.pdf"
        with open(test_filename, 'wb') as f:
            f.write(pdf_buffer.read())
        
        file_size = os.path.getsize(test_filename)
        print(f"   ✅ SUCCESS: Account Ledger PDF generated ({file_size:,} bytes)")
        print(f"   📄 File saved: {test_filename}")
        return True
        
    except Exception as e:
        print(f"   ❌ FAILED: {str(e)}")
        return False


def test_trial_balance_pdf():
    """Test Trial Balance PDF generation"""
    print("\n[3/3] Testing Trial Balance PDF...")
    
    # Sample trial balance data
    trial_balance_data = {
        'report_date': date.today(),
        'branch': 'All Branches',
        'accounts': [
            {
                'code': '101001',
                'name': 'Cash and Bank Balances',
                'debit_balance': Decimal('150000.00'),
                'credit_balance': Decimal('0.00')
            },
            {
                'code': '101002',
                'name': 'Loan Portfolio',
                'debit_balance': Decimal('5000000.00'),
                'credit_balance': Decimal('0.00')
            },
            {
                'code': '201001',
                'name': 'Client Savings Deposits',
                'debit_balance': Decimal('0.00'),
                'credit_balance': Decimal('250000.00')
            },
            {
                'code': '301001',
                'name': 'Share Capital',
                'debit_balance': Decimal('0.00'),
                'credit_balance': Decimal('1000000.00')
            },
            {
                'code': '401001',
                'name': 'Interest Income',
                'debit_balance': Decimal('0.00'),
                'credit_balance': Decimal('750000.00')
            },
            {
                'code': '501001',
                'name': 'Staff Salaries',
                'debit_balance': Decimal('180000.00'),
                'credit_balance': Decimal('0.00')
            },
        ],
        'total_debits': Decimal('5330000.00'),
        'total_credits': Decimal('2000000.00')
    }
    
    try:
        pdf_generator = AccountingPDFGenerator()
        pdf_buffer = pdf_generator.generate_trial_balance_pdf(
            trial_balance_data=trial_balance_data,
            as_of_date=date.today()
        )
        
        # Save test PDF
        test_filename = f"test_trial_balance_{date.today()}.pdf"
        with open(test_filename, 'wb') as f:
            f.write(pdf_buffer.read())
        
        file_size = os.path.getsize(test_filename)
        print(f"   ✅ SUCCESS: Trial Balance PDF generated ({file_size:,} bytes)")
        print(f"   📄 File saved: {test_filename}")
        return True
        
    except Exception as e:
        print(f"   ❌ FAILED: {str(e)}")
        return False


def main():
    """Run all PDF generation tests"""
    print("\n" + "="*70)
    print("ACCOUNTING PDF REPORTS - TEST SUITE")
    print("Haven Grazuri Investment Limited")
    print("="*70)
    
    results = []
    
    # Run tests
    results.append(test_chart_of_accounts_pdf())
    results.append(test_account_ledger_pdf())
    results.append(test_trial_balance_pdf())
    
    # Summary
    print("\n" + "="*70)
    print("TEST SUMMARY")
    print("="*70)
    
    passed = sum(results)
    total = len(results)
    
    print(f"\nTests Passed: {passed}/{total}")
    
    if passed == total:
        print("\n🎉 ALL TESTS PASSED!")
        print("\n✅ PDF generation system is working correctly")
        print("\nGenerated test PDFs:")
        print("  • test_chart_of_accounts_*.pdf")
        print("  • test_account_ledger_*.pdf")
        print("  • test_trial_balance_*.pdf")
        print("\nYou can now access PDF reports through the web interface:")
        print("  1. Navigate to Reports → Financial Reports → Chart of Accounts")
        print("  2. Click 'Download PDF' or 'Trial Balance PDF' buttons")
        print("  3. Click any account code to view ledger and export to PDF")
    else:
        print("\n⚠️ SOME TESTS FAILED")
        print("Please check the error messages above for details")
    
    print("\n" + "="*70 + "\n")
    
    return 0 if passed == total else 1


if __name__ == '__main__':
    sys.exit(main())
