"""Smoke test: every example under ``examples/`` MUST run cleanly.

Regression guard against API drift breaking the documentation.
The discovery glob (``examples/[0-9][0-9]_*/[0-9][0-9]_*.py``)
picks up new examples automatically, so adding an example is
zero-config.

Each example runs in a fresh subprocess for full isolation —
process-global state (``logging.root.handlers``, OTel
``TracerProvider``, ``sys.excepthook``, env vars) cannot leak
between examples. Cost: ~50 ms per script + Python startup;
the full sweep finishes well under the 5 s soft budget.
"""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

import pytest

EXAMPLES_DIR = Path(__file__).resolve().parent.parent.parent / "examples"


def _example_files() -> list[Path]:
    """Discover every layered example by glob pattern."""
    return sorted(EXAMPLES_DIR.glob("[0-9][0-9]_*/[0-9][0-9]_*.py"))


@pytest.mark.parametrize(
    "example_path",
    _example_files(),
    ids=lambda p: f"{p.parent.name}/{p.stem}",
)
def test_example_runs_without_error(example_path: Path) -> None:
    """Each example MUST exit 0 when invoked as ``python <path>``."""
    result = subprocess.run(
        [sys.executable, str(example_path)],
        capture_output=True,
        text=True,
        timeout=30,
        cwd=EXAMPLES_DIR.parent,  # repo root, so imports resolve
    )
    assert result.returncode == 0, (
        f"\n{example_path.relative_to(EXAMPLES_DIR.parent)} "
        f"exited with {result.returncode}\n"
        f"--- stdout ---\n{result.stdout}\n"
        f"--- stderr ---\n{result.stderr}"
    )


def test_examples_dir_exists_and_is_populated() -> None:
    """Sanity: the discovery glob found at least one example.

    A failing run of ``test_example_runs_without_error`` parameterised
    with an empty list silently produces zero tests — this guard
    fails loudly if the glob misses everything (e.g., directory
    renamed without updating the pattern).
    """
    examples = _example_files()
    assert examples, (
        f"no examples discovered under {EXAMPLES_DIR}; "
        f"glob 'examples/[0-9][0-9]_*/[0-9][0-9]_*.py' matched nothing"
    )
    # Six topics x three layers = 18 expected today.
    assert len(examples) >= 18, (
        f"expected at least 18 examples (6 topics x 3 layers), "
        f"found {len(examples)}: "
        f"{[p.relative_to(EXAMPLES_DIR.parent).as_posix() for p in examples]}"
    )
