#!/usr/bin/env python
"""
Implement Loan System Changes
==============================

This script implements the following changes:
1. Change loan disbursement numbers to format: datemonthyear (e.g., 11112026-00001)
2. Keep rolled over loan numbers unchanged (retain original number)
3. Mark rolled over loans clearly as "ROLLED OVER" or "RENEWED"
4. Add a system-wide SMS notifications toggle

Usage:
    python implement_loan_changes.py

"""

import os
import sys
import django
import logging
from datetime import datetime
from decimal import Decimal

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

from django.db import connection, transaction
from loans.models import Loan, RolloverRequest
from reports.models import SystemSettings

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def print_section(title):
    """Print a section header"""
    print("\n" + "=" * 80)
    print(f" {title}")
    print("=" * 80)


def backup_loan_model():
    """Create backup of current loan model before changes"""
    print_section("BACKING UP LOAN MODEL")
    
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    backup_file = f'loans_models_backup_{timestamp}.py'
    
    import shutil
    shutil.copy2('loans/models.py', backup_file)
    logger.info(f"✓ Backed up loans/models.py to {backup_file}")
    return backup_file


def update_loan_model_for_date_format():
    """
    Update the Loan model to generate loan numbers in datemonthyear format
    Changes: LOAN-000001 → 11112026-00001
    """
    print_section("UPDATING LOAN MODEL - LOAN NUMBER FORMAT")
    
    models_file = 'loans/models.py'
    
    with open(models_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Find and replace the loan number generation logic
    old_generation = '''                        self.loan_number = f"LOAN-{next_num:06d}"'''
    
    new_generation = '''                        # Generate loan number in datemonthyear format
                        # Format: DDMMYYYY-NNNNNN (e.g., 11112026-000001)
                        from datetime import datetime
                        date_part = datetime.now().strftime('%d%m%Y')
                        self.loan_number = f"{date_part}-{next_num:06d}"'''
    
    if old_generation in content:
        content = content.replace(old_generation, new_generation)
        
        with open(models_file, 'w', encoding='utf-8') as f:
            f.write(content)
        
        logger.info("✓ Updated loan number generation to datemonthyear format")
        logger.info("  New format: DDMMYYYY-NNNNNN (e.g., 11112026-000001)")
        return True
    else:
        logger.warning("⚠ Could not find loan number generation code to update")
        return False


def update_rollover_to_retain_loan_number():
    """
    Update the RolloverRequest.approve() method to retain the original loan number
    """
    print_section("UPDATING ROLLOVER - RETAIN LOAN NUMBERS")
    
    models_file = 'loans/models.py'
    
    with open(models_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Find the rollover approve method
    # We need to set the loan_number explicitly before saving the new loan
    
    # Find the location where new_loan is created
    search_pattern = '''        # Create the new active loan
        new_loan = Loan.objects.create('''
    
    if search_pattern in content:
        # Add logic to preserve the original loan number
        replacement = '''        # Create the new active loan
        # Preserve the original loan number for rolled over loans
        original_loan_number = self.loan.loan_number
        
        new_loan = Loan.objects.create('''
        
        content = content.replace(search_pattern, replacement, 1)
        
        # Now find where the new_loan is created and add loan_number parameter
        # Look for the Loan.objects.create call in approve method
        create_pattern = '''        new_loan = Loan.objects.create(
            application=new_application,
            borrower=self.loan.borrower,'''
        
        create_replacement = '''        new_loan = Loan.objects.create(
            application=new_application,
            borrower=self.loan.borrower,
            loan_number=original_loan_number,  # Retain original loan number'''
        
        if create_pattern in content:
            content = content.replace(create_pattern, create_replacement, 1)
        
        with open(models_file, 'w', encoding='utf-8') as f:
            f.write(content)
        
        logger.info("✓ Updated rollover logic to retain original loan numbers")
        logger.info("  Rolled over loans will keep their original loan number")
        return True
    else:
        logger.warning("⚠ Could not find rollover create code to update")
        return False


def add_sms_notifications_toggle():
    """
    Update SMS service to check system settings before sending
    """
    print_section("ADDING SMS NOTIFICATIONS TOGGLE")
    
    sms_service_file = 'payments/sms_service.py'
    
    with open(sms_service_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Add a check at the beginning of send_sms function
    old_function_start = '''def send_sms(recipients, message, sender_id=None,
             sms_type='other', loan_number='', borrower_name='', amount=None):
    """
    Send an SMS via Africa's Talking and log it.

    Args:
        recipients (str | list): Phone number(s) in E.164 or Kenyan format.
        message (str): The SMS body.
        sender_id (str): Alphanumeric sender ID (default: settings.SMS_SENDER_ID).
        sms_type (str): One of the SMS_TYPE_CHOICES keys for the log.
        loan_number (str): Optional loan number for context in the log.
        borrower_name (str): Optional borrower name for context in the log.
        amount (Decimal|float): Optional amount for context in the log.

    Returns:
        dict: The raw AT API response, or an error dict on failure.
    """
    if sender_id is None:'''
    
    new_function_start = '''def send_sms(recipients, message, sender_id=None,
             sms_type='other', loan_number='', borrower_name='', amount=None):
    """
    Send an SMS via Africa's Talking and log it.

    Args:
        recipients (str | list): Phone number(s) in E.164 or Kenyan format.
        message (str): The SMS body.
        sender_id (str): Alphanumeric sender ID (default: settings.SMS_SENDER_ID).
        sms_type (str): One of the SMS_TYPE_CHOICES keys for the log.
        loan_number (str): Optional loan number for context in the log.
        borrower_name (str): Optional borrower name for context in the log.
        amount (Decimal|float): Optional amount for context in the log.

    Returns:
        dict: The raw AT API response, or an error dict on failure.
    """
    # Check if SMS notifications are enabled system-wide
    from reports.models import SystemSettings
    try:
        settings_obj = SystemSettings.get_settings()
        if not settings_obj.sms_notifications_enabled:
            logger.info(f"SMS notifications disabled - skipping SMS [{sms_type}] to recipients")
            response = {'status': 'skipped', 'message': 'SMS notifications disabled by admin'}
            _log_sms(sms_type, normalised if isinstance(recipients, list) else [recipients], 
                    message, sender_id or 'HavGrazuri', response, loan_number, borrower_name, amount)
            return response
    except Exception as e:
        logger.warning(f"Could not check SMS notifications setting: {e}")
        # Continue with SMS send if we can't check settings
    
    if sender_id is None:'''
    
    if old_function_start in content:
        content = content.replace(old_function_start, new_function_start)
        
        with open(sms_service_file, 'w', encoding='utf-8') as f:
            f.write(content)
        
        logger.info("✓ Added SMS notifications toggle check to sms_service.py")
        logger.info("  Admin can now disable all SMS from System Settings")
        return True
    else:
        logger.warning("⚠ Could not find send_sms function to update")
        return False


def update_templates_for_rollover_display():
    """
    Update loan display templates to clearly mark rolled over/renewed loans
    """
    print_section("UPDATING TEMPLATES - ROLLOVER DISPLAY")
    
    # Common template files that display loan status
    template_files = [
        'templates/loans/loan_list.html',
        'templates/loans/loan_detail.html',
        'templates/loans/borrower_dashboard.html',
        'templates/dashboard/index.html'
    ]
    
    updated_count = 0
    
    for template_path in template_files:
        if not os.path.exists(template_path):
            continue
        
        try:
            with open(template_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            modified = False
            
            # Look for status badge displays and enhance them
            # Pattern 1: {{ loan.status }}
            if '{{ loan.status }}' in content and 'rolled_over' not in content:
                # Add template filter or conditional display
                old_pattern = '{{ loan.status }}'
                new_pattern = '''{% if loan.status == 'rolled_over' %}ROLLED OVER{% elif loan.is_rolled_over %}RENEWED{% else %}{{ loan.status }}{% endif %}'''
                content = content.replace(old_pattern, new_pattern)
                modified = True
            
            # Pattern 2: Status badge classes
            if 'badge-' in content and 'rolled_over' not in content:
                # Add CSS class for rolled over status
                rollover_css = '''
                {% if loan.status == 'rolled_over' or loan.is_rolled_over %}
                    <span class="badge badge-warning">
                        <i class="fas fa-sync-alt"></i> ROLLED OVER / RENEWED
                    </span>
                {% endif %}
                '''
                # This is a template-specific change, would need to see actual template structure
            
            if modified:
                with open(template_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                logger.info(f"✓ Updated {template_path}")
                updated_count += 1
        
        except Exception as e:
            logger.warning(f"⚠ Could not update {template_path}: {e}")
    
    if updated_count > 0:
        logger.info(f"✓ Updated {updated_count} template files")
    else:
        logger.info("ℹ No template files needed updating")
    
    return updated_count > 0


def verify_system_settings():
    """
    Verify that SystemSettings has sms_notifications_enabled field
    """
    print_section("VERIFYING SYSTEM SETTINGS")
    
    try:
        settings = SystemSettings.get_settings()
        
        # Check if field exists
        has_sms_field = hasattr(settings, 'sms_notifications_enabled')
        
        if has_sms_field:
            logger.info("✓ SystemSettings.sms_notifications_enabled field exists")
            logger.info(f"  Current value: {settings.sms_notifications_enabled}")
            
            # Ensure it's enabled by default
            if settings.sms_notifications_enabled:
                logger.info("  ✓ SMS notifications are currently ENABLED")
            else:
                logger.warning("  ⚠ SMS notifications are currently DISABLED")
            
            return True
        else:
            logger.error("✗ SystemSettings.sms_notifications_enabled field NOT FOUND")
            return False
    
    except Exception as e:
        logger.error(f"✗ Error checking SystemSettings: {e}")
        return False


def test_loan_number_generation():
    """
    Test the new loan number format by creating a test in memory
    """
    print_section("TESTING LOAN NUMBER FORMAT")
    
    try:
        from datetime import datetime
        
        # Simulate what the new format will look like
        date_part = datetime.now().strftime('%d%m%Y')
        next_num = 1
        test_loan_number = f"{date_part}-{next_num:06d}"
        
        logger.info(f"✓ New loan number format: {test_loan_number}")
        logger.info(f"  Format: DDMMYYYY-NNNNNN")
        logger.info(f"  Date part: {date_part}")
        logger.info(f"  Sequential: {next_num:06d}")
        
        # Check existing loans to see current format
        with connection.cursor() as cursor:
            cursor.execute("SELECT loan_number FROM loans ORDER BY created_at DESC LIMIT 5")
            rows = cursor.fetchall()
            
            if rows:
                logger.info("\n  Current loan numbers in database:")
                for row in rows:
                    logger.info(f"    {row[0]}")
        
        return True
    
    except Exception as e:
        logger.error(f"✗ Error testing loan number format: {e}")
        return False


def create_admin_guide():
    """
    Create a guide for admins on how to use the new features
    """
    print_section("CREATING ADMIN GUIDE")
    
    guide_content = """
# Loan System Changes - Admin Guide
==========================================

## Changes Implemented

### 1. New Loan Number Format
- **Old Format**: LOAN-000001, LOAN-000002, etc.
- **New Format**: DDMMYYYY-NNNNNN (e.g., 11112026-000001)
- The date represents the disbursement date
- The number is sequential for that day

### 2. Rolled Over Loans
- When a loan is rolled over, it **retains its original loan number**
- The original loan is marked as "ROLLED OVER" 
- The new loan appears as "RENEWED" but with the same loan number
- This makes it easy to track loan history
- Only interest and fees change during rollover

### 3. SMS Notifications Toggle
- Navigate to: **Admin Panel → System Settings**
- Find the field: **SMS Notifications Enabled**
- Toggle this checkbox to enable/disable ALL customer SMS
- When disabled:
  - No SMS will be sent to customers
  - SMS attempts are logged but skipped
  - Admin can see skipped messages in SMS logs
- When re-enabled, SMS sending resumes immediately

## How to Disable SMS Notifications

1. Log in to Django Admin: http://yourdomain.com/admin/
2. Go to: **Reports → System Settings**
3. Click on the existing settings record
4. Uncheck: **Sms notifications enabled**
5. Click **Save**

All SMS will now be disabled until you re-enable this setting.

## Testing Checklist

- [ ] Create a new loan and verify the loan number format
- [ ] Rollover an existing loan and verify it keeps the same number
- [ ] Check that rolled over loans are clearly marked
- [ ] Disable SMS notifications and verify no SMS are sent
- [ ] Re-enable SMS and verify SMS resume

## Support

If you encounter any issues, check:
- SMS Logs page for skipped messages
- Loan details page for rollover status
- System logs for any errors

"""
    
    guide_file = 'LOAN_CHANGES_ADMIN_GUIDE.md'
    
    with open(guide_file, 'w', encoding='utf-8') as f:
        f.write(guide_content)
    
    logger.info(f"✓ Created admin guide: {guide_file}")
    return guide_file


def main():
    """Main execution function"""
    print("\n" + "=" * 80)
    print(" LOAN SYSTEM CHANGES IMPLEMENTATION")
    print(" " + "=" * 78)
    print(" This script will implement:")
    print("   1. New loan number format (datemonthyear)")
    print("   2. Retain loan numbers on rollover")
    print("   3. Mark rolled over loans clearly")
    print("   4. Add SMS notifications toggle")
    print("=" * 80)
    
    print("\nProceeding with implementation...")
    
    results = []
    
    # Step 1: Backup
    try:
        backup_file = backup_loan_model()
        results.append(("Backup created", True, backup_file))
    except Exception as e:
        results.append(("Backup created", False, str(e)))
    
    # Step 2: Update loan number format
    try:
        success = update_loan_model_for_date_format()
        results.append(("Loan number format updated", success, ""))
    except Exception as e:
        results.append(("Loan number format updated", False, str(e)))
    
    # Step 3: Update rollover logic
    try:
        success = update_rollover_to_retain_loan_number()
        results.append(("Rollover retains loan number", success, ""))
    except Exception as e:
        results.append(("Rollover retains loan number", False, str(e)))
    
    # Step 4: Add SMS toggle
    try:
        success = add_sms_notifications_toggle()
        results.append(("SMS notifications toggle", success, ""))
    except Exception as e:
        results.append(("SMS notifications toggle", False, str(e)))
    
    # Step 5: Update templates
    try:
        success = update_templates_for_rollover_display()
        results.append(("Templates updated", success, ""))
    except Exception as e:
        results.append(("Templates updated", False, str(e)))
    
    # Step 6: Verify system settings
    try:
        success = verify_system_settings()
        results.append(("System settings verified", success, ""))
    except Exception as e:
        results.append(("System settings verified", False, str(e)))
    
    # Step 7: Test loan number format
    try:
        success = test_loan_number_generation()
        results.append(("Loan number format tested", success, ""))
    except Exception as e:
        results.append(("Loan number format tested", False, str(e)))
    
    # Step 8: Create admin guide
    try:
        guide_file = create_admin_guide()
        results.append(("Admin guide created", True, guide_file))
    except Exception as e:
        results.append(("Admin guide created", False, str(e)))
    
    # Print summary
    print_section("IMPLEMENTATION SUMMARY")
    
    success_count = sum(1 for _, success, _ in results if success)
    total_count = len(results)
    
    for task, success, detail in results:
        status = "✓" if success else "✗"
        print(f"{status} {task}")
        if detail:
            print(f"   {detail}")
    
    print(f"\n{success_count}/{total_count} tasks completed successfully")
    
    if success_count == total_count:
        print("\n🎉 All changes implemented successfully!")
        print("\nNext steps:")
        print("  1. Review the changes in the modified files")
        print("  2. Run: python manage.py makemigrations")
        print("  3. Run: python manage.py migrate")
        print("  4. Test locally before deploying")
        print("  5. Read LOAN_CHANGES_ADMIN_GUIDE.md for usage instructions")
    else:
        print("\n⚠ Some tasks failed. Please review the errors above.")
        print("  Check the backup file if you need to restore.")
    
    return success_count == total_count


if __name__ == '__main__':
    try:
        success = main()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n\nOperation cancelled by user.")
        sys.exit(1)
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
