#!/usr/bin/env python
"""
Script to set up the two Grazuri Haven Investment Limited loan products:
1. Biashara Loan (Business Loan) - Type 'B'
2. Log Book Loan (Personal/Asset-backed Loan) - Type 'P'

This script creates or updates these products in the database with proper configuration.
"""
import os
import django

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

from loans.models import LoanProduct
from decimal import Decimal
import uuid


def setup_biashara_loan():
    """
    Set up Biashara Loan (Business Loan)
    Product Type: 'B' (Business)
    GL Code: 11002
    """
    print("\n" + "=" * 80)
    print("SETTING UP BIASHARA LOAN (BUSINESS LOAN)")
    print("=" * 80)
    
    # Check if product already exists
    existing = LoanProduct.objects.filter(product_type='biashara').first()
    
    product_data = {
        'name': 'Biashara Loan',
        'product_type': 'biashara',
        'description': 'Business loan for entrepreneurs and SMEs. Flexible terms with competitive rates for business growth and working capital.',
        'gl_code': '11002',
        'grazuri_account_type': 'B',
        
        # Loan amounts (KES)
        'min_amount': Decimal('5000.00'),
        'max_amount': Decimal('500000.00'),
        
        # Interest and fees (percentages)
        'interest_rate': Decimal('15.00'),  # 15% monthly
        'processing_fee': Decimal('5.00'),  # 5% one-time
        'late_payment_penalty': Decimal('5.00'),  # 5% penalty
        'penalty_mode': 'auto',
        'penalty_frequency': 'daily',
        
        # Terms (days)
        'duration_months': 1,
        'min_duration': 30,  # 1 month minimum
        'max_duration': 365,  # 12 months maximum
        'available_durations': [],  # Empty = flexible duration within min/max
        
        # Repayment methods
        'available_repayment_methods': ['daily', 'weekly', 'monthly'],
        
        # Requirements
        'requires_guarantor': False,
        'requires_collateral': False,
        'minimum_income': Decimal('10000.00'),
        
        # Rollover settings
        'rollover_fee_percentage': Decimal('10.00'),
        'max_rollover_count': 3,
        'max_rollover_days': 30,
        
        # Status
        'is_active': True,
    }
    
    if existing:
        print(f"\n✓ Found existing Biashara Loan product (ID: {existing.id})")
        print("  Updating with new configuration...")
        
        for key, value in product_data.items():
            setattr(existing, key, value)
        existing.save()
        
        print(f"✓ Updated Biashara Loan product")
        product = existing
    else:
        print("\n✓ Creating new Biashara Loan product...")
        product = LoanProduct.objects.create(**product_data)
        print(f"✓ Created Biashara Loan product (ID: {product.id})")
    
    # Display product details
    print("\nBiashara Loan Configuration:")
    print(f"  Product Type: {product.product_type}")
    print(f"  Grazuri Account Type: {product.grazuri_account_type}")
    print(f"  GL Code: {product.gl_code}")
    print(f"  Amount Range: KES {product.min_amount:,.2f} - {product.max_amount:,.2f}")
    print(f"  Interest Rate: {product.interest_rate}% monthly")
    print(f"  Processing Fee: {product.processing_fee}% one-time")
    print(f"  Duration: {product.min_duration}-{product.max_duration} days (flexible)")
    print(f"  Repayment Methods: {', '.join(product.available_repayment_methods)}")
    print(f"  Requires Guarantor: {product.requires_guarantor}")
    print(f"  Requires Collateral: {product.requires_collateral}")
    
    return product


