#!/usr/bin/env python3
"""
Fix rollover to UPDATE existing loan instead of creating new one
This fixes the duplicate loan number IntegrityError
"""

import os
import sys

print("🚀 Deploying Rollover Fix: Update Instead of Create")
print("=" * 60)

if not os.path.exists('manage.py'):
    print("\n❌ Error: manage.py not found!")
    print("Run from Django project root: cd ~/public_html")
    sys.exit(1)

print("\n📋 What Changed:")
print("-" * 60)
print("BEFORE (caused duplicate error):")
print("  1. Mark old loan as 'rolled_over'")
print("  2. Create NEW loan record with same/different number")
print("  ❌ Issues:")
print("     - Duplicate loan numbers")
print("     - Two loan records for same loan")
print("     - Payment history fragmented")
print()
print("AFTER (clean update):")
print("  1. UPDATE existing loan with new terms:")
print("     - New principal amount")
print("     - New interest amount")
print("     - New duration & due date")
print("     - Add rollover fee to processing fee")
print("     - Mark is_rolled_over = True")
print("  ✅ Benefits:")
print("     - Same loan, same loan number")
print("     - All payments stay with same loan")
print("     - No duplicate records")
print("     - Cleaner data model")

print("\n📁 Files Modified:")
print("-" * 60)
print("  • loans/models.py - RolloverRequest.approve() method")
print("  • loans/views.py - Success message updated")

print("\n🔍 Technical Details:")
print("-" * 60)
print("The approve() method now:")
print("  1. Calculates new loan terms (amount, interest, fees)")
print("  2. Updates self.loan with:")
print("     - principal_amount = new amount")
print("     - interest_amount = new interest")
print("     - processing_fee += rollover_fee")
print("     - total_amount = principal + interest + fees")
print("     - duration_days = new duration")
print("     - due_date = rollover_date + duration")
print("     - is_rolled_over = True")
print("  3. Saves the updated loan")
print("  4. Returns the same loan object")

response = input("\n" + "=" * 60 + "\nDeploy this fix? (yes/no): ")

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

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

# 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"⚠️  Manual restart needed: {e}")

print("\n" + "=" * 60)
print("✅ Deployment Complete!")
print("\nTesting Steps:")
print("  1. Go to Loans → Rollovers")
print("  2. Find a pending rollover request")
print("  3. Click 'Approve Rollover'")
print("  4. Should work without IntegrityError")
print("  5. Check the loan:")
print("     - Same loan number (unchanged)")
print("     - Updated amounts and dates")
print("     - All previous payments still visible")
print("     - is_rolled_over flag = True")
print("=" * 60)
