#!/usr/bin/env python
"""
Simple fix for loans migration dependency issue
"""

import os
import sys
import django
from django.db import connection
from datetime import datetime

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()
    
    print("=== Fixing Loans Migration Dependency ===")
    
    with connection.cursor() as cursor:
        # Remove the problematic migration
        cursor.execute("DELETE FROM django_migrations WHERE app = 'loans' AND name = '0018_add_rollover_date_field'")
        print("Removed loans.0018_add_rollover_date_field")
        
        # Add 0017 if it doesn't exist
        cursor.execute("INSERT IGNORE INTO django_migrations (app, name, applied) VALUES ('loans', '0017_merge_20251002_0238', %s)", [datetime.now()])
        print("Ensured loans.0017_merge_20251002_0238 exists")
        
        # Re-add 0018 after 0017
        cursor.execute("INSERT INTO django_migrations (app, name, applied) VALUES ('loans', '0018_add_rollover_date_field', %s)", [datetime.now()])
        print("Re-added loans.0018_add_rollover_date_field")
        
        # Ensure rollover_date column exists
        try:
            cursor.execute("ALTER TABLE rollover_requests ADD COLUMN rollover_date DATE NULL COMMENT 'Preferred rollover date'")
            print("Added rollover_date column")
        except Exception as e:
            if "Duplicate column name" in str(e):
                print("rollover_date column already exists")
            else:
                print(f"Error adding column: {e}")
    
    print("SUCCESS: Loans migration dependency fixed!")

if __name__ == "__main__":
    main()
