from __future__ import annotations

import importlib.util
import sys
from pathlib import Path

_CHECK_DEPS_PATH = Path(__file__).resolve().parents[2] / "scripts" / "check_deps.py"
_spec = importlib.util.spec_from_file_location("check_deps", _CHECK_DEPS_PATH)
assert _spec and _spec.loader
check_deps = importlib.util.module_from_spec(_spec)
sys.modules[_spec.name] = check_deps
_spec.loader.exec_module(check_deps)


def _write(root: Path, rel: str, content: str) -> None:
    path = root / rel
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8")


def test_dependency_gate_allows_boundary_import_core(tmp_path: Path) -> None:
    src_root = tmp_path / "src"
    v1_root = src_root / "crystflux" / "v1"

    _write(v1_root, "core/a.py", "from __future__ import annotations\n")
    _write(
        v1_root,
        "boundary/b.py",
        "from __future__ import annotations\nfrom ..core.value_api import ValueAPI\n",
    )
    _write(
        v1_root,
        "adapters/c.py",
        "from __future__ import annotations\nfrom ..boundary.event_schema import DesireEvent\n",
    )

    violations, parse_errors = check_deps.scan_v1(v1_root=v1_root, src_root=src_root)
    assert parse_errors == []
    assert violations == []


def test_dependency_gate_blocks_core_import_boundary_relative(tmp_path: Path) -> None:
    src_root = tmp_path / "src"
    v1_root = src_root / "crystflux" / "v1"

    _write(
        v1_root,
        "core/x.py",
        "from __future__ import annotations\nfrom ..boundary.event_schema import DesireEvent\n",
    )

    violations, parse_errors = check_deps.scan_v1(v1_root=v1_root, src_root=src_root)
    assert parse_errors == []
    assert len(violations) == 1
    assert violations[0].importer_layer == "core"
    assert violations[0].imported_module.startswith("crystflux.v1.boundary")
    assert violations[0].rule == "core must not import boundary"


def test_dependency_gate_blocks_boundary_import_adapters_absolute(tmp_path: Path) -> None:
    src_root = tmp_path / "src"
    v1_root = src_root / "crystflux" / "v1"

    _write(
        v1_root,
        "boundary/y.py",
        "from __future__ import annotations\nimport crystflux.v1.adapters.crystallizer_impl\n",
    )

    violations, parse_errors = check_deps.scan_v1(v1_root=v1_root, src_root=src_root)
    assert parse_errors == []
    assert len(violations) == 1
    assert violations[0].importer_layer == "boundary"
    assert violations[0].imported_module.startswith("crystflux.v1.adapters")
    assert violations[0].rule == "boundary must not import adapters"

