"""PC-05: ``IpAllowlist.__call__`` CIDR scan cost — baseline-relative (PF-01).

The dependency iterates ``self._networks`` checking ``client_ip in network``.
For a small allowlist (loopback only — 2 entries) the per-request cost is
sub-µs. For a "trust all our prod ranges" allowlist (100+ CIDRs), the
per-request scan compounds.

Pinned: a 100-CIDR allowlist, hitting the LAST CIDR (worst-case scan, no
early-match short-circuit), compared to the recorded baseline in
``baselines.json`` (PF-01/07) — NOT the old absolute 50 µs budget.

Marker: ``perf``. Run via ``pytest -m perf``.
"""

from __future__ import annotations

from typing import TYPE_CHECKING
from unittest.mock import Mock

import pytest

from mgf.fastapi.security import IpAllowlist

if TYPE_CHECKING:
    from tests.perf.conftest import Baselines, _Bench

pytestmark = pytest.mark.perf


def _make_request(client_host: str) -> Mock:
    request = Mock()
    request.client = Mock()
    request.client.host = client_host
    request.headers = {}
    return request


def test_ipallowlist_100_cidr_no_regression(bench: _Bench, baselines: Baselines) -> None:
    # 100 CIDRs — realistic upper bound for "all our prod /16s".
    cidrs = [f"10.{i}.0.0/16" for i in range(100)]
    allowlist = IpAllowlist(cidrs=cidrs)

    # Hit the LAST CIDR so we exercise the worst-case scan (no short-circuit
    # on early match).
    request = _make_request("10.99.0.1")

    per_call_us = bench.measure(lambda: allowlist(request), iterations=1000, warmup=50) * 1e6
    baselines.assert_no_regression(
        "ip_allowlist_100cidr_p50_us",
        per_call_us,
        units="us",
        description="IpAllowlist worst-case scan over 100 CIDRs (last-match), median over 1000",
    )
