"""TURN credential generation using the TURN REST API (RFC 7635).

Generates time-limited HMAC-SHA1 credentials that coturn validates against
a shared static-auth-secret. Credentials expire automatically — no per-user
config on the TURN server needed.

Env vars:
    TURN_SERVER  — TURN server URI, e.g. "turn:turn.roohai.com:443"
    TURN_SECRET  — Shared secret matching coturn's --static-auth-secret
    TURN_TTL     — Credential TTL in seconds (default: 86400 = 24h)
    STUN_SERVER  — Optional STUN URI (default: "stun:stun.l.google.com:19302")
"""

import base64
import hashlib
import hmac
import os
import time


def get_ice_servers() -> list[dict]:
    """Return ICE server configuration for WebRTC clients.

    If TURN_SERVER and TURN_SECRET are set, generates time-limited
    HMAC credentials. Always includes a STUN server for direct
    connectivity attempts.
    """
    stun = os.environ.get("STUN_SERVER", "stun:stun.l.google.com:19302")
    servers: list[dict] = [{"urls": stun}]

    turn_server = os.environ.get("TURN_SERVER", "")
    turn_secret = os.environ.get("TURN_SECRET", "")

    if turn_server and turn_secret:
        ttl = int(os.environ.get("TURN_TTL", "86400"))
        servers.append(_generate_turn_credentials(turn_server, turn_secret, ttl))

    return servers


def _generate_turn_credentials(turn_uri: str, secret: str, ttl: int) -> dict:
    """Generate time-limited TURN credentials (TURN REST API).

    Username format: "{expiry_timestamp}:{random_id}"
    Credential: HMAC-SHA1(secret, username) base64-encoded

    coturn validates: hmac(static-auth-secret, username) == credential
    and checks that the timestamp hasn't expired.
    """
    expiry = int(time.time()) + ttl
    username = f"{expiry}:roohai"

    mac = hmac.new(secret.encode(), username.encode(), hashlib.sha1)
    credential = base64.b64encode(mac.digest()).decode()

    return {
        "urls": [turn_uri, turn_uri.replace("turn:", "turns:", 1)],
        "username": username,
        "credential": credential,
    }
