"""PC-02: ``HmacWebhookVerifier.verify`` latency — baseline-relative (PF-01).

`HmacWebhookVerifier.verify` runs:

  1. Build a case-insensitive header dict.
  2. Three header reads + UUID-ish event_id capture.
  3. `int(ts_raw)` parse + replay-window check.
  4. SHA-256 over `<id>.<ts>.<body>` — payload-size dominated.
  5. base64-encode the digest.
  6. Iterate signature candidates + `hmac.compare_digest`.

SHA-256 is CPython C-coded; its per-call cost is linear in body size at roughly
200 MB/s, so the wall-clock is dominated by the body. The Python overhead (dict
comp, int parse, base64 encode) is fixed at ~5-10 µs.

Pinned per body size so a non-linear regression (a redundant pass over the
body, a re-encode, a regex over the payload) breaches the larger sizes first.
Each size is its OWN baseline metric in ``baselines.json`` (PF-03), compared
via ``baselines.assert_no_regression`` (PF-01/07) — NEVER an absolute
wall-clock budget (the PAPER-50 anti-pattern the old ``_PER_SIZE_BUDGETS_US``
table was).

Marker: ``perf`` (registered in pyproject.toml). Excluded from the default
suite; run via ``pytest -m perf``. Re-baseline on the reference tier
(``hw_tiers.md``): ``MGF_PERF_REBASELINE=1 pytest -m perf`` or
``mgf-fed bench rebaseline``.
"""

from __future__ import annotations

import base64
import hashlib
import hmac
from typing import TYPE_CHECKING

import pytest
from mgf.common.webhooks import decode_svix_secret

from mgf.fastapi.webhooks._verifier import HmacWebhookVerifier

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

pytestmark = pytest.mark.perf

# Body sizes pinned, with the metric key recorded per size. SHA-256 throughput
# dominates the larger sizes, so the worst-case non-linear regression shows
# there first.
_SIZES: tuple[tuple[int, str], ...] = (
    (1 * 1024, "hmac_verify_1kb_p50_us"),
    (16 * 1024, "hmac_verify_16kb_p50_us"),
    (64 * 1024, "hmac_verify_64kb_p50_us"),
    (256 * 1024, "hmac_verify_256kb_p50_us"),
)

# Use a wide replay window so synthetic test payloads with fixed timestamps
# don't fail the freshness check.
_REPLAY_WINDOW = 10**9
_SECRET = b"whsec_perf_test_secret"
_EVENT_ID = "evt_perf_test"
_TIMESTAMP = 1_700_000_000


def _make_signed_payload(body_size: int) -> tuple[dict[str, str], bytes]:
    """Build (headers, body) for a Svix-shape signed webhook."""
    body = b"x" * body_size
    signed = f"{_EVENT_ID}.{_TIMESTAMP}.".encode() + body
    digest = hmac.new(decode_svix_secret(_SECRET), signed, hashlib.sha256).digest()
    sig = "v1," + base64.b64encode(digest).decode("ascii")
    headers = {
        "svix-id": _EVENT_ID,
        "svix-timestamp": str(_TIMESTAMP),
        "svix-signature": sig,
    }
    return headers, body


@pytest.mark.perf
class TestHmacVerifierLatency:
    """Pin per-body-size verify() latency against a recorded baseline."""

    def test_verify_no_regression(self, bench: _Bench, baselines: Baselines) -> None:
        verifier = HmacWebhookVerifier(
            secret=_SECRET,
            replay_window_seconds=_REPLAY_WINDOW,
        )

        for body_size, metric in _SIZES:
            headers, body = _make_signed_payload(body_size)
            per_call_us = (
                bench.measure(
                    lambda h=headers, b=body: verifier.verify(h, b),
                    iterations=1000,
                    warmup=50,
                )
                * 1e6
            )
            baselines.assert_no_regression(
                metric,
                per_call_us,
                units="us",
                description=(
                    f"HmacWebhookVerifier.verify median over a {body_size}-byte body, "
                    f"1000 iterations"
                ),
            )
