"""
Test script for client growth and portfolio reports
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from reports.client_report_service import ClientReportService
from users.models import CustomUser
from decimal import Decimal

def test_client_metrics():
    """Test client growth metrics calculation"""
    print("=" * 60)
    print("Testing Client Growth Metrics")
    print("=" * 60)
    
    # Get client metrics
    metrics = ClientReportService.get_client_metrics()
    
    print(f"\n✅ Total Clients: {metrics['total_clients']}")
    print(f"✅ New Clients This Month: {metrics['new_clients_this_month']}")
    print(f"✅ New Clients Last Month: {metrics['new_clients_last_month']}")
    print(f"✅ Growth Rate: {metrics['growth_rate']}%")
    print(f"✅ Clients with Loans: {metrics['clients_with_loans']}")
    print(f"✅ Loan Penetration Rate: {metrics['loan_penetration_rate']}%")
    print(f"✅ Total Outstanding: KES {metrics['total_outstanding']}")
    
    return metrics

def test_demographic_distribution():
    """Test demographic distribution"""
    print("\n" + "=" * 60)
    print("Testing Demographic Distribution")
    print("=" * 60)
    
    distribution = ClientReportService.get_demographic_distribution()
    
    print("\n📊 Gender Distribution:")
    for gender, count in distribution['gender'].items():
        print(f"  - {gender}: {count}")
    
    print("\n📊 Loan Status Distribution:")
    for status, count in distribution['loan_status'].items():
        print(f"  - {status}: {count}")
    
    return distribution

def test_growth_trends():
    """Test growth trends over time"""
    print("\n" + "=" * 60)
    print("Testing Growth Trends (Last 6 Months)")
    print("=" * 60)
    
    trends = ClientReportService.get_growth_trends(months=6)
    
    if trends:
        print("\n📈 Monthly Growth:")
        for trend in trends:
            print(f"  {trend['month']}: +{trend['new_clients']} (Total: {trend['cumulative_total']})")
    else:
        print("\n⚠️  No growth data available")
    
    return trends

def test_top_clients():
    """Test top clients by portfolio size"""
    print("\n" + "=" * 60)
    print("Testing Top Clients by Portfolio Size")
    print("=" * 60)
    
    top_clients = ClientReportService.get_top_clients_by_portfolio(limit=5)
    
    if top_clients:
        print("\n💰 Top 5 Clients:")
        for i, client in enumerate(top_clients, 1):
            print(f"\n  {i}. {client['name']}")
            print(f"     Phone: {client['phone_number']}")
            print(f"     Active Loans: {client['total_loans']}")
            print(f"     Total Disbursed: KES {client['total_disbursed']}")
            print(f"     Outstanding: KES {client['total_outstanding']}")
            print(f"     Member Since: {client['date_joined']}")
    else:
        print("\n⚠️  No client portfolio data available")
    
    return top_clients

def run_all_tests():
    """Run all tests"""
    print("\n" + "=" * 60)
    print("CLIENT GROWTH & PORTFOLIO REPORTS TEST")
    print("=" * 60)
    
    try:
        # Test 1: Client Metrics
        metrics = test_client_metrics()
        assert metrics['total_clients'] >= 0, "Total clients should be non-negative"
        assert metrics['growth_rate'] is not None, "Growth rate should be calculated"
        print("\n✅ Client metrics test PASSED")
        
        # Test 2: Demographic Distribution
        distribution = test_demographic_distribution()
        assert 'gender' in distribution, "Gender distribution should exist"
        assert 'loan_status' in distribution, "Loan status distribution should exist"
        print("\n✅ Demographic distribution test PASSED")
        
        # Test 3: Growth Trends
        trends = test_growth_trends()
        print("\n✅ Growth trends test PASSED")
        
        # Test 4: Top Clients
        top_clients = test_top_clients()
        print("\n✅ Top clients test PASSED")
        
        print("\n" + "=" * 60)
        print("ALL TESTS PASSED! ✅")
        print("=" * 60)
        
        print("\n📋 Summary:")
        print(f"  - Total Clients: {metrics['total_clients']}")
        print(f"  - New This Month: {metrics['new_clients_this_month']}")
        print(f"  - Growth Rate: {metrics['growth_rate']}%")
        print(f"  - Loan Penetration: {metrics['loan_penetration_rate']}%")
        print(f"  - Top Clients Found: {len(top_clients)}")
        print(f"  - Growth Months Tracked: {len(trends)}")
        
    except Exception as e:
        print(f"\n❌ TEST FAILED: {str(e)}")
        import traceback
        traceback.print_exc()
        return False
    
    return True

if __name__ == '__main__':
    success = run_all_tests()
    exit(0 if success else 1)
