# Generated by Django 5.2.8 on 2025-11-25 18:41

from django.db import migrations


PRIORITY_COLUMN = "priority"


def _identifier_converter(connection):
    introspection = connection.introspection
    return getattr(introspection, "table_name_converter", None) or getattr(
        introspection, "identifier_converter", lambda value: value
    )


def _table_names(connection):
    converter = _identifier_converter(connection)
    return {converter(name) for name in connection.introspection.table_names()}


def ensure_module_priority_column(apps, schema_editor):
    Module = apps.get_model("pages", "Module")
    connection = schema_editor.connection

    converter = _identifier_converter(connection)
    normalized_table_name = converter(Module._meta.db_table)

    if normalized_table_name not in _table_names(connection):
        return

    if _column_exists(connection, Module._meta.db_table, PRIORITY_COLUMN):
        return

    field = Module._meta.get_field(PRIORITY_COLUMN)
    field.set_attributes_from_name(PRIORITY_COLUMN)
    schema_editor.add_field(Module, field)


def _column_exists(connection, table_name: str, column_name: str) -> bool:
    vendor = connection.vendor
    with connection.cursor() as cursor:
        if vendor == "sqlite":
            cursor.execute(f"PRAGMA table_info('{table_name}')")
            return any(row[1] == column_name for row in cursor.fetchall())

        if vendor == "postgresql":
            cursor.execute(
                """
                SELECT 1
                FROM information_schema.columns
                WHERE table_schema = current_schema()
                  AND table_name = %s
                  AND column_name = %s
                LIMIT 1
                """,
                [table_name, column_name],
            )
            return cursor.fetchone() is not None

    # Fallback for other engines using Django introspection
    with connection.cursor() as cursor:
        return column_name in [
            c.name for c in connection.introspection.get_table_description(cursor, table_name)
        ]


class Migration(migrations.Migration):

    dependencies = [
        ("pages", "0044_rename_chargers_module"),
    ]

    operations = [
        migrations.RunPython(ensure_module_priority_column, migrations.RunPython.noop),
    ]
