# Generated by Django 5.1 on 2024-08-01 12:34

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

import bionty
import bionty.ids
from bionty._bionty import encode_uid, list_biorecord_models


def prepend_bionty_to_entity(apps, schema_editor):
    bionty_models = list_biorecord_models(bionty)
    Source = apps.get_model("bionty", "Source")
    for source in Source.objects.all():
        if source.entity in bionty_models and not source.entity.startswith("bionty."):
            # append bionty to entity
            source.entity = f"bionty.{source.entity}"
            # re-encode uid
            source.uid = encode_uid(
                Source,
                {
                    "entity": source.entity,
                    "name": source.name,
                    "organism": source.organism,
                    "version": source.version,
                },
            )["uid"]
            source.save()


class Migration(migrations.Migration):
    dependencies = [
        ("bionty", "0031_alter_cellmarker_name_and_more"),
        (
            "lnschema_core",
            "0056_rename_ulabel_ref_is_name_artifactulabel_label_ref_is_name_and_more",
        ),
    ]

    operations = [
        migrations.RenameField(
            model_name="source",
            old_name="source_name",
            new_name="description",
        ),
        migrations.RenameField(
            model_name="source",
            old_name="source",
            new_name="name",
        ),
        migrations.RenameField(
            model_name="source",
            old_name="df",
            new_name="dataframe_artifact",
        ),
        migrations.AlterField(
            model_name="source",
            name="dataframe_artifact",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.PROTECT,
                related_name="source_dataframe_of",
                to="lnschema_core.artifact",
            ),
        ),
        migrations.AlterField(
            model_name="source",
            name="artifacts",
            field=models.ManyToManyField(
                related_name="source_artifact_of", to="lnschema_core.artifact"
            ),
        ),
        migrations.AlterField(
            model_name="source",
            name="entity",
            field=models.CharField(db_index=True, max_length=256),
        ),
        migrations.AlterField(
            model_name="source",
            name="uid",
            field=models.CharField(
                default=bionty.ids.source, max_length=4, unique=True
            ),
        ),
        migrations.RunPython(prepend_bionty_to_entity),
    ]
