from __future__ import annotations

import os
import sys
import types
from pathlib import Path


def _ensure_mvp_py_on_path() -> None:
    repo_root = Path(__file__).resolve().parents[4]
    py_root = repo_root / "src" / "mvp" / "py"
    if str(py_root) not in sys.path:
        sys.path.insert(0, str(py_root))


def _install_ray_stub() -> None:
    if "ray" in sys.modules:
        return

    ray = types.ModuleType("ray")
    ray.__path__ = []  # type: ignore[attr-defined]

    def _init(*args: object, **kwargs: object) -> None:
        return None

    ray.init = _init  # type: ignore[attr-defined]
    ray.cluster_resources = lambda: {}  # type: ignore[attr-defined]
    ray.available_resources = lambda: {}  # type: ignore[attr-defined]
    sys.modules["ray"] = ray

    job_submission = types.ModuleType("ray.job_submission")
    job_submission.__path__ = []  # type: ignore[attr-defined]

    class JobSubmissionClient:  # minimal stub; tests can monkeypatch methods
        def __init__(self, address: str):
            self.address = address

        def submit_job(self, **kwargs: object) -> str:
            raise NotImplementedError

        def get_job_status(self, submission_id: str) -> str:
            raise NotImplementedError

        def stop_job(self, submission_id: str) -> bool:
            raise NotImplementedError

        def get_job_logs(self, submission_id: str) -> str:
            raise NotImplementedError

        def list_jobs(self) -> list[object]:
            return []

    job_submission.JobSubmissionClient = JobSubmissionClient  # type: ignore[attr-defined]
    sys.modules["ray.job_submission"] = job_submission
    ray.job_submission = job_submission  # type: ignore[attr-defined]

    private = types.ModuleType("ray._private")
    private.__path__ = []  # type: ignore[attr-defined]
    state = types.ModuleType("ray._private.state")

    def available_resources_per_node() -> dict[str, object]:
        return {}

    state.available_resources_per_node = available_resources_per_node  # type: ignore[attr-defined]
    sys.modules["ray._private"] = private
    sys.modules["ray._private.state"] = state
    private.state = state  # type: ignore[attr-defined]
    ray._private = private  # type: ignore[attr-defined]


_ensure_mvp_py_on_path()
_install_ray_stub()


def pytest_configure(config: object) -> None:
    os.environ.setdefault("PYTHONUTF8", "1")