def setup_logbook_loan():
    """
    Set up Log Book Loan (Personal/Asset-backed Loan)
    Product Type: 'P' (Personal)
    GL Code: 11002
    """
    print("\n" + "=" * 80)
    print("SETTING UP LOG BOOK LOAN (PERSONAL/ASSET-BACKED LOAN)")
    print("=" * 80)
    
    # Check if product already exists
    existing = LoanProduct.objects.filter(product_type='logbook').first()
    
    product_data = {
        'name': 'Log Book Loan',
        'product_type': 'logbook',
        'description': 'Asset-backed loan secured by vehicle logbook. Quick approval with competitive rates for personal and business needs.',
        'gl_code': '11002',
        'grazuri_account_type': 'P',
        
        # Loan amounts (KES)
        'min_amount': Decimal('10000.00'),
        'max_amount': Decimal('1000000.00'),
        
        # Interest and fees (percentages)
        'interest_rate': Decimal('12.00'),  # 12% monthly (lower than Biashara due to collateral)
        'processing_fee': Decimal('4.00'),  # 4% one-time (lower due to secured nature)
        'late_payment_penalty': Decimal('5.00'),  # 5% penalty
        'penalty_mode': 'auto',
        'penalty_frequency': 'daily',
        
        # Terms (days)
        'duration_months': 1,
        'min_duration': 30,  # 1 month minimum
        'max_duration': 365,  # 12 months maximum
        'available_durations': [],  # Empty = flexible duration within min/max
        
        # Repayment methods
        'available_repayment_methods': ['daily', 'weekly', 'monthly'],
        
        # Requirements
        'requires_guarantor': False,
        'requires_collateral': True,  # Requires vehicle logbook
        'minimum_income': Decimal('15000.00'),
        
        # Rollover settings
        'rollover_fee_percentage': Decimal('8.00'),  # Lower rollover fee due to collateral
        'max_rollover_count': 3,
        'max_rollover_days': 30,
        
        # Status
        'is_active': True,
    }
    
    if existing:
        print(f"\n✓ Found existing Log Book Loan product (ID: {existing.id})")
        print("  Updating with new configuration...")
        
        for key, value in product_data.items():
            setattr(existing, key, value)
        existing.save()
        
        print(f"✓ Updated Log Book Loan product")
        product = existing
    else:
        print("\n✓ Creating new Log Book Loan product...")
        product = LoanProduct.objects.create(**product_data)
        print(f"✓ Created Log Book Loan product (ID: {product.id})")
    
    # Display product details
    print("\nLog Book Loan Configuration:")
    print(f"  Product Type: {product.product_type}")
    print(f"  Grazuri Account Type: {product.grazuri_account_type}")
    print(f"  GL Code: {product.gl_code}")
    print(f"  Amount Range: KES {product.min_amount:,.2f} - {product.max_amount:,.2f}")
    print(f"  Interest Rate: {product.interest_rate}% monthly")
    print(f"  Processing Fee: {product.processing_fee}% one-time")
    print(f"  Duration: {product.min_duration}-{product.max_duration} days (flexible)")
    print(f"  Repayment Methods: {', '.join(product.available_repayment_methods)}")
    print(f"  Requires Guarantor: {product.requires_guarantor}")
    print(f"  Requires Collateral: {product.requires_collateral}")
    
    return product


def test_loan_calculations():
    """Test loan calculations for both products"""
    print("\n" + "=" * 80)
    print("TESTING LOAN CALCULATIONS")
    print("=" * 80)
    
    biashara = LoanProduct.objects.filter(product_type='biashara').first()
    logbook = LoanProduct.objects.filter(product_type='logbook').first()
    
    if not biashara or not logbook:
        print("✗ Products not found. Cannot test calculations.")
        return False
    
    # Test Biashara Loan calculations
    print("\n--- Biashara Loan Test ---")
    test_amount = Decimal('50000.00')
    test_duration = 90  # 3 months
    
    interest = biashara.calculate_interest_from_days(test_amount, test_duration)
    fee = biashara.calculate_processing_fee(test_amount)
    total = biashara.calculate_total_loan_amount(test_amount, test_duration)
    
    print(f"Principal: KES {test_amount:,.2f}")
    print(f"Duration: {test_duration} days (3 months)")
    print(f"Interest (15% × 3 months): KES {interest:,.2f}")
    print(f"Processing Fee (5% one-time): KES {fee:,.2f}")
    print(f"Total Repayment: KES {total:,.2f}")
    
    # Verify calculation
    expected_interest = test_amount * Decimal('0.15') * Decimal('3')  # 15% × 3 months
    expected_fee = test_amount * Decimal('0.05')  # 5% one-time
    expected_total = test_amount + expected_interest + expected_fee
    
    if interest == expected_interest and fee == expected_fee and total == expected_total:
        print("✓ Biashara Loan calculations correct")
    else:
        print("✗ Biashara Loan calculations incorrect")
        return False
    
    # Test Log Book Loan calculations
    print("\n--- Log Book Loan Test ---")
    test_amount = Decimal('100000.00')
    test_duration = 180  # 6 months
    
    interest = logbook.calculate_interest_from_days(test_amount, test_duration)
    fee = logbook.calculate_processing_fee(test_amount)
    total = logbook.calculate_total_loan_amount(test_amount, test_duration)
    
    print(f"Principal: KES {test_amount:,.2f}")
    print(f"Duration: {test_duration} days (6 months)")
    print(f"Interest (12% × 6 months): KES {interest:,.2f}")
    print(f"Processing Fee (4% one-time): KES {fee:,.2f}")
    print(f"Total Repayment: KES {total:,.2f}")
    
    # Verify calculation
    expected_interest = test_amount * Decimal('0.12') * Decimal('6')  # 12% × 6 months
    expected_fee = test_amount * Decimal('0.04')  # 4% one-time
    expected_total = test_amount + expected_interest + expected_fee
    
    if interest == expected_interest and fee == expected_fee and total == expected_total:
        print("✓ Log Book Loan calculations correct")
    else:
        print("✗ Log Book Loan calculations incorrect")
        return False
    
    print("\n✓ All loan calculations verified successfully")
    return True


