# Generated by Django 4.2.16 on 2026-02-27 11:03
# Standard Library
from datetime import timedelta

# Django
import django.db.models.deletion
from django.db import migrations, models
from django.utils import timezone


def clear(qryset, model_name):
    """ Tidy up the old unused models. """
    if qryset.exists():
        for o in qryset:
            print(f" - Deleting {model_name} record {vars(o)}")
            o.delete()


def check(qryset, model_name):
    """ Check for any records that would be left orphaned by the migration. """
    count = qryset.count()
    if count > 0:
        items = "\n".join([f" - {vars(o)})" for o in qryset])
        raise Exception(
            f"There are {count} {model_name} records that do not have a corresponding record in the eve_sde app. \n"
            "Please run the esde_load_sde management command to sync the data before applying this migration. \n"
            f"{items}"
        )


def check_exists(apps, schema_editor):
    es_update = apps.get_model('eve_sde', 'EveSDE')

    last_sde_update = es_update.objects.all().first().last_check_date

    print(" Running pre-migration check for eve_sde data freshness...")
    if last_sde_update is None or last_sde_update < timezone.now() - timedelta(days=1):
        print(last_sde_update)
        raise Exception(
            "The eve_sde app has not been updated in the last 24h.\n"
            "Please run the `esde_load_sde` management command to sync the data before applying this migration.")
    print(" eve_sde data is up to date. Proceeding with migration...")

    ct_item = apps.get_model('corptools', 'EveItemType')
    es_item = apps.get_model('eve_sde', 'ItemType')
    clear(ct_item.objects.exclude(
        type_id__in=es_item.objects.all().values_list("id", flat=True)), "EveItemType")
    check(ct_item.objects.exclude(
        type_id__in=es_item.objects.all().values_list("id", flat=True)), "EveItemType")

    ct_grp = apps.get_model('corptools', 'EveItemGroup')
    es_grp = apps.get_model('eve_sde', 'ItemGroup')
    clear(ct_grp.objects.exclude(group_id__in=es_grp.objects.all(
    ).values_list("id", flat=True)), "EveItemGroup")
    check(ct_grp.objects.exclude(group_id__in=es_grp.objects.all(
    ).values_list("id", flat=True)), "EveItemGroup")

    ct_cat = apps.get_model('corptools', 'EveItemCategory')
    es_cat = apps.get_model('eve_sde', 'ItemCategory')
    clear(ct_cat.objects.exclude(category_id__in=es_cat.objects.all(
    ).values_list("id", flat=True)), "EveItemCategory")
    check(ct_cat.objects.exclude(category_id__in=es_cat.objects.all(
    ).values_list("id", flat=True)), "EveItemCategory")

    ct_reg = apps.get_model('corptools', 'MapRegion')
    es_reg = apps.get_model('eve_sde', 'Region')
    clear(ct_reg.objects.exclude(
        region_id__in=es_reg.objects.all().values_list("id", flat=True)), "MapRegion")
    check(ct_reg.objects.exclude(
        region_id__in=es_reg.objects.all().values_list("id", flat=True)), "MapRegion")

    ct_con = apps.get_model('corptools', 'MapConstellation')
    es_con = apps.get_model('eve_sde', 'Constellation')
    clear(ct_con.objects.exclude(constellation_id__in=es_con.objects.all(
    ).values_list("id", flat=True)), "MapConstellation")
    check(ct_con.objects.exclude(constellation_id__in=es_con.objects.all(
    ).values_list("id", flat=True)), "MapConstellation")

    ct_sys = apps.get_model('corptools', 'MapSystem')
    es_sys = apps.get_model('eve_sde', 'SolarSystem')
    clear(ct_sys.objects.exclude(
        system_id__in=es_sys.objects.all().values_list("id", flat=True)), "MapSystem")
    check(ct_sys.objects.exclude(
        system_id__in=es_sys.objects.all().values_list("id", flat=True)), "MapSystem")

    ct_pnt = apps.get_model('corptools', 'MapSystemPlanet')
    es_pnt = apps.get_model('eve_sde', 'Planet')
    clear(ct_pnt.objects.exclude(planet_id__in=es_pnt.objects.all(
    ).values_list("id", flat=True)), "MapSystemPlanet")
    check(ct_pnt.objects.exclude(planet_id__in=es_pnt.objects.all(
    ).values_list("id", flat=True)), "MapSystemPlanet")

    ct_mns = apps.get_model('corptools', 'MapSystemMoon')
    es_mns = apps.get_model('eve_sde', 'Moon')
    clear(ct_mns.objects.exclude(moon_id__in=es_mns.objects.all(
    ).values_list("id", flat=True)), "MapSystemMoon")
    check(ct_mns.objects.exclude(moon_id__in=es_mns.objects.all(
    ).values_list("id", flat=True)), "MapSystemMoon")


