"""
Management command for manual multi-user sig-select testing.

Creates (or reuses) a room with all 6 gate slots filled, roles assigned,
deck contributions wired, and table_status=SIG_SELECT.  Prints one pre-auth
URL per gamer so you can paste them into 6 Firefox Multi-Account Container tabs.

Deck contribution by role pair (same segment, levity vs gravity pole):
  PC & BC → Brands + Crowns     (levity / gravity)
  SC & AC → Blades + Grails     (levity / gravity)
  NC & EC → Trumps              (levity / gravity)

Usage:
    python src/manage.py setup_sig_session
    python src/manage.py setup_sig_session --base-url http://localhost:8000
    python src/manage.py setup_sig_session --room <uuid>   # reuse existing room
"""

from django.contrib.auth import BACKEND_SESSION_KEY, HASH_SESSION_KEY, SESSION_KEY
from django.contrib.sessions.backends.db import SessionStore
from django.core.management.base import BaseCommand

from apps.drama.models import Note
from apps.epic.models import DeckVariant, GateSlot, Room, TableSeat
from apps.lyric.models import User


GAMERS = [
    ("founder@test.io", "discoman"),
    ("amigo@test.io",   "amigo"),
    ("bud@test.io",     "bud"),
    ("pal@test.io",     "pal"),
    ("dude@test.io",    "dude"),
    ("bro@test.io",     "bro"),
]

ROLES = ["PC", "NC", "EC", "SC", "AC", "BC"]


def _make_session(user):
    session = SessionStore()
    session[SESSION_KEY] = str(user.pk)
    session[BACKEND_SESSION_KEY] = "apps.lyric.authentication.PasswordlessAuthenticationBackend"
    session[HASH_SESSION_KEY] = user.get_session_auth_hash()
    session.save()
    return session.session_key


class Command(BaseCommand):
    help = "Set up a SIG_SELECT room and print pre-auth URLs for all six gamers"

    def add_arguments(self, parser):
        parser.add_argument("--base-url", default="http://localhost:8000")
        parser.add_argument("--room", default=None, help="UUID of an existing room to reuse")

    def handle(self, *args, **options):
        base_url = options["base_url"].rstrip("/")
        earthman = DeckVariant.objects.get(slug="earthman")

        # ── Users ────────────────────────────────────────────────────────────
        users = []
        for email, _ in GAMERS:
            user, _ = User.objects.get_or_create(email=email)
            user.is_staff = True
            user.is_superuser = True
            # Deck will be assigned to seat below; ensure it's in unlocked_decks
            # but leave equipped_deck=None (seat assignment owns it)
            user.equipped_deck = None
            user.save()
            user.unlocked_decks.add(earthman)
            Note.grant_if_new(user, "super-schizo")
            Note.grant_if_new(user, "super-nomad")
            users.append(user)

        # ── Room ─────────────────────────────────────────────────────────────
        if options["room"]:
            room = Room.objects.get(pk=options["room"])
        else:
            room = Room.objects.create(
                name="Sig Select Test Room",
                owner=users[0],
                visibility=Room.PUBLIC,
            )

        # ── Gate slots ───────────────────────────────────────────────────────
        for i, user in enumerate(users, start=1):
            slot = room.gate_slots.get(slot_number=i)
            slot.gamer = user
            slot.status = GateSlot.FILLED
            slot.save()

        room.gate_status = Room.OPEN
        room.save()

        # ── Table seats + roles + deck contributions ─────────────────────────
        # PC/NC/SC → levity pole; BC/EC/AC → gravity pole.
        # Each role pair shares a deck segment:
        #   PC & BC → Brands + Crowns
        #   SC & AC → Blades + Grails
        #   NC & EC → Trumps
        for i, (user, role) in enumerate(zip(users, ROLES), start=1):
            TableSeat.objects.update_or_create(
                room=room, slot_number=i,
                defaults={
                    "gamer": user,
                    "role": role,
                    "role_revealed": True,
                    "deck_variant": earthman,
                },
            )

        room.table_status = Room.SIG_SELECT
        room.save()

        # ── Print URLs ───────────────────────────────────────────────────────
        room_path = f"/gameboard/room/{room.pk}/"
        self.stdout.write(f"\nRoom: {base_url}{room_path}\n")
        self.stdout.write(f"{'Container':<12}  {'Email':<22}  {'Role':<6}  URL")
        self.stdout.write("─" * 100)

        for (email, container), user, role in zip(GAMERS, users, ROLES):
            session_key = _make_session(user)
            url = f"{base_url}/dashboard/dev-login/{session_key}/?next={room_path}"
            self.stdout.write(f"{container:<12}  {email:<22}  {role:<6}  {url}")

        self.stdout.write("")