def deactivate_old_products():
    """Deactivate old HAVEN GRAZURI INVESTMENT LIMITEDproducts"""
    print("\n" + "=" * 80)
    print("DEACTIVATING OLD PRODUCTS")
    print("=" * 80)
    
    old_product_types = ['boost', 'boost_plus', 'mwamba', 'imara']
    deactivated_count = 0
    
    for product_type in old_product_types:
        products = LoanProduct.objects.filter(product_type=product_type, is_active=True)
        count = products.count()
        
        if count > 0:
            products.update(is_active=False)
            print(f"✓ Deactivated {count} {product_type} product(s)")
            deactivated_count += count
    
    if deactivated_count == 0:
        print("✓ No old products to deactivate")
    else:
        print(f"\n✓ Total deactivated: {deactivated_count} product(s)")
    
    return deactivated_count


def generate_summary():
    """Generate summary of all loan products"""
    print("\n" + "=" * 80)
    print("LOAN PRODUCTS SUMMARY")
    print("=" * 80)
    
    all_products = LoanProduct.objects.all().order_by('-is_active', 'name')
    
    print(f"\nTotal Products: {all_products.count()}")
    print(f"Active Products: {all_products.filter(is_active=True).count()}")
    print(f"Inactive Products: {all_products.filter(is_active=False).count()}")
    
    print("\n--- Active Grazuri Products ---")
    grazuri_products = all_products.filter(product_type__in=['biashara', 'logbook'], is_active=True)
    
    for product in grazuri_products:
        print(f"\n{product.name} ({product.grazuri_account_type})")
        print(f"  Type: {product.product_type}")
        print(f"  GL Code: {product.gl_code}")
        print(f"  Amount: KES {product.min_amount:,.2f} - {product.max_amount:,.2f}")
        print(f"  Interest: {product.interest_rate}% monthly")
        print(f"  Processing Fee: {product.processing_fee}%")
        print(f"  Duration: {product.min_duration}-{product.max_duration} days")
    
    print("\n--- Inactive Legacy Products ---")
    legacy_products = all_products.filter(is_active=False)
    
    if legacy_products.exists():
        for product in legacy_products:
            print(f"  • {product.name} ({product.product_type}) - INACTIVE")
    else:
        print("  None")


def main():
    """Main execution function"""
    print("\n" + "=" * 80)
    print("HAVEN GRAZURI INVESTMENT LIMITED")
    print("LOAN PRODUCTS SETUP")
    print("=" * 80)
    
    try:
        # Set up the two Grazuri products
        biashara = setup_biashara_loan()
        logbook = setup_logbook_loan()
        
        # Test calculations
        calculations_ok = test_loan_calculations()
        
        # Deactivate old products
        deactivate_old_products()
        
        # Generate summary
        generate_summary()
        
        print("\n" + "=" * 80)
        if calculations_ok:
            print("✓ LOAN PRODUCTS SETUP COMPLETED SUCCESSFULLY")
        else:
            print("⚠ LOAN PRODUCTS SETUP COMPLETED WITH WARNINGS")
        print("=" * 80)
        
        print("\nNext Steps:")
        print("  1. Review the loan products in Django admin")
        print("  2. Test loan application workflow with both products")
        print("  3. Update any frontend forms to show only Grazuri products")
        print("  4. Run migrations if any model changes were made")
        
        return 0 if calculations_ok else 1
        
    except Exception as e:
        print(f"\n✗ ERROR: {str(e)}")
        import traceback
        traceback.print_exc()
        return 1


if __name__ == '__main__':
    exit(main())
