"""Sprint A.0 data migration.

The existing `fiorentine-minchiate` DeckVariant is actually 78-card Rider-Waite-Smith
Tarot (22 majors numbered 0-21 with RWS names + 56 minors in WANDS/CUPS/SWORDS/PENTACLES).
Rename to its true identity, set the new schema fields (family / has_card_images /
is_polarized), and revocab card suits to the canonical Earthman vocabulary that
SUIT_CHOICES now requires. Earthman gets its new-field values set too. FKs remain
intact since slug-only changes don't break referential integrity.

The actual Minchiate Fiorentine deck (97 cards, 1860-1890 publication, image set
already imported per [[reference-card-image-naming-convention]]) is seeded in
Sprint A.1's follow-up migration.
"""
from django.db import migrations


SUIT_REVOCAB = {
    "WANDS":     "BRANDS",
    "CUPS":      "GRAILS",
    "SWORDS":    "BLADES",
    "PENTACLES": "CROWNS",
}


def forward(apps, schema_editor):
    DeckVariant = apps.get_model("epic", "DeckVariant")
    TarotCard = apps.get_model("epic", "TarotCard")

    # Earthman: set new-field values explicitly (default=True for has_card_images
    # would have left it True after the schema migration — wrong for Earthman).
    DeckVariant.objects.filter(slug="earthman").update(
        family="earthman", has_card_images=False, is_polarized=True,
    )

    # fiorentine-minchiate → RWS Tarot rename + new-field values.
    rws = DeckVariant.objects.filter(slug="fiorentine-minchiate").first()
    if rws:
        rws.slug = "tarot-rider-waite-smith"
        rws.name = "Tarot (Rider-Waite-Smith)"
        rws.family = "english"
        rws.has_card_images = False
        rws.is_polarized = False
        rws.save()
        # Revocab the 56 minor cards' suits to canonical Earthman vocab.
        for old_suit, new_suit in SUIT_REVOCAB.items():
            TarotCard.objects.filter(deck_variant=rws, suit=old_suit).update(
                suit=new_suit,
            )


def backward(apps, schema_editor):
    DeckVariant = apps.get_model("epic", "DeckVariant")
    TarotCard = apps.get_model("epic", "TarotCard")

    rws = DeckVariant.objects.filter(slug="tarot-rider-waite-smith").first()
    if rws:
        for new_suit, old_suit in {v: k for k, v in SUIT_REVOCAB.items()}.items():
            TarotCard.objects.filter(deck_variant=rws, suit=new_suit).update(
                suit=old_suit,
            )
        rws.slug = "fiorentine-minchiate"
        rws.name = "Fiorentine Minchiate"
        rws.save()


class Migration(migrations.Migration):
    dependencies = [
        ("epic", "0011_deckvariant_family_deckvariant_has_card_images_and_more"),
    ]
    operations = [migrations.RunPython(forward, backward)]
