#!/usr/bin/env python
"""
Simple fix for loans migration issues
Removes problematic migrations and lets Django recreate them
"""

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("=== Simple Loans Migration Fix ===")
    
    with connection.cursor() as cursor:
        # Remove all problematic loans migrations
        problematic_migrations = [
            '0002_enhance_rollover_request',
            '0017_merge_20251002_0238',
            '0018_add_rollover_date_field'
        ]
        
        for migration_name in problematic_migrations:
            cursor.execute("DELETE FROM django_migrations WHERE app = 'loans' AND name = %s", [migration_name])
            print(f"Removed loans.{migration_name}")
        
        # 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: Problematic loans migrations removed!")
    print("Now run: python manage.py makemigrations loans")
    print("Then run: python manage.py migrate")

if __name__ == "__main__":
    main()
