"""Who the page is speaking to. The kit's /api/bw/me carries no display name
(a kit ask, logged in v8-feedback), so caddie reads it from the directory
through the kit's own userinfo call, caches it briefly, and falls back to a
name derived from the username. The directory being down must never blank a
page — this always answers.
"""

import re
import time

from app import bw_auth

_TTL = 600
_cache: dict[str, tuple[float, dict]] = {}


def name_from_username(u: str) -> str:
    """"darren.williams" -> "Darren": a person, not an account."""
    first = re.split(r"[._\s-]+", u or "")[0]
    return first[:1].upper() + first[1:] if first else ""


def of(username: str) -> dict:
    """{"first_name", "display_name"} for a username; cached per process."""
    now = time.monotonic()
    hit = _cache.get(username)
    if hit and hit[0] > now:
        return hit[1]
    first = last = ""
    try:
        info = bw_auth.userinfo(username) or {}
        first = (info.get("first") or "").strip()
        last = (info.get("last") or "").strip()
    except Exception:  # noqa: BLE001 — a directory hiccup must not blank a page
        pass
    first = first or name_from_username(username)
    prof = {"first_name": first, "display_name": f"{first} {last}".strip() or username}
    _cache[username] = (now + _TTL, prof)
    return prof
