"""Runtime and atomic evidence helpers for the disposable v1.4 CLI."""

from __future__ import annotations

import importlib.util
import json
import os
import shutil
import sys
from pathlib import Path
from typing import TypeAlias

JsonScalar: TypeAlias = str | int | float | bool | None
JsonValue: TypeAlias = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"]


class CandidateRuntimeUnavailableError(RuntimeError):
    """The candidate-bound project interpreter is unavailable."""


def ensure_project_runtime(repository: Path) -> None:
    """Re-execute PEP-723 isolation in the candidate project runtime."""
    if (
        importlib.util.find_spec("anyio") is not None
        and importlib.util.find_spec("telegram") is not None
    ):
        return
    uv = shutil.which("uv")
    if os.environ.get("NUTRICOACH_V140_REEXEC") == "1" or uv is None:
        raise CandidateRuntimeUnavailableError
    environment = dict(os.environ)
    environment["NUTRICOACH_V140_REEXEC"] = "1"
    script = repository / "scripts/run_nutricoach_v140_disposable_e2e.py"
    os.execvpe(
        uv,
        [uv, "run", "--offline", "--extra", "messaging", "python", str(script), *sys.argv[1:]],
        environment,
    )


def write_json(path: Path, value: JsonValue) -> None:
    """Atomically write canonical compact JSON evidence."""
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    _ = temporary.write_text(
        json.dumps(value, sort_keys=True, separators=(",", ":")), encoding="utf-8",
    )
    _ = temporary.replace(path)
