#!/usr/bin/env python
"""
cPanel Script: Update Rollover Loans Status
===========================================

This script updates existing rolled over loans to follow the new status pattern:
- Changes loan application status from 'approved' to 'active' for rolled over loans
- Ensures consistency across all rolled over loans

Run this script from your cPanel terminal or via SSH.

Usage:
    python cpanel_update_rollover_status.py

Requirements:
    - Django project must be properly configured
    - Database access permissions
    - Python environment with Django installed
"""

import os
import sys
import django
from datetime import datetime
import logging

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('rollover_status_update.log'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger(__name__)

def setup_django():
    """Setup Django environment"""
    try:
        # Add the project directory to Python path
        project_dir = os.path.dirname(os.path.abspath(__file__))
        sys.path.append(project_dir)
        
        # Set Django settings module
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
        
        # Initialize Django
        django.setup()
        
        logger.info("✅ Django environment setup successfully")
        return True
    except Exception as e:
        logger.error(f"❌ Failed to setup Django environment: {str(e)}")
        return False

def update_rollover_loans_status():
    """Update existing rolled over loans to follow the new status pattern"""
    logger.info("🚀 Starting Rollover Status Update")
    logger.info("=" * 50)
    
    try:
        from django.db import transaction
        from loans.models import Loan, LoanApplication, RolloverRequest
        
        with transaction.atomic():
            # Find all rolled over loans
            rolled_over_loans = Loan.objects.filter(status='rolled_over')
            total_rolled_over = rolled_over_loans.count()
            
            logger.info(f"📊 Found {total_rolled_over} rolled over loans to check")
            
            if total_rolled_over == 0:
                logger.info("ℹ️  No rolled over loans found. Nothing to update.")
                return True
            
            updated_count = 0
            already_correct = 0
            
            for i, loan in enumerate(rolled_over_loans, 1):
                logger.info(f"🔄 Processing loan {i}/{total_rolled_over}: {loan.loan_number}")
                
                # Check current application status
                current_status = loan.application.status
                logger.info(f"   📋 Current application status: '{current_status}'")
                
                # Update the loan application status to 'active' if it's 'approved'
                if current_status == 'approved':
                    loan.application.status = 'active'
                    loan.application.save()
                    logger.info(f"   ✅ Updated application status from 'approved' to 'active'")
                    updated_count += 1
                elif current_status == 'active':
                    logger.info(f"   ✅ Application status already 'active' - no change needed")
                    already_correct += 1
                else:
                    logger.info(f"   ⚠️  Application status '{current_status}' - unexpected status")
            
            # Also check for any rollover requests that might need updating
            rollover_requests = RolloverRequest.objects.filter(status='approved')
            logger.info(f"\n📋 Found {rollover_requests.count()} approved rollover requests")
            
            rollover_updated_count = 0
            
            for rollover in rollover_requests:
                # Find loans created by this rollover (we can identify them by the purpose)
                related_loans = Loan.objects.filter(
                    application__purpose__icontains=f'Rollover for loan {rollover.loan.loan_number}'
                )
                
                for related_loan in related_loans:
                    if related_loan.application.status == 'approved':
                        related_loan.application.status = 'active'
                        related_loan.application.save()
                        logger.info(f"   ✅ Updated rollover-related loan {related_loan.loan_number} application status")
                        rollover_updated_count += 1
            
            # Summary
            total_updated = updated_count + rollover_updated_count
            
            logger.info("\n" + "=" * 50)
            logger.info("📊 UPDATE SUMMARY")
            logger.info("=" * 50)
            logger.info(f"✅ Rolled over loans updated: {updated_count}")
            logger.info(f"✅ Already correct: {already_correct}")
            logger.info(f"✅ Rollover-related loans updated: {rollover_updated_count}")
            logger.info(f"🎯 Total updates completed: {total_updated}")
            
            if total_updated > 0:
                logger.info("✅ All updates completed successfully!")
            else:
                logger.info("ℹ️  No updates were needed - all loans already have correct status")
            
            return True
            
    except Exception as e:
        logger.error(f"❌ Failed to update rollover loans: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        return False

def verify_updates():
    """Verify that the updates were applied correctly"""
    logger.info("\n🔍 Verifying updates...")
    
    try:
        from loans.models import Loan
        
        # Check rolled over loans
        rolled_over_loans = Loan.objects.filter(status='rolled_over')
        active_applications = rolled_over_loans.filter(application__status='active').count()
        approved_applications = rolled_over_loans.filter(application__status='approved').count()
        
        logger.info(f"📊 Rolled over loans verification:")
        logger.info(f"   - Total rolled over loans: {rolled_over_loans.count()}")
        logger.info(f"   - With 'active' application status: {active_applications}")
        logger.info(f"   - With 'approved' application status: {approved_applications}")
        
        if approved_applications == 0:
            logger.info("✅ All rolled over loans have 'active' application status")
            return True
        else:
            logger.warning(f"⚠️  {approved_applications} rolled over loans still have 'approved' status")
            return False
            
    except Exception as e:
        logger.error(f"❌ Verification failed: {str(e)}")
        return False

def main():
    """Main function"""
    logger.info("🎯 cPanel Rollover Status Update Script")
    logger.info("=" * 50)
    logger.info("This script will update rolled over loan statuses")
    logger.info("to follow the new pattern (active instead of approved)")
    logger.info("=" * 50)
    
    # Setup Django
    if not setup_django():
        logger.error("❌ Cannot proceed without Django setup")
        return False
    
    # Update rollover loans
    if not update_rollover_loans_status():
        logger.error("❌ Update process failed")
        return False
    
    # Verify updates
    if not verify_updates():
        logger.warning("⚠️  Some loans may not have been updated correctly")
        return False
    
    logger.info("\n🎉 Script completed successfully!")
    logger.info("All rolled over loans now follow the new status pattern.")
    
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
