# Generated by Django 4.2.23 on 2025-09-28 05:03

from django.db import migrations, models
import django.db.models.deletion


def migrate_existing_analysis_annotations(apps, schema_editor):
    """
    Set created_by_analysis for existing non-structural analysis annotations.
    This ensures that existing analysis-created annotations maintain their privacy.
    """
    Annotation = apps.get_model('annotations', 'Annotation')

    # Update annotations that are linked to an analysis and are not structural
    # These are likely created by the analysis and should be private to it
    updated = Annotation.objects.filter(
        analysis__isnull=False,
        structural=False
    ).update(
        created_by_analysis_id=models.F('analysis_id')
    )

    print(f"Updated {updated} annotations to have created_by_analysis set")


def reverse_migrate_analysis_annotations(apps, schema_editor):
    """
    Reverse the migration by clearing created_by_analysis fields.
    """
    Annotation = apps.get_model('annotations', 'Annotation')

    updated = Annotation.objects.filter(
        created_by_analysis__isnull=False
    ).update(
        created_by_analysis_id=None
    )

    print(f"Cleared created_by_analysis from {updated} annotations")


class Migration(migrations.Migration):

    dependencies = [
        ("annotations", "0038_add_comprehensive_indexes"),
        ("analyzer", "0001_initial"),  # Ensure analyzer app is available
        ("extracts", "0001_initial"),  # Ensure extracts app is available
    ]

    operations = [
        # Add the created_by_analysis field
        migrations.AddField(
            model_name='annotation',
            name='created_by_analysis',
            field=models.ForeignKey(
                blank=True,
                help_text='If set, this annotation is private to the analysis that created it',
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name='created_annotations',
                to='analyzer.analysis',
            ),
        ),

        # Add the created_by_extract field
        migrations.AddField(
            model_name='annotation',
            name='created_by_extract',
            field=models.ForeignKey(
                blank=True,
                help_text='If set, this annotation is private to the extract that created it',
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name='created_annotations',
                to='extracts.extract',
            ),
        ),

        # Add indexes for the new fields
        migrations.AddIndex(
            model_name='annotation',
            index=models.Index(fields=['created_by_analysis'], name='annotations_created_a3e4d5_idx'),
        ),
        migrations.AddIndex(
            model_name='annotation',
            index=models.Index(fields=['created_by_extract'], name='annotations_created_b6f7g8_idx'),
        ),

        # Add the database constraint to ensure mutual exclusivity
        migrations.AddConstraint(
            model_name='annotation',
            constraint=models.CheckConstraint(
                check=models.Q(
                    models.Q(created_by_analysis__isnull=True) |
                    models.Q(created_by_extract__isnull=True)
                ),
                name='annotation_created_by_only_one_source',
                violation_error_message='An annotation cannot be created by both an analysis and an extract',
            ),
        ),

        # Migrate existing data
        migrations.RunPython(
            migrate_existing_analysis_annotations,
            reverse_migrate_analysis_annotations,
        ),
    ]