"""Collapse of old migrations 0007–0022 into a single end-state finalize.

Schema:
  - mechanisms      → energies            (was 0008)
  - articulations   → operations          (was 0008)
  - reversal        → reversal_qualifier  (was 0014)
  - +italic_word                          (was 0018)

Data (operates on the Earthman deck seeded in 0004; idempotent against the
current schema, which is the post-rename state thanks to the operations
above running first):
  - Middle court reversal_qualifier per suit       (was 0007)
  - Schizo energies + operations w/ .card-ref      (was 0008 + 0009)
  - fa-hand-dots fallback for empty MAJOR icons    (was 0010; only card 41
                                                     in fresh-seed state)
  - Card 49 polarity-split reversal titles         (was 0015 + 0016)
  - Castanedan Virtues: trumps 6-9 + 19-21         (was 0017)
  - italic_word for trumps 19-21                   (was 0019)
  - Trump 8 rename + non-breaking hyphen           (was 0020 + 0021)
  - Trump 9 non-breaking space                     (was 0021)
  - Pip cards (number 1-10) MIDDLE → MINOR arcana  (was 0022)

Skipped (all no-ops against fresh 0004 seed):
  - 0011 (nomad/schizo icons already correct in 0004)
  - 0012 (no PENTACLES seeded for Earthman in 0004)
  - 0013 (nomad icon already fa-hat-cowboy-side in 0004)
"""
from django.db import migrations, models


# ── Schizo energies + operations ─────────────────────────────────────────────
CR = '<span class="card-ref">{}</span>'

SCHIZO_ENERGIES = [
    {"type": "LIBIDO",   "effect": f'When encountering territorial Libido, may convert Emanation into {CR.format("1. The Priest")}.'},
    {"type": "NUMEN",    "effect": f'When encountering despotic Numen, may convert Emanation into {CR.format("1. The Powerful")}.'},
    {"type": "VOLUPTAS", "effect": f'When encountering axiomatic Voluptas, may convert Emanation into {CR.format("1. The Normal")}.'},
    {"type": "VOLUPTAS", "effect": f'When encountering annihilating Voluptas, may convert Emanation into {CR.format("1. The Surrendered")}.'},
]

SCHIZO_OPERATIONS = [
    {"type": "COVER",  "effect": f'When covering {CR.format("2. The Occultist")} she may choose, by converting her own Reversal into {CR.format("2. Pestilence")}, to convert this Reversal into {CR.format("1. The Pervert")}.'},
    {"type": "CROWN",  "effect": f'When crowning {CR.format("3. The Despot")} she may choose, by converting her own Reversal into {CR.format("3. War")}, to convert this Reversal into {CR.format("1. The Paranoiac")}.'},
    {"type": "BEHIND", "effect": f'When behind {CR.format("4. The Capitalist")} he may choose, by converting his own Reversal into {CR.format("4. Famine")}, to convert this Reversal into {CR.format("1. The Neurotic")}.'},
    {"type": "BEFORE", "effect": f'When before {CR.format("5. The Fascist")} he may choose, by converting his own Reversal into {CR.format("5. Death")}, to convert this Reversal into {CR.format("1. The Suicidal")}.'},
]

# ── Middle court suit reversals ──────────────────────────────────────────────
SUIT_REVERSAL_QUALIFIER = {
    "BRANDS": "Seething",
    "GRAILS": "Gloomy",
    "BLADES": "Nervous",
    "CROWNS": "Vacant",
}
COURT_NUMBERS = [11, 12, 13, 14]

# ── Castanedan Virtues ───────────────────────────────────────────────────────
IMPLICIT_VIRTUES = [
    # (number, levity_qualifier, gravity_qualifier, reversal_title)
    (6, "Sublimating", "Sedimentary", "Indulged Folly"),
    (7, "Sublimating", "Sedimentary", "Indulgent Doing"),
    (8, "Sublimating", "Sedimentary", "Self-Indulgence"),
    (9, "Sublimating", "Sedimentary", "Indulging Personal History"),
]

EXPLICIT_VIRTUES = [
    # (number, levity_emanation, gravity_emanation, levity_reversal, gravity_reversal, italic_word)
    (19, "The Hunter's Stalking",  "The Hunter's Stalking",  "The Sleeper's Stalking", "The Quarry's Stalking",   "Stalking"),
    (20, "The Dreamer's Dreaming", "The Dreamer's Dreaming", "The Sleeper's Dreaming", "The Dreamed's Dreaming",  "Dreaming"),
    (21, "The Warrior's Intent",   "The Warrior's Intent",   "The Sleeper's Intent",   "The Predator's Intent",   "Intent"),
]


