"""Pin: tests/public_surface/* MUST NOT import ``mgf.common._*``.

The discipline this directory enforces is "test as the user
sees it." Users only import from the public ``mgf.common.*``
surface — they don't reach into ``_lifecycle``, ``_identity``,
``_env_source``, etc. If a public-surface test imports a
private module it has lost the user-perspective property and
becomes another internals-aware test.

This pin walks the AST of every ``test_*.py`` in this directory
on every test run; any ``import mgf.common._x`` or ``from
mgf.common._x import y`` fails the suite with a clear message.

Allowed imports, for reference:
- ``mgf.common`` (the top-level package)
- ``mgf.common.exceptions`` / ``config`` / ``observability`` /
  ``settings`` / ``typing`` / ``progress`` / ``progress.asyncio`` /
  ``vault`` / ``cli`` / ``registry`` (every public subpackage)
- Anything outside ``mgf.common.*`` (stdlib, pytest, etc.)
"""

from __future__ import annotations

import ast
from pathlib import Path

import pytest

PUBLIC_SURFACE_DIR = Path(__file__).resolve().parent


def _iter_test_files() -> list[Path]:
    """Every ``test_*.py`` in this directory except this pin file."""
    return sorted(
        p for p in PUBLIC_SURFACE_DIR.glob("test_*.py") if p.name != "test_no_private_imports.py"
    )


def _imported_modules(py_file: Path) -> list[tuple[int, str]]:
    """Return ``(lineno, module_name)`` for every import node."""
    tree = ast.parse(py_file.read_text(encoding="utf-8"))
    out: list[tuple[int, str]] = []
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom):
            if node.module is not None:
                out.append((node.lineno, node.module))
        elif isinstance(node, ast.Import):
            for alias in node.names:
                out.append((node.lineno, alias.name))
    return out


@pytest.mark.parametrize(
    "test_file",
    _iter_test_files(),
    ids=lambda p: p.name,
)
def test_file_imports_only_public_surface(test_file: Path) -> None:
    """For each test file, walk imports; reject ``mgf.common._*``."""
    violations: list[str] = []
    for lineno, module in _imported_modules(test_file):
        if module.startswith("mgf.common._"):
            violations.append(f"  line {lineno}: {module}")

    if violations:
        msg = (
            f"{test_file.name} imports private mgf.common._* modules — "
            f"public-surface tests MUST use only the documented public "
            f"API. Move the test to tests/unit/ if it genuinely needs "
            f"internal access, or rewrite to use the public path.\n" + "\n".join(violations)
        )
        raise AssertionError(msg)


def test_pin_actually_walks_files() -> None:
    """Sanity: the parametrize discovery actually finds files.

    Catches the empty-discovery failure mode where the pin
    silently passes 0 cases (giving false confidence that the
    rule is enforced when it's not running at all).
    """
    files = _iter_test_files()
    assert len(files) >= 1, (
        "Public-surface test discovery returned 0 files — the "
        "import-rule pin would silently pass against an empty set. "
        "Add at least one test_*.py here, or fix the discovery glob."
    )
