import json
import secrets
import uuid

import redis as redis_lib
import redis.asyncio as redis_asyncio

from app.utils.time import utcnow

# How long a minted WebSocket ticket stays redeemable — just long
# enough for the client to open the connection right after requesting
# one (see app.api.v1.endpoints.tracking). Deliberately short: unlike
# a real access token, this only needs to survive the handshake.
WS_TICKET_TTL_SECONDS = 60


def channel(order_id: uuid.UUID) -> str:
    return f"order:{order_id}:tracking"


def _ws_ticket_key(ticket: str) -> str:
    return f"ws_ticket:{ticket}"


def mint_ws_ticket(redis: redis_lib.Redis, user_id: uuid.UUID) -> str:
    """A short-lived, single-use ticket standing in for a real access
    token on the tracking WebSocket handshake — browsers can't set an
    Authorization header on a WebSocket handshake, so *something* has
    to go in the query string, but a real access token (valid up to
    access_token_expire_minutes, and capable of hitting any
    authenticated endpoint) is a much bigger thing to have sitting in
    a proxy/access log than a ticket that's dead within a minute and
    only good for one connection attempt."""
    ticket = secrets.token_urlsafe(32)
    redis.set(_ws_ticket_key(ticket), str(user_id), ex=WS_TICKET_TTL_SECONDS)
    return ticket


async def redeem_ws_ticket(redis: redis_asyncio.Redis, ticket: str) -> uuid.UUID | None:
    """One-shot: deletes the ticket the instant it's read, so it can
    never be reused even within its TTL. Async because the WebSocket
    endpoint that calls this is already on the async Redis client (see
    app.db.redis) for its pub/sub listen loop."""
    key = _ws_ticket_key(ticket)
    user_id = await redis.get(key)
    if user_id is None:
        return None
    await redis.delete(key)
    return uuid.UUID(user_id)


def _publish(redis: redis_lib.Redis, order_id: uuid.UUID, event: dict) -> None:
    """Fire-and-forget push to anyone currently subscribed on the
    WebSocket in app.api.v1.endpoints.tracking for this order. Takes
    the redis client as a parameter — same DI pattern as
    app.services.cache — rather than importing a module-level client,
    so tests can swap in fakeredis via the get_redis override."""
    redis.publish(channel(order_id), json.dumps({**event, "at": utcnow().isoformat()}))


def publish_location(
    redis: redis_lib.Redis, order_id: uuid.UUID, latitude: float, longitude: float
) -> None:
    _publish(
        redis,
        order_id,
        {"type": "location", "latitude": latitude, "longitude": longitude},
    )


def publish_status(redis: redis_lib.Redis, order_id: uuid.UUID, status: str) -> None:
    _publish(redis, order_id, {"type": "status", "status": status})
