import os
import django
from decimal import Decimal

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

from loans.models import LoanProduct

# ============================================================
# GRAZURI HAVEN INVESTMENT LIMITED - CANONICAL LOAN PRODUCTS
# These are the two products that exist in the Grazuri database
# (product_id 2 and 3, gl_code 11002).
# ============================================================
grazuri_products_data = [
    {
        # product_id: 2 in Grazuri DB  |  accountType: 'B'
        'name': 'Biashara Loan',
        'product_type': 'biashara',
        'grazuri_account_type': 'B',
        'gl_code': '11002',
        'description': (
            'Business loan (Biashara) for Haven Grazuri Investment Limited clients. '
            'Designed for SMEs and business owners seeking working capital, inventory '
            'restocking, or business expansion financing.'
        ),
        # Amounts — align with Grazuri spec (min: 1,000 / max: 50,000)
        'min_amount': Decimal('1000.00'),
        'max_amount': Decimal('50000.00'),
        # Interest — 15% flat monthly rate (Grazuri requirement 3.2)
        'interest_rate': Decimal('15.00'),
        # Processing fee — one-time 2% upfront (Grazuri requirement 3.3)
        'processing_fee': Decimal('2.00'),
        # Penalty — 5% on outstanding for overdue loans
        'late_payment_penalty': Decimal('5.00'),
        'penalty_mode': 'auto',
        'penalty_frequency': 'monthly',
        # Duration — flexible within 1–12 months (Grazuri policy)
        'min_duration': 30,
        'max_duration': 365,
        'duration_months': 1,
        'available_durations': [],        # any duration within min–max
        # Repayment
        'available_repayment_methods': ['monthly'],
        # Eligibility
        'requires_guarantor': False,
        'requires_collateral': False,
        'minimum_income': Decimal('20000.00'),
        # Rollover
        'max_rollover_count': 2,
        'rollover_fee_percentage': Decimal('5.00'),
        'max_rollover_days': 30,
        'is_active': True,
    },
    {
        # product_id: 3 in Grazuri DB  |  accountType: 'P'
        'name': 'Log Book Loan',
        'product_type': 'logbook',
        'grazuri_account_type': 'P',
        'gl_code': '11002',
        'description': (
            'Secured loan against a motor vehicle log book (registration certificate). '
            'Haven Grazuri Investment Limited offers competitive rates for borrowers '
            'who own a registered vehicle and require larger financing amounts.'
        ),
        # Amounts — higher ceiling because collateral (log book) is required
        'min_amount': Decimal('5000.00'),
        'max_amount': Decimal('100000.00'),
        # Interest — 12% flat monthly rate
        'interest_rate': Decimal('12.00'),
        # Processing fee — one-time 3% upfront
        'processing_fee': Decimal('3.00'),
        # Penalty
        'late_payment_penalty': Decimal('5.00'),
        'penalty_mode': 'auto',
        'penalty_frequency': 'monthly',
        # Duration — 1–12 months flexible
        'min_duration': 30,
        'max_duration': 365,
        'duration_months': 3,
        'available_durations': [],        # any duration within min–max
        # Repayment
        'available_repayment_methods': ['monthly'],
        # Eligibility — log book loan requires collateral (vehicle)
        'requires_guarantor': False,
        'requires_collateral': True,
        'minimum_income': Decimal('30000.00'),
        # Rollover
        'max_rollover_count': 1,
        'rollover_fee_percentage': Decimal('5.00'),
        'max_rollover_days': 30,
        'is_active': True,
    },
]

