import os
import django
import sys

# Set up Django environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from utils.models import SystemSetting
from loans.models import LoanProduct
from decimal import Decimal

def fix_loan_settings():
    print("\n" + "="*60)
    print("FIXING LOAN PRODUCT SETTINGS")
    print("="*60)
    
    # 1. Set boost_plus_interest_rate to 20%
    try:
        setting, created = SystemSetting.objects.update_or_create(
            key='boost_plus_interest_rate',
            defaults={
                'value': '20.0',
                'category': 'loan',
                'description': 'Monthly interest rate for Boost Plus loans (percentage)',
                'is_public': True
            }
        )
        status = "Created" if created else "Updated"
        print(f"✓ {status} boost_plus_interest_rate: 20%")
    except Exception as e:
        print(f"✗ Failed to set boost_plus_interest_rate: {str(e)}")
    
    # 2. Set boost_plus_processing_fee to 2%
    try:
        setting, created = SystemSetting.objects.update_or_create(
            key='boost_plus_processing_fee',
            defaults={
                'value': '2.0',
                'category': 'loan',
                'description': 'Processing fee for Boost Plus loans (percentage)',
                'is_public': True
            }
        )
        status = "Created" if created else "Updated"
        print(f"✓ {status} boost_plus_processing_fee: 2%")
    except Exception as e:
        print(f"✗ Failed to set boost_plus_processing_fee: {str(e)}")
    
    # 3. Fix late payment penalties for all loan products
    product_types = ['boost', 'boost_plus', 'mwamba', 'imara']
    penalty_rates = {
        'boost': 5.0,
        'boost_plus': 5.0,
        'mwamba': 5.0,
        'imara': 3.0
    }
    
    for product_type in product_types:
        penalty_key = f"{product_type}_late_payment_penalty"
        penalty_rate = penalty_rates.get(product_type, 5.0)
        
        try:
            setting, created = SystemSetting.objects.update_or_create(
                key=penalty_key,
                defaults={
                    'value': str(penalty_rate),
                    'category': 'loan',
                    'description': f'Monthly penalty rate for {product_type} loans (percentage)',
                    'is_public': True
                }
            )
            status = "Created" if created else "Updated"
            print(f"✓ {status} {penalty_key}: {penalty_rate}%")
        except Exception as e:
            print(f"✗ Failed to set {penalty_key}: {str(e)}")
    
    # 4. Set boost_plus_min_amount and boost_plus_max_amount
    try:
        setting, created = SystemSetting.objects.update_or_create(
            key='boost_plus_min_amount',
            defaults={
                'value': '5000',  # Default minimum amount for Boost Plus loans
                'category': 'loan',
                'description': 'Minimum loan amount for Boost Plus loans',
                'is_public': True
            }
        )
        status = "Created" if created else "Updated"
        print(f"✓ {status} boost_plus_min_amount: 5000")
    except Exception as e:
        print(f"✗ Failed to set boost_plus_min_amount: {str(e)}")
    
    try:
        setting, created = SystemSetting.objects.update_or_create(
            key='boost_plus_max_amount',
            defaults={
                'value': '50000',  # Default maximum amount for Boost Plus loans
                'category': 'loan',
                'description': 'Maximum loan amount for Boost Plus loans',
                'is_public': True
            }
        )
        status = "Created" if created else "Updated"
        print(f"✓ {status} boost_plus_max_amount: 50000")
    except Exception as e:
        print(f"✗ Failed to set boost_plus_max_amount: {str(e)}")
    
    # 5. Set system feature flags
    system_settings = [
        {
            'key': 'enable_email_reports',
            'value': 'True',
            'category': 'system',
            'description': 'Enable automated email reports',
            'is_public': False
        },
        {
            'key': 'track_customer_behavior',
            'value': 'True',
            'category': 'system',
            'description': 'Enable customer behavior tracking for analytics',
            'is_public': False
        },
        {
            'key': 'enable_advanced_analytics',
            'value': 'True',
            'category': 'system',
            'description': 'Enable advanced analytics features',
            'is_public': False
        }
    ]
    
    # Add Imara loan duration settings
    system_settings.extend([
        {
            'key': 'imara_min_duration',
            'value': '30',
            'category': 'loan',
            'description': 'Minimum duration in days for Imara loans',
            'is_public': True
        },
        {
            'key': 'imara_max_duration',
            'value': '365',
            'category': 'loan',
            'description': 'Maximum duration in days for Imara loans',
            'is_public': True
        },
        {
            'key': 'imara_default_duration',
            'value': '90',
            'category': 'loan',
            'description': 'Default duration in days for Imara loans',
            'is_public': True
        }
    ])
    for setting_data in system_settings:
        try:
            setting, created = SystemSetting.objects.update_or_create(
                key=setting_data['key'],
                defaults={
                    'value': setting_data['value'],
                    'category': setting_data['category'],
                    'description': setting_data['description'],
                    'is_public': setting_data['is_public']
                }
            )
            status = "Created" if created else "Updated"
            print(f"✓ {status} {setting_data['key']}: {setting_data['value']}")
        except Exception as e:
            print(f"✗ Failed to set {setting_data['key']}: {str(e)}")
    
    # 6. Verify settings are working by checking a loan product
    try:
        # Get one of each product type to verify settings
        for product_type in product_types:
            products = LoanProduct.objects.filter(product_type=product_type)
            if products.exists():
                product = products.first()
                interest_rate = product.get_interest_rate()
                processing_fee = product.get_processing_fee()
                late_payment = product.get_late_payment_penalty()
                
                print(f"\nVerifying {product.name} ({product_type}):")
                print(f"  - Interest Rate: {interest_rate}%")
                print(f"  - Processing Fee: {processing_fee}%")
                print(f"  - Late Payment Penalty: {late_payment}%")
    except Exception as e:
        print(f"✗ Failed to verify settings: {str(e)}")

if __name__ == "__main__":
    fix_loan_settings()
    print("\nSettings update completed.")