"""
Setup script for penalty system
Run this after migrations to configure loan products with penalty settings
"""
import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import LoanProduct
from decimal import Decimal


def setup_penalty_system():
    """Configure penalty settings for all loan products"""
    
    print("🔧 Setting up penalty system...")
    print("-" * 50)
    
    # Default penalty configurations for each product type
    penalty_configs = {
        'boost': {
            'penalty_mode': 'auto',
            'penalty_frequency': 'daily',
            'late_payment_penalty': Decimal('2.0'),  # 2% daily
            'description': 'Automatic daily penalties'
        },
        'boost_plus': {
            'penalty_mode': 'auto',
            'penalty_frequency': 'daily',
            'late_payment_penalty': Decimal('2.5'),  # 2.5% daily
            'description': 'Automatic daily penalties'
        },
        'mwamba': {
            'penalty_mode': 'manual',
            'penalty_frequency': 'weekly',
            'late_payment_penalty': Decimal('5.0'),  # 5% weekly
            'description': 'Manual weekly penalties'
        },
        'imara': {
            'penalty_mode': 'auto',
            'penalty_frequency': 'monthly',
            'late_payment_penalty': Decimal('10.0'),  # 10% monthly
            'description': 'Automatic monthly penalties'
        }
    }
    
    updated_count = 0
    
    for product in LoanProduct.objects.all():
        product_type = product.product_type
        
        if product_type in penalty_configs:
            config = penalty_configs[product_type]
            
            # Update penalty settings
            product.penalty_mode = config['penalty_mode']
            product.penalty_frequency = config['penalty_frequency']
            product.late_payment_penalty = config['late_payment_penalty']
            product.save()
            
            print(f"✓ Updated {product.name} ({product_type}):")
            print(f"  - Mode: {config['penalty_mode']}")
            print(f"  - Frequency: {config['penalty_frequency']}")
            print(f"  - Rate: {config['late_payment_penalty']}%")
            print(f"  - {config['description']}")
            print()
            
            updated_count += 1
        else:
            print(f"⚠️  Skipped {product.name} - unknown product type: {product_type}")
    
    print("-" * 50)
    print(f"✅ Setup complete! Updated {updated_count} loan products.")
    print()
    print("Next steps:")
    print("1. Run migrations: python manage.py migrate")
    print("2. Install Celery: pip install celery redis")
    print("3. Start Redis: redis-server (or docker run -d -p 6379:6379 redis)")
    print("4. Start Celery worker: celery -A branch_system worker -l info")
    print("5. Start Celery beat: celery -A branch_system beat -l info")
    print()
    print("To test automatic penalties:")
    print("  python manage.py shell")
    print("  >>> from loans.tasks import apply_automatic_penalties")
    print("  >>> apply_automatic_penalties()")
    print()
    print("Or use the management command:")
    print("  python manage.py apply_penalties --dry-run")


if __name__ == '__main__':
    try:
        setup_penalty_system()
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()
