"""PC-04: cold-import time for ``mgf.apiprobe``.

``mgf.apiprobe`` is the verification harness; consumers invoke it
from CLI (`mgf-apiprobe run suite.yml`). On invocation, the CLI
process pays the cold-import cost before any useful work starts.
A regression in startup time hurts the short-suite case the most —
a 200 ms startup on a 30 s suite is 0.7 %; on a 1 s smoke run it
is 20 %.

Cold-import drivers (cumulative, from `python -X importtime`):
  - `mgf.common`     ~18 ms (post mgf-common PC-01 fix)
  - `httpx` + h11    ~50 ms
  - `pydantic`       (cached if loaded by mgf.common; ~22 ms cold)
  - `mgf.apiprobe`   ~50 ms (the ~45-module submodule tree)

Local baseline (Linux 6.17, Python 3.12, v0.3.0): ~136 ms median
over 5 runs. Budget is set at 500 ms — a ~3.5x cushion to absorb
CI noise + slower hardware + Python-version drift.

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 subprocess
import sys
import time

import pytest

# Generous budget: measured ~136 ms locally; 500 ms accommodates
# CI noise + slower hardware. A breach means new eager imports
# crept into the `mgf.apiprobe` import tree — investigate
# `src/mgf/apiprobe/__init__.py` + the imports it pulls.
_COLD_IMPORT_BUDGET_MS = 500.0


@pytest.mark.perf
class TestColdImport:
    """Pin the cold-import wall-clock for ``mgf.apiprobe``."""

    def test_cold_import_under_budget(self) -> None:
        """Median of 5 fresh-subprocess imports stays under budget.

        Why median-of-5: the first run often pays first-time
        filesystem-cache costs and noisy CI runners drop outliers
        on either end. Taking the middle value of 5 gives a stable
        signal without false-positive on a single slow run.
        """
        runs: list[float] = []
        for _ in range(5):
            start = time.perf_counter()
            subprocess.run(
                [sys.executable, "-c", "import mgf.apiprobe"],
                check=True,
            )
            runs.append((time.perf_counter() - start) * 1000.0)

        runs.sort()
        median_ms = runs[2]

        assert median_ms < _COLD_IMPORT_BUDGET_MS, (
            f"PC-04: cold-import budget breach: median {median_ms:.0f} ms "
            f"over 5 runs (budget {_COLD_IMPORT_BUDGET_MS:.0f} ms). "
            f"All runs: {[f'{r:.0f}' for r in runs]} ms. "
            f"Investigate new eager imports in src/mgf/apiprobe/__init__.py "
            f"and the submodule tree; `python -X importtime -c "
            f"'import mgf.apiprobe'` shows the cumulative breakdown."
        )