class Migration(migrations.Migration):
    dependencies = [
        ("eve_sde", "0012_alter_constellation_region"),
        ("corptools", "0129_alter_notification_id"),
    ]

    operations = [
        migrations.RunPython(check_exists),
        migrations.AlterField(
            model_name="assetsfilter",
            name="categories",
            field=models.ManyToManyField(
                blank=True,
                help_text="Filter on Asset Categories.",
                to="eve_sde.itemcategory",
            ),
        ),
        migrations.AlterField(
            model_name="assetsfilter",
            name="constellations",
            field=models.ManyToManyField(
                blank=True,
                help_text="Limit filter to specific constellations",
                to="eve_sde.constellation",
            ),
        ),
        migrations.AlterField(
            model_name="assetsfilter",
            name="groups",
            field=models.ManyToManyField(
                blank=True, help_text="Filter on Asset Groups.", to="eve_sde.itemgroup"
            ),
        ),
        migrations.AlterField(
            model_name="assetsfilter",
            name="regions",
            field=models.ManyToManyField(
                blank=True,
                help_text="Limit filter to specific regions",
                to="eve_sde.region",
            ),
        ),
        migrations.AlterField(
            model_name="assetsfilter",
            name="systems",
            field=models.ManyToManyField(
                blank=True,
                help_text="Limit filter to specific systems",
                to="eve_sde.solarsystem",
            ),
        ),
        migrations.AlterField(
            model_name="assetsfilter",
            name="types",
            field=models.ManyToManyField(
                blank=True, help_text="Filter on Asset Types.", to="eve_sde.itemtype"
            ),
        ),
        migrations.AlterField(
            model_name="characterasset",
            name="type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="characterbountystat",
            name="type_name",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE, to="eve_sde.itemtype"
            ),
        ),
        migrations.AlterField(
            model_name="characterindustryjob",
            name="blueprint_type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="blueprint_type",
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="characterindustryjob",
            name="product_type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="product_type",
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="characterlocation",
            name="current_ship",
            field=models.ForeignKey(
                blank=True,
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="charactermarketorder",
            name="region_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.region",
            ),
        ),
        migrations.AlterField(
            model_name="charactermarketorder",
            name="type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="characterminingledger",
            name="system",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE, to="eve_sde.solarsystem"
            ),
        ),
        migrations.AlterField(
            model_name="characterminingledger",
            name="type_name",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE, to="eve_sde.itemtype"
            ),
        ),
        migrations.AlterField(
            model_name="contractitem",
            name="type_name",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE, to="eve_sde.itemtype"
            ),
        ),
        migrations.AlterField(
            model_name="corpasset",
            name="type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="corporatecontractitem",
            name="type_name",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE, to="eve_sde.itemtype"
            ),
        ),
        migrations.AlterField(
            model_name="corporationindustryjob",
            name="blueprint_type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="corp_blueprint_type",
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="corporationindustryjob",
            name="product_type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="corp_product_type",
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="corporationmarketorder",
            name="region_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.region",
            ),
        ),
        migrations.AlterField(
            model_name="corporationmarketorder",
            name="type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="currentshipfilter",
            name="constellations",
            field=models.ManyToManyField(
                blank=True,
                help_text="Limit filter to specific constellations",
                to="eve_sde.constellation",
            ),
        ),
        migrations.AlterField(
            model_name="currentshipfilter",
            name="groups",
            field=models.ManyToManyField(
                blank=True, help_text="Filter on Ship Groups.", to="eve_sde.itemgroup"
            ),
        ),
        migrations.AlterField(
            model_name="currentshipfilter",
            name="regions",
            field=models.ManyToManyField(
                blank=True,
                help_text="Limit filter to specific regions",
                to="eve_sde.region",
            ),
        ),
        migrations.AlterField(
            model_name="currentshipfilter",
            name="systems",
            field=models.ManyToManyField(
                blank=True,
                help_text="Limit filter to specific systems",
                to="eve_sde.solarsystem",
            ),
        ),
        migrations.AlterField(
            model_name="currentshipfilter",
            name="types",
            field=models.ManyToManyField(
                blank=True, help_text="Filter on Ship Types.", to="eve_sde.itemtype"
            ),
        ),
        migrations.AlterField(
            model_name="evelocation",
            name="system",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.solarsystem",
            ),
        ),
        migrations.AlterField(
            model_name="implant",
            name="type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="mapjumpbridge",
            name="from_solar_system",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="bridge_from_system",
                to="eve_sde.solarsystem",
            ),
        ),
        migrations.AlterField(
            model_name="mapjumpbridge",
            name="to_solar_system",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="bridge_to_system",
                to="eve_sde.solarsystem",
            ),
        ),
        migrations.AlterField(
            model_name="oretax",
            name="item",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.DO_NOTHING, to="eve_sde.itemtype"
            ),
        ),
        migrations.AlterField(
            model_name="poco",
            name="planet",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.planet",
            ),
        ),
        migrations.AlterField(
            model_name="poco",
            name="system_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.solarsystem",
            ),
        ),
        migrations.AlterField(
            model_name="skill",
            name="skill_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="skillqueue",
            name="skill_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="starbase",
            name="moon",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="eve_sde.moon",
            ),
        ),
        migrations.AlterField(
            model_name="starbase",
            name="system",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="eve_sde.solarsystem",
            ),
        ),
        migrations.AlterField(
            model_name="starbase",
            name="type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="structure",
            name="system_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.solarsystem",
            ),
        ),
        migrations.AlterField(
            model_name="structure",
            name="type_name",
            field=models.ForeignKey(
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to="eve_sde.itemtype",
            ),
        ),
        migrations.AlterField(
            model_name="typeprice",
            name="item",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.DO_NOTHING, to="eve_sde.itemtype"
            ),
        ),
    ]