# ============================================================
# LEGACY / INTERNAL PRODUCTS (kept for backward compatibility)
# ============================================================
legacy_products_data = [
    {
        'name': 'Boost',
        'product_type': 'boost',
        'gl_code': '',
        'grazuri_account_type': '',
        'description': 'Fast approval loan for urgent business needs. Perfect for inventory restocking or emergency expenses.',
        'min_amount': Decimal('5000.00'),
        'max_amount': Decimal('50000.00'),
        'interest_rate': Decimal('15.00'),
        'min_duration': 7,
        'max_duration': 30,
        'duration_months': 1,
        'processing_fee': Decimal('2.00'),
        'late_payment_penalty': Decimal('5.00'),
        'is_active': True,
        'requires_guarantor': False,
        'requires_collateral': False,
        'available_repayment_methods': ['daily', 'weekly', 'monthly'],
        'available_durations': [7, 14, 21, 30],
        'max_rollover_count': 2,
        'rollover_fee_percentage': Decimal('10.00'),
        'minimum_income': Decimal('20000.00'),
    },
    {
        'name': 'Boost Plus',
        'product_type': 'boost_plus',
        'gl_code': '',
        'grazuri_account_type': '',
        'description': 'Premium loan product with flexible terms and competitive rates. Best for established businesses with good credit history.',
        'min_amount': Decimal('50000.00'),
        'max_amount': Decimal('500000.00'),
        'interest_rate': Decimal('10.00'),
        'min_duration': 60,
        'max_duration': 180,
        'duration_months': 3,
        'processing_fee': Decimal('2.50'),
        'late_payment_penalty': Decimal('4.00'),
        'is_active': True,
        'requires_guarantor': True,
        'requires_collateral': True,
        'available_repayment_methods': ['monthly'],
        'available_durations': [60, 90, 120, 150, 180],
        'max_rollover_count': 1,
        'rollover_fee_percentage': Decimal('12.00'),
        'minimum_income': Decimal('80000.00'),
    },
    {
        'name': 'Mwamba',
        'product_type': 'mwamba',
        'gl_code': '',
        'grazuri_account_type': '',
        'description': 'Medium-term loan for business expansion and growth. Ideal for purchasing equipment or expanding operations.',
        'min_amount': Decimal('20000.00'),
        'max_amount': Decimal('200000.00'),
        'interest_rate': Decimal('12.00'),
        'min_duration': 30,
        'max_duration': 90,
        'duration_months': 2,
        'processing_fee': Decimal('3.00'),
        'late_payment_penalty': Decimal('5.00'),
        'is_active': True,
        'requires_guarantor': True,
        'requires_collateral': False,
        'available_repayment_methods': ['weekly', 'monthly'],
        'available_durations': [30, 45, 60, 75, 90],
        'max_rollover_count': 1,
        'rollover_fee_percentage': Decimal('15.00'),
        'minimum_income': Decimal('40000.00'),
    },
    {
        'name': 'Imara',
        'product_type': 'imara',
        'gl_code': '',
        'grazuri_account_type': '',
        'description': 'Small loan for micro-businesses and startups. No collateral required, quick approval process.',
        'min_amount': Decimal('1000.00'),
        'max_amount': Decimal('20000.00'),
        'interest_rate': Decimal('18.00'),
        'min_duration': 7,
        'max_duration': 30,
        'duration_months': 1,
        'processing_fee': Decimal('1.50'),
        'late_payment_penalty': Decimal('6.00'),
        'is_active': True,
        'requires_guarantor': False,
        'requires_collateral': False,
        'available_repayment_methods': ['daily', 'weekly'],
        'available_durations': [7, 14, 21, 30],
        'max_rollover_count': 3,
        'rollover_fee_percentage': Decimal('8.00'),
        'minimum_income': Decimal('15000.00'),
    },
]

all_products = grazuri_products_data + legacy_products_data

print("\n" + "=" * 80)
print("Creating / Updating Loan Products — Haven Grazuri Investment Limited")
print("=" * 80 + "\n")

created_count = 0
updated_count = 0
error_count = 0

for product_data in all_products:
    try:
        product_type = product_data['product_type']

        # Check if product already exists
        product, created = LoanProduct.objects.update_or_create(
            product_type=product_type,
            defaults=product_data
        )

        tag = "✓ Created" if created else "↻ Updated"
        label = "🏦 GRAZURI" if product_data.get('grazuri_account_type') else "       "
        if created:
            created_count += 1
        else:
            updated_count += 1
        print(
            f"{tag}: {label} {product.name:25} "
            f"| Rate: {product.interest_rate}% "
            f"| Range: KES {product.min_amount:,.0f} – {product.max_amount:,.0f}"
        )

    except Exception as e:
        error_count += 1
        print(f"✗ Error creating {product_data['name']}: {str(e)}")

print("\n" + "=" * 80)
print(f"Summary:")
print(f"  Created: {created_count} loan products")
print(f"  Updated: {updated_count} loan products")
print(f"  Errors:  {error_count} loan products")
print(f"  Total:   {created_count + updated_count} loan products")
print("=" * 80)

print("\n" + "=" * 80)
print("Loan Products Details:")
print("=" * 80 + "\n")

for product in LoanProduct.objects.filter(is_active=True).order_by('min_amount'):
    grazuri_badge = " 🏦 [GRAZURI]" if product.is_grazuri_product() else ""
    print(f"📦 {product.name} ({product.get_product_type_display()}){grazuri_badge}")
    print(f"   Description: {product.description}")
    print(f"   Amount Range: KES {product.min_amount:,.0f} - KES {product.max_amount:,.0f}")
    print(f"   Interest Rate: {product.interest_rate}% per month (flat/simple)")
    print(f"   Duration: {product.min_duration} - {product.max_duration} days")
    if product.available_durations:
        print(f"   Available Durations: {', '.join(map(str, product.available_durations))} days")
    else:
        print(f"   Available Durations: Any within {product.min_duration}–{product.max_duration} days")
    print(f"   Processing Fee: {product.processing_fee}% (one-time upfront)")
    print(f"   Late Payment Penalty: {product.late_payment_penalty}%")
    print(f"   Repayment Methods: {', '.join(product.available_repayment_methods)}")
    if product.minimum_income:
        print(f"   Minimum Income: KES {product.minimum_income:,.0f}")
    print(f"   Requires Guarantor: {'Yes' if product.requires_guarantor else 'No'}")
    print(f"   Requires Collateral: {'Yes' if product.requires_collateral else 'No'}")
    print(f"   Max Rollovers: {product.max_rollover_count}")
    print(f"   Rollover Fee: {product.rollover_fee_percentage}%")
    if product.gl_code:
        print(f"   GL Code: {product.gl_code}  |  Account Type: {product.grazuri_account_type}")
    print()

print("=" * 80)
print("✓ All loan products loaded successfully!")
print("=" * 80 + "\n")
