"""PC-03: ``DjangoSettingsBridge.from_django()`` per-call cost.

`from_django()` snapshots `django.conf.settings` into a fresh
`DjangoSettingsBridge` instance. Per call:

  - 9 getattr reads against the Django settings object.
  - Two iterations (ALLOWED_HOSTS, INSTALLED_APPS) coerced to
    tuple.
  - Pydantic validation of the resulting fields.
  - The bridge instance itself.

Single-call use cases (`mgf-common explain` at startup) don't
care about the cost. Repeated calls (e.g. a diagnostic endpoint
returning the bridge per-request) would amplify the allocation
churn — pin it before it becomes a hot path.

Local baseline (Linux 6.17, Python 3.11, v0.2.0): ~175 µs/call.
Budget: 1 ms/call — ~5.7x cushion to absorb CI noise + pydantic-
version variance.

Marker: ``perf`` (registered in pyproject.toml). Excluded from
the default suite; run via ``pytest -m perf`` for the nightly
sweep.
"""

from __future__ import annotations

import time

import pytest

# Per-call budget: 1 ms. Generous against the ~175 µs local
# baseline — a 5.7x cushion. A breach signals a regression in
# either Django's settings access or pydantic's validation
# overhead; the bridge itself is a thin getattr-and-tuple shell.
_PER_CALL_BUDGET_US = 1000.0


@pytest.mark.perf
class TestSettingsBridgeConstruction:
    """Pin the per-call cost of `DjangoSettingsBridge.from_django()`."""

    def test_from_django_under_budget(self) -> None:
        from mgf.django._settings import DjangoSettingsBridge

        # Warm-up — pay first-call import/cache costs before the
        # measurement window opens.
        for _ in range(100):
            DjangoSettingsBridge.from_django()

        n = 1000
        start = time.perf_counter()
        for _ in range(n):
            DjangoSettingsBridge.from_django()
        elapsed = time.perf_counter() - start
        per_call_us = (elapsed / n) * 1_000_000

        assert per_call_us < _PER_CALL_BUDGET_US, (
            f"PC-03: DjangoSettingsBridge.from_django budget breach: "
            f"{per_call_us:.2f} µs/call (budget "
            f"{_PER_CALL_BUDGET_US:.0f} µs). Investigate "
            f"`from_django()` in src/mgf/django/_settings.py — likely "
            f"a regression in the getattr chain or pydantic validation."
        )
