#!/usr/bin/env python3
"""
Simple script to update Boost Plus product to accept 90 days
"""

import os
import sys
import django
import json

# Add the project directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

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

from loans.models import LoanProduct
from utils.models import SystemSetting
from django.db import transaction

def update_boost_plus_product():
    """Update Boost Plus product to accept 90 days"""
    print("Updating Boost Plus Product for 90 Days...")
    
    try:
        with transaction.atomic():
            # Get the Boost Plus product
            boost_plus = LoanProduct.objects.filter(product_type='boost_plus').first()
            
            if not boost_plus:
                print("Boost Plus product not found. Creating it...")
                boost_plus = LoanProduct.objects.create(
                    name='Boost Plus',
                    product_type='boost_plus',
                    description='Flexible loan with 30, 60, or 90-day terms. Processing fee charged monthly like interest.',
                    min_amount=1000,
                    max_amount=50000,
                    interest_rate=20.0,  # 20% per month
                    processing_fee=5.0,  # 5% processing fee (charged monthly)
                    late_payment_penalty=5.0,
                    duration_months=1,
                    min_duration=30,
                    max_duration=90,
                    available_repayment_methods=['daily', 'weekly', 'monthly'],
                    requires_guarantor=False,
                    requires_collateral=False,
                    is_active=True
                )
                print("Created new Boost Plus product")
            else:
                print(f"Found existing Boost Plus product: {boost_plus.name}")
            
            # Update the product to support 90 days
            boost_plus.max_duration = 90
            boost_plus.available_durations = [30, 60, 90]  # Set specific duration options
            boost_plus.description = 'Flexible loan with 30, 60, or 90-day terms. Processing fee charged monthly like interest.'
            boost_plus.save()
            
            print("Updated Boost Plus product:")
            print(f"   - Max Duration: {boost_plus.max_duration} days")
            print(f"   - Available Durations: {boost_plus.available_durations}")
            print(f"   - Description: {boost_plus.description}")
            
            return True
            
    except Exception as e:
        print(f"Error updating Boost Plus product: {e}")
        return False

def update_boost_plus_settings():
    """Update system settings for Boost Plus to support 90 days"""
    print("\nUpdating Boost Plus System Settings...")
    
    try:
        with transaction.atomic():
            # Define settings to update
            settings_to_update = [
                {
                    'key': 'boost_plus_max_duration',
                    'value': '90',
                    'category': 'loan',
                    'description': 'Boost Plus maximum duration in days'
                },
                {
                    'key': 'boost_plus_available_durations',
                    'value': json.dumps([30, 60, 90]),
                    'category': 'loan',
                    'description': 'Boost Plus available duration options in days'
                },
                {
                    'key': 'boost_plus_interest_rate',
                    'value': '20.0',
                    'category': 'loan',
                    'description': 'Boost Plus monthly interest rate (%)'
                },
                {
                    'key': 'boost_plus_processing_fee',
                    'value': '5.0',
                    'category': 'loan',
                    'description': 'Boost Plus processing fee (%) - charged monthly'
                },
                {
                    'key': 'boost_plus_min_amount',
                    'value': '1000',
                    'category': 'loan',
                    'description': 'Boost Plus minimum loan amount'
                },
                {
                    'key': 'boost_plus_max_amount',
                    'value': '50000',
                    'category': 'loan',
                    'description': 'Boost Plus maximum loan amount'
                },
                {
                    'key': 'boost_plus_repayment_methods',
                    'value': json.dumps(['daily', 'weekly', 'monthly']),
                    'category': 'loan',
                    'description': 'Boost Plus available repayment methods'
                }
            ]
            
            updated_count = 0
            created_count = 0
            
            for setting_data in settings_to_update:
                setting, created = SystemSetting.objects.update_or_create(
                    key=setting_data['key'],
                    defaults={
                        'value': setting_data['value'],
                        'category': setting_data['category'],
                        'description': setting_data['description']
                    }
                )
                
                if created:
                    created_count += 1
                    print(f"Created setting: {setting.key} = {setting.value}")
                else:
                    updated_count += 1
                    print(f"Updated setting: {setting.key} = {setting.value}")
            
            print(f"\nSettings Summary:")
            print(f"   - Created: {created_count} settings")
            print(f"   - Updated: {updated_count} settings")
            
            return True
            
    except Exception as e:
        print(f"Error updating Boost Plus settings: {e}")
        return False

def verify_boost_plus_changes():
    """Verify that Boost Plus product now supports 90 days"""
    print("\nVerifying Boost Plus Changes...")
    
    try:
        # Check the product
        boost_plus = LoanProduct.objects.filter(product_type='boost_plus').first()
        
        if not boost_plus:
            print("Boost Plus product not found")
            return False
        
        print(f"Boost Plus Product Verification:")
        print(f"   - Name: {boost_plus.name}")
        print(f"   - Max Duration: {boost_plus.max_duration} days")
        print(f"   - Available Durations: {boost_plus.available_durations}")
        print(f"   - Min Amount: KES {boost_plus.min_amount:,.2f}")
        print(f"   - Max Amount: KES {boost_plus.max_amount:,.2f}")
        print(f"   - Interest Rate: {boost_plus.interest_rate}% per month")
        print(f"   - Processing Fee: {boost_plus.processing_fee}%")
        print(f"   - Repayment Methods: {boost_plus.available_repayment_methods}")
        
        # Check system settings
        max_duration_setting = SystemSetting.objects.filter(key='boost_plus_max_duration').first()
        available_durations_setting = SystemSetting.objects.filter(key='boost_plus_available_durations').first()
        
        print(f"\nSystem Settings Verification:")
        if max_duration_setting:
            print(f"   - Max Duration Setting: {max_duration_setting.value} days")
        if available_durations_setting:
            durations = json.loads(available_durations_setting.value)
            print(f"   - Available Durations Setting: {durations} days")
        
        # Verify 90 days is supported
        if boost_plus.max_duration >= 90 and 90 in (boost_plus.available_durations or []):
            print("\nSUCCESS: Boost Plus now supports 90 days!")
            return True
        else:
            print("\nFAILED: Boost Plus does not properly support 90 days")
            return False
            
    except Exception as e:
        print(f"Error verifying Boost Plus changes: {e}")
        return False

if __name__ == "__main__":
    print("Starting Boost Plus 90 Days Update...")
    
    success = True
    
    # Update the product
    if not update_boost_plus_product():
        success = False
    
    # Update system settings
    if not update_boost_plus_settings():
        success = False
    
    # Verify changes
    if not verify_boost_plus_changes():
        success = False
    
    if success:
        print("\nBoost Plus 90 Days Update Completed Successfully!")
        print("\nWhat was updated:")
        print("   - Boost Plus product now supports 90 days maximum duration")
        print("   - Available durations set to [30, 60, 90] days")
        print("   - System settings updated to reflect 90-day support")
        print("\nNext steps:")
        print("   1. Test creating a new Boost Plus loan with 90 days duration")
        print("   2. Verify the loan application form shows 90 days as an option")
        print("   3. Check that existing Boost Plus loans are not affected")
    else:
        print("\nBoost Plus 90 Days Update Failed!")
        print("   Please check the error messages above and try again.")
    
    print("\n" + "="*60)
