# -*- coding: utf-8 -*-
"""Top-level test: helper.selftest() + dispatch.py shim re-export verification.

task-2646 E10 — verifies (a) utils.callback_registration.selftest() passes and
(b) the dispatch.py SHIM file (NOT the dispatch/ package) re-exports the
single-helper symbols, satisfying the "dispatch.py path uses the same helper"
결선 contract.

Notes
-----
* Python resolves ``import dispatch`` to the package ``dispatch/__init__.py``
  rather than the ``dispatch.py`` shim when both coexist, so this test loads
  the shim explicitly via ``importlib.util.spec_from_file_location`` to assert
  the shim itself carries the wiring.
* The worktree root must be first on ``sys.path`` so that
  ``utils.callback_registration`` (new task-2646 module) resolves from the
  worktree and not from the live workspace which lacks it. We inject this at
  file load time because ``tests/conftest.py`` ahead-of-us inserts the LIVE
  workspace path; we must precede it.
"""
from __future__ import annotations

import importlib.util
import sys
from pathlib import Path

# ── sys.path: worktree root must come first ────────────────────────────────
_WORKTREE_ROOT = Path(__file__).resolve().parents[1]
_WORKTREE_ROOT_STR = str(_WORKTREE_ROOT)
if _WORKTREE_ROOT_STR in sys.path:
    sys.path.remove(_WORKTREE_ROOT_STR)
sys.path.insert(0, _WORKTREE_ROOT_STR)

# Purge any utils/* already loaded from the live workspace so the worktree
# version takes precedence on next import.
for _mod_name in list(sys.modules.keys()):
    if _mod_name == "utils" or _mod_name.startswith("utils."):
        _utils_file = getattr(sys.modules[_mod_name], "__file__", "") or ""
        if _WORKTREE_ROOT_STR not in _utils_file:
            sys.modules.pop(_mod_name, None)


_DISPATCH_PY_SHIM = _WORKTREE_ROOT / "dispatch.py"


def _load_dispatch_shim_module():
    """Load the dispatch.py SHIM file explicitly (not the dispatch/ package).

    Returns the loaded module object. Cached on the function attribute.
    """
    cached = getattr(_load_dispatch_shim_module, "_cached", None)
    if cached is not None:
        return cached
    spec = importlib.util.spec_from_file_location(
        "_task2646_dispatch_shim", str(_DISPATCH_PY_SHIM)
    )
    assert spec is not None and spec.loader is not None
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    _load_dispatch_shim_module._cached = mod
    return mod


class TestHelperSelftest:
    """helper.selftest() must pass all internal checks."""

    def test_selftest_passes(self):
        from utils.callback_registration import selftest
        result = selftest()
        assert result["ok"], f"selftest() failed with {result['failures']!r}"

    def test_selftest_returns_schema(self):
        from utils.callback_registration import selftest, HELPER_SCHEMA
        result = selftest()
        assert result["schema"] == HELPER_SCHEMA

    def test_selftest_no_failures(self):
        from utils.callback_registration import selftest
        result = selftest()
        assert result["failures"] == [], (
            f"selftest failures: {result['failures']}"
        )

    def test_selftest_tests_run_count(self):
        from utils.callback_registration import selftest
        result = selftest()
        assert result["tests_run"] >= 5


class TestDispatchPyShimReExport:
    """dispatch.py SHIM file must re-export the helper (task-2646 ANCHOR-2).

    These tests assert the wiring on the SHIM file specifically — ``import
    dispatch`` resolves to the package and would mask a missing shim wiring.
    We therefore load the shim file directly with importlib.
    """

    def test_dispatch_py_shim_file_has_helper_import_text(self):
        """Text-grep proof: dispatch.py SHIM source contains the helper import."""
        src = _DISPATCH_PY_SHIM.read_text(encoding="utf-8")
        assert "from utils.callback_registration import" in src, (
            "dispatch.py SHIM must contain the helper import line "
            "(task-2646 ANCHOR-2 wiring)."
        )
        assert "register_callback as register_callback_via_helper" in src
        assert "verify_actual_owner as verify_actual_owner_via_helper" in src
        assert "HELPER_SCHEMA as CALLBACK_REGISTRATION_HELPER_SCHEMA" in src

    def test_dispatch_shim_module_exposes_register_callback_via_helper(self):
        shim = _load_dispatch_shim_module()
        assert hasattr(shim, "register_callback_via_helper"), (
            "dispatch.py SHIM must re-export register_callback_via_helper"
        )

    def test_dispatch_shim_module_exposes_verify_actual_owner_via_helper(self):
        shim = _load_dispatch_shim_module()
        assert hasattr(shim, "verify_actual_owner_via_helper"), (
            "dispatch.py SHIM must re-export verify_actual_owner_via_helper"
        )

    def test_dispatch_shim_module_exposes_helper_schema(self):
        shim = _load_dispatch_shim_module()
        assert hasattr(shim, "CALLBACK_REGISTRATION_HELPER_SCHEMA"), (
            "dispatch.py SHIM must re-export CALLBACK_REGISTRATION_HELPER_SCHEMA"
        )

    def test_dispatch_shim_helper_schema_value_matches(self):
        from utils.callback_registration import HELPER_SCHEMA
        shim = _load_dispatch_shim_module()
        assert shim.CALLBACK_REGISTRATION_HELPER_SCHEMA == HELPER_SCHEMA

    def test_dispatch_shim_register_callback_via_helper_callable(self):
        shim = _load_dispatch_shim_module()
        assert callable(shim.register_callback_via_helper)

    def test_dispatch_shim_verify_actual_owner_via_helper_callable(self):
        shim = _load_dispatch_shim_module()
        assert callable(shim.verify_actual_owner_via_helper)


class TestHelperSchemaConstant:
    """HELPER_SCHEMA and ANU_KEY constants."""

    def test_helper_schema_value(self):
        from utils.callback_registration import HELPER_SCHEMA
        assert HELPER_SCHEMA == "utils.callback_registration.v1"

    def test_anu_key_constant(self):
        from utils.callback_registration import ANU_KEY
        assert ANU_KEY == "c119085addb0f8b7"
