# Generated by Django 5.2.14 on 2026-06-10 20:00

from django.conf import settings
from django.db import migrations, models


def dedupe_keyless_references(apps, schema_editor):
    """Drop duplicate keyless rows (keep the oldest) before the partial
    unique constraint lands. Postgres treats NULLs as distinct, so duplicates
    may exist for (source_annotation, reference_type) pairs with no
    canonical_key."""
    CorpusReference = apps.get_model("annotations", "CorpusReference")
    seen: set[tuple[int, str]] = set()
    duplicate_ids: list[int] = []
    rows = (
        CorpusReference.objects.filter(canonical_key__isnull=True)
        .order_by("id")
        .values_list("id", "source_annotation_id", "reference_type")
    )
    for pk, source_id, ref_type in rows:
        key = (source_id, ref_type)
        if key in seen:
            duplicate_ids.append(pk)
        else:
            seen.add(key)
    if duplicate_ids:
        CorpusReference.objects.filter(id__in=duplicate_ids).delete()


class Migration(migrations.Migration):

    dependencies = [
        ("analyzer", "0022_alter_analysis_status"),
        ("annotations", "0078_corpusreference"),
        (
            "corpuses",
            "0057_rename_corpuses_co_corpus__vote_idx_corpuses_co_corpus__64f0b6_idx_and_more",
        ),
        ("documents", "0042_pendingcorpusimport"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.RunPython(
            dedupe_keyless_references, reverse_code=migrations.RunPython.noop
        ),
        migrations.AddConstraint(
            model_name="corpusreference",
            constraint=models.UniqueConstraint(
                condition=models.Q(("canonical_key__isnull", True)),
                fields=("source_annotation", "reference_type"),
                name="uniq_corpusref_source_type_nullkey",
            ),
        ),
    ]
