from __future__ import annotations

import json
from pathlib import Path
from tempfile import NamedTemporaryFile

from one_run.models import RunRuntime, RunStatus


def write_json_atomic(path: Path, data: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with NamedTemporaryFile("w", encoding="utf-8", delete=False, dir=path.parent) as tmp:
        json.dump(data, tmp, indent=2, default=str)
        tmp.write("\n")
        tmp_path = Path(tmp.name)
    tmp_path.replace(path)


def write_status(path: Path, status: RunStatus) -> None:
    write_json_atomic(path, status.model_dump(mode="json"))


def read_status(path: Path) -> RunStatus:
    payload = json.loads(path.read_text(encoding="utf-8"))
    return RunStatus.model_validate(payload)


def write_metadata(path: Path, metadata: dict) -> None:
    write_json_atomic(path, metadata)


def read_metadata(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def write_runtime(path: Path, runtime: RunRuntime) -> None:
    write_json_atomic(path, runtime.model_dump(mode="json"))


def read_runtime(path: Path) -> RunRuntime:
    payload = json.loads(path.read_text(encoding="utf-8"))
    return RunRuntime.model_validate(payload)
