# Generated by Django 4.2.21 on 2026-01-08 23:35

from django.db import migrations
from django.apps import apps


def remove_compliance_filter_if_exists(apps_registry, schema_editor):
    """
    Remove compliance_filter field only if charlink is installed.
    This allows the migration to run whether charlink is present or not.
    """
    if apps.is_installed("charlink"):
        # Only remove the field if charlink is installed
        # If charlink isn't installed, the field was never added via add_to_class
        db_alias = schema_editor.connection.alias
        try:
            TicketToolConfig = apps_registry.get_model('aa_bb', 'TicketToolConfig')
            # Check if field exists in the model
            if hasattr(TicketToolConfig, 'compliance_filter'):
                # Use raw SQL to check if column exists in database
                with schema_editor.connection.cursor() as cursor:
                    cursor.execute("""
                        SELECT COUNT(*)
                        FROM information_schema.columns
                        WHERE table_name='aa_bb_tickettoolconfig'
                        AND column_name='compliance_filter_id'
                    """)
                    if cursor.fetchone()[0] > 0:
                        # Column exists, safe to remove
                        cursor.execute("ALTER TABLE aa_bb_tickettoolconfig DROP COLUMN compliance_filter_id")
        except Exception:
            # If anything fails, just pass - field doesn't exist or already removed
            pass


def reverse_func(apps_registry, schema_editor):
    """
    Reverse migration is a no-op since we can't reliably re-add the field.
    Users should use the model's add_to_class() instead.
    """
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('aa_bb', '0104_alter_bigbrotherconfig_is_active'),
    ]

    operations = [
        migrations.RunPython(remove_compliance_filter_if_exists, reverse_func),
    ]
