"""Sig-state FT helpers — sprint 4c of [[project-my-sea-roadmap]]. Two
public helpers:

- `_seed_earthman_sig_pile()` — restore the Earthman DeckVariant + 16
  MIDDLE court cards that `personal_sig_cards(user)` returns. The
  migration seed gets flushed by TransactionTestCase between tests
  (see [[feedback_transactiontestcase_flush]]); each setUp that touches
  the picker or its dependents must call this before creating a User.

- `_assign_sig(user, card=None, reversed_flag=False)` — set
  `User.significator` (+ `significator_reversed`) directly, bypassing
  the picker UI. Returns the assigned card so downstream assertions can
  use it. Use this in any FT that needs a "user has a sig" precondition
  without walking the SCAN SIGN → click thumb → OK → SAVE SIGN flow.

Naming follows the room_page.py / post_page.py / my_posts_page.py
convention: underscored to signal "test infrastructure, not API
surface"; public within `functional_tests/`.

Consumers:
    test_bill_my_sign — both helpers
    test_game_my_sea  — both helpers (gate / no-gate branches)
"""
from apps.epic.models import DeckVariant, TarotCard, personal_sig_cards


def _seed_earthman_sig_pile():
    """Re-seed Earthman DeckVariant + the 16 MIDDLE court cards that
    `personal_sig_cards(user)` returns. Idempotent — `get_or_create` on
    deck + each card slug.

    The 16 cards are Maid/Jack/Queen/King × BRANDS/CROWNS/BLADES/GRAILS.
    Major 0/1 (Nomad/Schizo) are *not* seeded here — `_filter_major_unlocks`
    in `personal_sig_cards()` strips them for users without the matching
    Note unlocks, which is the default state in solo FTs. If a future FT
    needs the Major seed (Note-unlocked path), it should seed those rows
    separately or extend this helper w. a flag."""
    earthman, _ = DeckVariant.objects.get_or_create(
        slug="earthman",
        defaults={"name": "Earthman", "card_count": 106, "is_default": True,
                  "is_polarized": True, "has_card_images": False},
    )
    _NAME = {11: "Maid", 12: "Jack", 13: "Queen", 14: "King"}
    for suit in ("BRANDS", "CROWNS", "BLADES", "GRAILS"):
        for number in (11, 12, 13, 14):
            TarotCard.objects.get_or_create(
                deck_variant=earthman,
                slug=f"{_NAME[number].lower()}-of-{suit.lower()}-em",
                defaults={"arcana": "MIDDLE", "suit": suit, "number": number,
                          "name": f"{_NAME[number]} of {suit.capitalize()}",
                          "levity_qualifier": "Elevated",
                          "gravity_qualifier": "Graven"},
            )
    return earthman


def _seed_minchiate_image_fixtures():
    """Re-seed the minimal Minchiate Fiorentine 1860-1890 deck rows that the
    image-rendering FTs need (Sprint A.3+ of [[project-image-based-deck-face-rendering]]):
    DeckVariant + Il Matto (MAJOR rank 0, unnumbered Fool) + Papa Uno (MAJOR rank 1).
    Idempotent — `get_or_create` on deck slug + each card slug. The full 97-card
    seed lives in migration 0013; this helper restores enough for image-render
    tests after TransactionTestCase's flush wipes migration data."""
    deck, _ = DeckVariant.objects.get_or_create(
        slug="minchiate-fiorentine-1860-1890",
        defaults={
            "name": "Minchiate Fiorentine (1860–1890)",
            "card_count": 97,
            "is_default": False,
            "family": "italian",
            "has_card_images": True,
            "is_polarized": False,
        },
    )
    for number, name, slug, corr in [
        (0, "Il Matto", "il-matto", "The Fool"),
        (1, "Papa Uno", "papa-uno", ""),
    ]:
        TarotCard.objects.get_or_create(
            deck_variant=deck,
            slug=slug,
            defaults={"arcana": "MAJOR", "suit": None, "number": number,
                      "name": name, "correspondence": corr},
        )
    return deck


def _assign_sig(user, card=None, reversed_flag=False):
    """Assign `user.significator` (and optionally `significator_reversed`)
    directly, bypassing the picker UI. Returns the assigned card.

    If `card` is None, defaults to the first card in
    `personal_sig_cards(user)` — the same card the picker happy-path FT
    targets. Caller is responsible for ensuring the sig pile is seeded
    (call `_seed_earthman_sig_pile()` before User.create if needed)."""
    if card is None:
        card = personal_sig_cards(user)[0]
    user.significator = card
    user.significator_reversed = reversed_flag
    user.save(update_fields=["significator", "significator_reversed"])
    return card