def finalize(apps, schema_editor):
    TarotCard = apps.get_model("epic", "TarotCard")
    DeckVariant = apps.get_model("epic", "DeckVariant")
    try:
        earthman = DeckVariant.objects.get(slug="earthman")
    except DeckVariant.DoesNotExist:
        return

    # Middle court suit reversals
    for suit, qualifier in SUIT_REVERSAL_QUALIFIER.items():
        TarotCard.objects.filter(
            deck_variant=earthman, arcana="MIDDLE", suit=suit,
            number__in=COURT_NUMBERS,
        ).update(reversal_qualifier=qualifier)

    # Schizo: clear stray reversal_qualifier (0004 seeds 'Territoriality') +
    # populate energies/operations
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MAJOR", number=1,
    ).update(
        reversal_qualifier="",
        energies=SCHIZO_ENERGIES,
        operations=SCHIZO_OPERATIONS,
    )

    # fa-hand-dots fallback for empty MAJOR icons (number ≥ 2)
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MAJOR", number__gte=2, icon="",
    ).update(icon="fa-hand-dots")

    # Card 49 polarity reversal titles
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MAJOR", number=49,
    ).update(
        levity_reversal="The Vibrational Mould of Man",
        gravity_reversal="The Bestowing Eagle",
    )

    # Castanedan Virtues — implicit (trumps 6-9): trump 7 name canonicalize +
    # qualifiers + reversal titles
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MAJOR", number=7,
    ).update(name="Not-Doing")
    for number, lvty, grav, rev in IMPLICIT_VIRTUES:
        TarotCard.objects.filter(
            deck_variant=earthman, arcana="MAJOR", number=number,
        ).update(
            levity_qualifier=lvty,
            gravity_qualifier=grav,
            levity_reversal=rev,
            gravity_reversal=rev,
        )

    # Castanedan Virtues — explicit (trumps 19-21): polarity-split titles +
    # italic_word for the agency stem
    for number, le, ge, lr, gr, word in EXPLICIT_VIRTUES:
        TarotCard.objects.filter(
            deck_variant=earthman, arcana="MAJOR", number=number,
        ).update(
            levity_emanation=le,
            gravity_emanation=ge,
            levity_reversal=lr,
            gravity_reversal=gr,
            italic_word=word,
        )

    # Trump 8: "Losing Self-Importance" → "Self‑Unimportance" w/ U+2011
    # non-breaking hyphen (keeps title on one line above qualifier)
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MAJOR", number=8,
    ).update(name="Self‑Unimportance", slug="self-unimportance")

    # Trump 9: insert U+00A0 between "Personal" and "History" so they wrap as
    # a single unit ("Erasing / Personal History, / Sublimating")
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MAJOR", number=9,
    ).update(name="Erasing Personal History")

    # Pip cards (number 1-10) → MINOR arcana; courts (11-14) stay MIDDLE
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MIDDLE", number__lte=10,
    ).update(arcana="MINOR")


def revert(apps, schema_editor):
    """Reverse just enough to restore 0006 schema state. Data reverts to the
    raw 0004 seed shape (without any of the post-seed tweaks)."""
    TarotCard = apps.get_model("epic", "TarotCard")
    DeckVariant = apps.get_model("epic", "DeckVariant")
    try:
        earthman = DeckVariant.objects.get(slug="earthman")
    except DeckVariant.DoesNotExist:
        return
    # Pip arcana
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MINOR", number__lte=10,
    ).update(arcana="MIDDLE")
    # Trump 8 + 9 names back
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MAJOR", number=8,
    ).update(name="Losing Self-Importance", slug="losing-self-importance")
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MAJOR", number=9,
    ).update(name="Erasing Personal History")
    # Trump 7 name back
    TarotCard.objects.filter(
        deck_variant=earthman, arcana="MAJOR", number=7,
    ).update(name="Not Doing")


class Migration(migrations.Migration):

    dependencies = [
        ("epic", "0006_add_deck_variant_to_tableseat"),
    ]

    operations = [
        migrations.RenameField("TarotCard", "mechanisms",    "energies"),
        migrations.RenameField("TarotCard", "articulations", "operations"),
        migrations.RenameField("TarotCard", "reversal",      "reversal_qualifier"),
        migrations.AddField(
            model_name="tarotcard",
            name="italic_word",
            field=models.CharField(blank=True, default="", max_length=50),
        ),
        migrations.RunPython(finalize, reverse_code=revert),
    ]
