#!/usr/bin/env python
"""
One-liner migration fix
Quick fix for migration dependency issues
"""

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("=== Quick Migration Fix ===")
    
    with connection.cursor() as cursor:
        # Remove problematic migrations
        cursor.execute("DELETE FROM django_migrations WHERE app = 'users' AND name IN ('0010_add_enhanced_permissions', '0011_manual_add_is_default', '0012_branch')")
        print("Removed problematic migrations")
        
        # Re-add in correct order
        cursor.execute("INSERT INTO django_migrations (app, name, applied) VALUES ('users', '0010_add_enhanced_permissions', %s)", [datetime.now()])
        cursor.execute("INSERT INTO django_migrations (app, name, applied) VALUES ('users', '0011_manual_add_is_default', %s)", [datetime.now()])
        cursor.execute("INSERT INTO django_migrations (app, name, applied) VALUES ('users', '0012_branch', %s)", [datetime.now()])
        print("Re-added migrations in correct order")
        
        # Add rollover column
        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}")
        
        # Add rollover migration record
        cursor.execute("INSERT IGNORE INTO django_migrations (app, name, applied) VALUES ('loans', '0018_add_rollover_date_field', %s)", [datetime.now()])
        print("Added rollover migration record")
    
    print("SUCCESS: Migration issues fixed!")

if __name__ == "__main__":
    main()
