#!/usr/bin/env python3
"""
Fix for rollover duplicate loan number error
Deployed to production to fix IntegrityError when approving rollovers
"""

import os
import sys

print("🚀 Deploying Rollover Loan Number Fix")
print("=" * 60)

# Check if we're in the right directory
if not os.path.exists('manage.py'):
    print("\n❌ Error: manage.py not found!")
    print("Please run this script from your Django project root:")
    print("  cd ~/public_html && python fix_rollover_duplicate_loan_number.py")
    sys.exit(1)

print("\n✅ Found Django project")

# Show what the fix does
print("\n📋 What this fix does:")
print("-" * 60)
print("BEFORE (causing error):")
print("  1. Original loan: '12112026-000003'")
print("  2. Try to create new loan: '12112026-000003'")
print("  ❌ ERROR: Duplicate entry - both loans have same number!")
print()
print("AFTER (with fix):")
print("  1. Rename original loan: '12112026-000003' → '12112026-000003-R'")
print("  2. Create new loan: '12112026-000003'")
print("  ✅ SUCCESS: No duplicate - old loan has -R suffix!")
print()
print("Benefits:")
print("  • Active rollover loans keep the original clean number")
print("  • Historical rolled-over loans have -R suffix")
print("  • No more IntegrityError on rollover approval")

# Confirm deployment
print("\n" + "=" * 60)
response = input("Deploy this fix now? (yes/no): ")

if response.lower() != 'yes':
    print("❌ Deployment cancelled")
    sys.exit(0)

print("\n🔄 Deploying fix...")

# The fix is already in loans/models.py
# We just need to restart the application

print("\n✅ Fix is already in loans/models.py")
print("   Modified: RolloverRequest.approve() method")
print("   Change: Rename old loan before creating new one")

# Restart Django
print("\n🔄 Restarting Django application...")
try:
    os.makedirs('tmp', exist_ok=True)
    with open('tmp/restart.txt', 'a'):
        os.utime('tmp/restart.txt', None)
    print("✅ Application restart triggered")
except Exception as e:
    print(f"⚠️  Could not trigger automatic restart: {e}")
    print("   Please restart manually via cPanel")

print("\n" + "=" * 60)
print("✅ Deployment Complete!")
print("\nWhat changed:")
print("  • loans/models.py - RolloverRequest.approve() method")
print("  • Old loans now get '-R' suffix when rolled over")
print("  • New rollover loans keep the original loan number")
print("\nTesting:")
print("  1. Go to a rollover request")
print("  2. Click 'Approve Rollover'")
print("  3. Should work without IntegrityError")
print("  4. Check loan numbers:")
print("     - Active loan: '12112026-000003'")
print("     - Rolled over loan: '12112026-000003-R'")
print("=" * 60)
