"""P1 startup guard: /internal/auth/email module must refuse to import in
production when the HMAC secret is unset.

Without this guard, `_verify_signature` would silently return False for every
incoming request, so BA would correctly see 401s — but auth emails would be
silently dropping in the wild with no actionable signal.
"""

from __future__ import annotations

import importlib
import sys

import pytest

from app.config import get_settings


def _reload_module() -> None:
    """Force re-evaluation of the module's import-time guard."""
    get_settings.cache_clear()
    if "app.routers.internal_email" in sys.modules:
        del sys.modules["app.routers.internal_email"]
    importlib.import_module("app.routers.internal_email")


def test_module_imports_in_development_without_secret(monkeypatch: pytest.MonkeyPatch) -> None:
    """Dev environment may run without the HMAC secret (auth emails log to
    stdout instead of dispatching). The startup guard must not fire."""
    monkeypatch.setenv("ENVIRONMENT", "development")
    monkeypatch.delenv("INTERNAL_EMAIL_SHARED_SECRET", raising=False)
    _reload_module()


def test_module_refuses_to_import_in_production_without_secret(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setenv("ENVIRONMENT", "production")
    monkeypatch.delenv("INTERNAL_EMAIL_SHARED_SECRET", raising=False)
    with pytest.raises(RuntimeError, match="INTERNAL_EMAIL_SHARED_SECRET"):
        _reload_module()


def test_module_imports_in_production_when_secret_is_set(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setenv("ENVIRONMENT", "production")
    monkeypatch.setenv("INTERNAL_EMAIL_SHARED_SECRET", "real-secret-bytes")
    _reload_module()
