"""Shared runtime helpers used by sync instrumentation.

Async decorators have moved to ``_codeflash_async_decorators.py``.
This module retains ``VerificationType``, ``get_run_tmp_file``, and
``extract_test_context_from_env`` which are still used by the sync
capture path (``_codeflash_capture.py``) and multiple test/analysis
modules.
"""

from __future__ import annotations

import os
from enum import Enum
from pathlib import Path
from tempfile import TemporaryDirectory


class VerificationType(str, Enum):
    """Type of correctness verification for captured test data."""

    FUNCTION_CALL = "function_call"
    INIT_STATE_FTO = "init_state_fto"
    INIT_STATE_HELPER = "init_state_helper"


def get_run_tmp_file(
    file_path: Path,
) -> Path:
    """Return a path inside a persistent per-run temporary directory.

    Uses ``CODEFLASH_RUN_TMPDIR`` if set (subprocess case), otherwise
    creates a new tmpdir and exports the env var so child processes
    share the same directory.
    """
    if not hasattr(get_run_tmp_file, "tmpdir"):
        env_dir = os.environ.get("CODEFLASH_RUN_TMPDIR")
        if env_dir and Path(env_dir).is_dir():
            get_run_tmp_file.tmpdir = env_dir  # type: ignore[attr-defined]
        else:
            td = TemporaryDirectory(prefix="codeflash_")
            get_run_tmp_file.tmpdir = td.name  # type: ignore[attr-defined]
            get_run_tmp_file.td_ref = td  # type: ignore[attr-defined]
            os.environ["CODEFLASH_RUN_TMPDIR"] = td.name
    return Path(get_run_tmp_file.tmpdir) / file_path  # type: ignore[attr-defined]


def extract_test_context_from_env() -> tuple[str, str | None, str]:
    """Read test module, class, and function names from environment variables."""
    test_module = os.environ["CODEFLASH_TEST_MODULE"]
    test_class = os.environ.get("CODEFLASH_TEST_CLASS", None)
    test_function = os.environ["CODEFLASH_TEST_FUNCTION"]

    if test_module and test_function:
        return (test_module, test_class or None, test_function)

    raise RuntimeError(  # noqa: TRY003
        "Test context environment variables not set - ensure tests are run through codeflash test runner"  # noqa: EM101
    )
