"""
Management command for manual single-gamer DRAW SEA testing.

Creates a room at SKY_SELECT with one seated gamer whose sky is already
confirmed, so the DRAW SEA overlay is immediately visible on page load.

Usage:
    python src/manage.py setup_sea_session
    python src/manage.py setup_sea_session --base-url http://192.168.1.42:8000
    python src/manage.py setup_sea_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 django.utils import timezone

from apps.epic.models import Character, DeckVariant, GateSlot, Room, TableSeat, TarotCard
from apps.lyric.models import User


GAMER_EMAIL = "founder@test.io"


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 SKY_SELECT room with sky confirmed and print a DRAW SEA URL"

    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")

        # ── User ─────────────────────────────────────────────────────────────
        user, _ = User.objects.get_or_create(email=GAMER_EMAIL)
        user.is_staff = True
        user.is_superuser = True
        user.equipped_deck = None
        user.save()
        user.unlocked_decks.add(earthman)

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

        # ── Gate slot ────────────────────────────────────────────────────────
        slot = room.gate_slots.get(slot_number=1)
        slot.gamer = user
        slot.status = GateSlot.FILLED
        slot.save()

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

        # ── Significator ─────────────────────────────────────────────────────
        sig_card = TarotCard.objects.filter(
            deck_variant=earthman, arcana="MAJOR"
        ).first()

        # ── Table seat (PC = levity pole) ────────────────────────────────────
        seat, _ = TableSeat.objects.update_or_create(
            room=room, slot_number=1,
            defaults={
                "gamer": user,
                "role": "PC",
                "role_revealed": True,
                "deck_variant": earthman,
                "significator": sig_card,
            },
        )

        # ── Confirmed Character (sky already done) ───────────────────────────
        char, created = Character.objects.get_or_create(
            seat=seat,
            retired_at__isnull=True,
            defaults={
                "significator": sig_card,
                "confirmed_at": timezone.now(),
            },
        )
        if not created and char.confirmed_at is None:
            char.confirmed_at = timezone.now()
            char.significator = sig_card
            char.save()

        # ── URL ──────────────────────────────────────────────────────────────
        room_path = f"/gameboard/room/{room.pk}/"
        session_key = _make_session(user)
        url = f"{base_url}/dashboard/dev-login/{session_key}/?next={room_path}"

        self.stdout.write(f"\nRoom:  {base_url}{room_path}")
        self.stdout.write(f"Gamer: {GAMER_EMAIL}  (PC / levity / earthman)")
        self.stdout.write(f"Sig:   {sig_card}")
        self.stdout.write(f"\nURL:\n  {url}\n")
