"""
Script to fix migration state for functions app.
This checks if the column already exists and marks migrations as applied if needed.
"""
import os
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'worktimeapp.settings')
django.setup()

from django.db import connection

def check_column_exists():
    """Check if function_ref_id column exists in functions_function table"""
    with connection.cursor() as cursor:
        cursor.execute("""
            SELECT COLUMN_NAME 
            FROM INFORMATION_SCHEMA.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
            AND TABLE_NAME = 'functions_function' 
            AND COLUMN_NAME IN ('function_ref', 'function_ref_id')
        """)
        columns = [row[0] for row in cursor.fetchall()]
        return columns

def main():
    columns = check_column_exists()
    print(f"Found columns: {columns}")
    
    if 'function_ref_id' in columns:
        print("✓ Column 'function_ref_id' already exists")
        if 'function_ref' in columns:
            print("⚠ WARNING: Both 'function_ref' and 'function_ref_id' exist!")
            print("  You may need to drop 'function_ref' column manually")
        else:
            print("✓ Column 'function_ref' does not exist (good)")
            print("\nThe column rename was already done.")
            print("You should mark these migrations as applied:")
            print("  python manage.py migrate functions 0010 --fake")
            print("  python manage.py migrate functions 0011 --fake")
            print("  python manage.py migrate functions 0012 --fake")
            print("  python manage.py migrate functions 0013 --fake")
    elif 'function_ref' in columns:
        print("⚠ Column 'function_ref' exists but 'function_ref_id' does not")
        print("  You need to run migration 0003 to rename it")
    else:
        print("⚠ Neither column exists - this is unexpected")

if __name__ == '__main__':
    main()

