"""Studio access tokens: HMAC(design name) under a server-held secret.

Only the server can mint them (STUDIO_SECRET lives in .env and never leaves
the box); the Telegram bot embeds one in each customer's studio link. A token
unlocks exactly one design's data and files; the admin token ("__admin__")
unlocks the internal review/eval pages.

If STUDIO_SECRET is missing on first run, serve.py generates one and appends
it to .env. Without a secret set, auth is OPEN (local development).
"""

from __future__ import annotations

import base64
import hashlib
import hmac
import os


def secret() -> str:
    return os.environ.get("STUDIO_SECRET", "")


def make_token(design: str) -> str:
    if not secret():
        return ""
    mac = hmac.new(secret().encode(), design.encode(), hashlib.sha256).digest()
    return base64.urlsafe_b64encode(mac).decode().rstrip("=")[:22]


def token_ok(design: str, token: str | None) -> bool:
    if not secret():
        return True                      # auth disabled: open local mode
    if not token:
        return False
    for want in (make_token(design), make_token("__admin__")):
        if want and hmac.compare_digest(want, token):
            return True
    return False
