import json
import os
import time

# Path where response.json is mounted inside the container
_STUB_DATA_PATH = os.getenv("STUB_DATA_PATH", "/app/stub_data/response.json")

_stub_measurements: list | None = None


def _load_stub_data() -> list:
    global _stub_measurements
    if _stub_measurements is None:
        if os.path.exists(_STUB_DATA_PATH):
            with open(_STUB_DATA_PATH, encoding="utf-8") as fh:
                _stub_measurements = json.load(fh)
        else:
            _stub_measurements = []
    return _stub_measurements


def start_measurement(**kwargs):
    time.sleep(1)
    measurements = _load_stub_data()
    meas_id = measurements[0]["measurement_id"] if measurements else "meas_stub"
    return {"measurement_id": meas_id, "status": "ok"}


def wait_data_ready(**kwargs):
    time.sleep(1)
    return {"data_ready": True}


def fetch_data(format="h5", **kwargs):
    time.sleep(1)
    measurements = _load_stub_data()
    if measurements:
        # Wrap in a list so the spectroscopy service and GUI range-detector
        # can find averaging_num / data_num / channel_num correctly
        return {"data": measurements[:1]}
    return {"raw_file": f"raw_stub.{format}"}


def run_reconstruction(sequence_name="linear", digit="2d", phase_shift=False, **kwargs):
    time.sleep(1)
    return {"session_id": "sess_stub", "status": "done", "sequence": sequence_name}


TASK_REGISTRY = {
    "start_measurement": start_measurement,
    "wait_data_ready": wait_data_ready,
    "fetch_data": fetch_data,
    "run_reconstruction": run_reconstruction,
}
