import secrets
import uuid

from fastapi import HTTPException, status
from sqlalchemy.orm import Session

from app.models.group_order import (
    GroupOrderParticipant,
    GroupOrderSession,
    GroupOrderSessionStatus,
)
from app.utils.time import utcnow

# Excludes 0/O/1/I — meant to be read off one phone screen and typed
# by someone else in the same room, unlike e.g.
# app.services.tracking's 32-byte ticket, which nobody ever has to
# type by hand.
_JOIN_CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
_JOIN_CODE_LENGTH = 6

_NOT_FOUND = HTTPException(
    status_code=status.HTTP_404_NOT_FOUND, detail="Group order session not found."
)


def generate_join_code() -> str:
    return "".join(
        secrets.choice(_JOIN_CODE_ALPHABET) for _ in range(_JOIN_CODE_LENGTH)
    )


def get_session_or_404(db: Session, session_id: uuid.UUID) -> GroupOrderSession:
    session = (
        db.query(GroupOrderSession).filter(GroupOrderSession.id == session_id).first()
    )
    if session is None:
        raise _NOT_FOUND
    return session


_ACTIVE_STATUSES = (
    GroupOrderSessionStatus.OPEN.value,
    GroupOrderSessionStatus.LOCKED.value,
)


def get_active_session_for_cart(
    db: Session, cart_id: uuid.UUID
) -> GroupOrderSession | None:
    return (
        db.query(GroupOrderSession)
        .filter(
            GroupOrderSession.cart_id == cart_id,
            GroupOrderSession.status.in_(_ACTIVE_STATUSES),
        )
        .first()
    )


def get_session_by_join_code_or_404(db: Session, join_code: str) -> GroupOrderSession:
    session = (
        db.query(GroupOrderSession)
        .filter(GroupOrderSession.join_code == join_code.strip().upper())
        .first()
    )
    if session is None:
        raise _NOT_FOUND
    return session


def is_expired(session: GroupOrderSession) -> bool:
    """No scheduled job ever flips status to expired — this is checked
    lazily, wherever it actually matters (see GroupOrderSession's own
    docstring for why that's the right call here, not a gap)."""
    return session.deadline is not None and utcnow() >= session.deadline


def require_open(session: GroupOrderSession) -> None:
    """Raises if the session can't accept a new participant or item
    right now — explicitly locked/cancelled/checked-out, or still
    marked OPEN but past its own deadline."""
    if session.status != GroupOrderSessionStatus.OPEN.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This group order is no longer open.",
        )
    if is_expired(session):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This group order's deadline has passed.",
        )


def require_host(session: GroupOrderSession, user_id: uuid.UUID) -> None:
    if session.host_id != user_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only the host can do this.",
        )


def is_participant(db: Session, session_id: uuid.UUID, user_id: uuid.UUID) -> bool:
    return (
        db.query(GroupOrderParticipant)
        .filter(
            GroupOrderParticipant.session_id == session_id,
            GroupOrderParticipant.user_id == user_id,
        )
        .first()
        is not None
    )


def require_participant_or_host(
    db: Session, session: GroupOrderSession, user_id: uuid.UUID
) -> None:
    if user_id == session.host_id:
        return
    if not is_participant(db, session.id, user_id):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You haven't joined this group order.",
        )
