# Generated by Django 4.2 on 2026-01-28

from django.db import migrations


def migrate_killmails_forward(apps, schema_editor):
    """
    Migrate data from CampaignKillmail to MonthlyKillmail.
    Also creates KillmailParticipant records from the attackers relationship.
    """
    CampaignKillmail = apps.get_model('aatps', 'CampaignKillmail')
    MonthlyKillmail = apps.get_model('aatps', 'MonthlyKillmail')
    KillmailParticipant = apps.get_model('aatps', 'KillmailParticipant')

    # Get CharacterOwnership model to link characters to users
    try:
        CharacterOwnership = apps.get_model('authentication', 'CharacterOwnership')
        has_ownership = True
    except LookupError:
        has_ownership = False

    # Track which killmails we've already migrated (same killmail can be in multiple campaigns)
    migrated_killmail_ids = set()

    for ck in CampaignKillmail.objects.all().iterator():
        # Skip if we've already migrated this killmail
        if ck.killmail_id in migrated_killmail_ids:
            continue

        # Get solar system info
        solar_system_id = 0
        solar_system_name = "Unknown"
        region_id = None
        region_name = "Unknown"

        if ck.solar_system:
            solar_system_id = ck.solar_system.id
            solar_system_name = ck.solar_system.name or "Unknown"
            # Try to get region info from solar system
            if hasattr(ck.solar_system, 'eve_constellation') and ck.solar_system.eve_constellation:
                constellation = ck.solar_system.eve_constellation
                if hasattr(constellation, 'eve_region') and constellation.eve_region:
                    region_id = constellation.eve_region.id
                    region_name = constellation.eve_region.name or "Unknown"

        # Create MonthlyKillmail
        mk = MonthlyKillmail.objects.create(
            killmail_id=ck.killmail_id,
            killmail_time=ck.killmail_time,
            solar_system_id=solar_system_id,
            solar_system_name=solar_system_name,
            region_id=region_id,
            region_name=region_name,
            ship_type_id=ck.ship_type_id or 0,
            ship_type_name=ck.ship_type_name or "Unknown",
            ship_group_name=ck.ship_group_name or "Unknown",
            victim_id=ck.victim_id or 0,
            victim_name=ck.victim_name or "Unknown",
            victim_corp_id=ck.victim_corp_id or 0,
            victim_corp_name=ck.victim_corp_name or "Unknown",
            victim_alliance_id=ck.victim_alliance_id,
            victim_alliance_name=ck.victim_alliance_name,
            final_blow_char_id=ck.final_blow_char_id or 0,
            final_blow_char_name=ck.final_blow_char_name or "Unknown",
            final_blow_corp_id=ck.final_blow_corp_id or 0,
            final_blow_corp_name=ck.final_blow_corp_name or "Unknown",
            final_blow_alliance_id=ck.final_blow_alliance_id,
            final_blow_alliance_name=ck.final_blow_alliance_name,
            total_value=ck.total_value or 0,
            zkill_hash="",
        )

        migrated_killmail_ids.add(ck.killmail_id)

        # Create KillmailParticipant records for attackers
        for attacker in ck.attackers.all():
            # Try to find the user who owns this character
            user = None
            if has_ownership:
                ownership = CharacterOwnership.objects.filter(
                    character_id=attacker.character_id
                ).first()
                if ownership:
                    user = ownership.user

            # Check if this attacker got the final blow
            is_final_blow = (attacker.character_id == ck.final_blow_char_id)

            KillmailParticipant.objects.create(
                killmail=mk,
                character=attacker,
                user=user,
                is_victim=False,
                is_final_blow=is_final_blow,
                damage_done=0,  # Not tracked in old model
                ship_type_id=0,  # Not tracked in old model
                ship_type_name="Unknown",
            )

        # If is_loss is True, the victim was a friendly - create a participant record
        if ck.is_loss:
            # Try to find the character and user for the victim
            EveCharacter = apps.get_model('eveonline', 'EveCharacter')
            victim_char = EveCharacter.objects.filter(
                character_id=ck.victim_id
            ).first()

            if victim_char:
                user = None
                if has_ownership:
                    ownership = CharacterOwnership.objects.filter(
                        character_id=victim_char.character_id
                    ).first()
                    if ownership:
                        user = ownership.user

                # Check if participant already exists (in case victim was also an attacker)
                exists = KillmailParticipant.objects.filter(
                    killmail=mk,
                    character=victim_char
                ).exists()

                if not exists:
                    KillmailParticipant.objects.create(
                        killmail=mk,
                        character=victim_char,
                        user=user,
                        is_victim=True,
                        is_final_blow=False,
                        damage_done=0,
                        ship_type_id=ck.ship_type_id or 0,
                        ship_type_name=ck.ship_type_name or "Unknown",
                    )


def migrate_killmails_reverse(apps, schema_editor):
    """
    Reverse migration - delete all MonthlyKillmail data.
    Note: This does NOT restore CampaignKillmail data, it just clears the new tables.
    """
    MonthlyKillmail = apps.get_model('aatps', 'MonthlyKillmail')
    # Deleting MonthlyKillmail will cascade delete KillmailParticipant
    MonthlyKillmail.objects.all().delete()


class Migration(migrations.Migration):

    dependencies = [
        ('aatps', '0006_add_monthly_killmail_models'),
        ('eveonline', '0017_alliance_and_corp_names_are_not_unique'),
        ('authentication', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(
            migrate_killmails_forward,
            migrate_killmails_reverse,
        ),
    ]
