"""Auth policy read from the environment — deliberately NOT pydantic
settings: these are read lazily at call time (like the kit's bw_auth env
handling) so tests can flip them per-case with monkeypatch and the
startup guard sees the real current env. (Mirrors /srv/apps/with.)
"""

import os


def app_env() -> str:
    """Deployment flavor. The container compose sets APP_ENV=production;
    anything else (dev/test/unset-on-a-laptop) counts as non-prod.
    Defaults to "production" so a missing flag can never ENABLE dev-only
    behavior."""
    return (os.environ.get("APP_ENV") or "production").strip().lower()


def is_production() -> bool:
    return app_env() == "production"


def dev_user() -> str:
    """AUTH_DEV_USER — the local-test identity stub. When set in a
    NON-production env, requests resolve to this username without a
    session (so the app can be driven/screenshotted overnight without a
    real BW login). Production refuses to start with it set."""
    return (os.environ.get("AUTH_DEV_USER") or "").strip()


def dev_stub_active() -> bool:
    return bool(dev_user()) and not is_production()


def enforce_dev_stub_policy() -> None:
    """AUTH_DEV_USER set in a production env -> refuse to start (mirrors
    with's T-AZ-043). Called from create_app(), so the container dies
    loudly at boot rather than serving with an identity backdoor."""
    if is_production() and dev_user():
        raise RuntimeError(
            "AUTH_DEV_USER is set but APP_ENV=production — the dev identity "
            "stub is a local-test convenience and must never run in "
            "production. Unset AUTH_DEV_USER."
        )
