"""Run record storage helpers for staged extraction from `hiveos.observe`."""

from __future__ import annotations

import json


def runs_dir(*, trace_home):
    path = trace_home() / "runs"
    path.mkdir(parents=True, exist_ok=True)
    return path


def run_file(run_id, *, trace_home):
    safe = str(run_id or "").replace(":", "_")
    return runs_dir(trace_home=trace_home) / f"{safe}.json"


def persist_run_record(record, *, trace_home):
    path = run_file((record or {}).get("run_id"), trace_home=trace_home)
    path.write_text(json.dumps(record or {}, indent=2), encoding="utf-8")
    return path


def read_run_record(run_id, *, trace_home):
    path = run_file(run_id, trace_home=trace_home)
    if not path.exists():
        return None
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return None


def list_run_records(*, trace_home, limit=100):
    records = []
    for path in runs_dir(trace_home=trace_home).glob("*.json"):
        try:
            record = json.loads(path.read_text(encoding="utf-8"))
            if isinstance(record, dict):
                records.append(record)
        except Exception:
            continue
    records.sort(key=lambda item: int(item.get("started_at_ms") or 0), reverse=True)
    return records[: max(1, min(1000, int(limit or 100)))]


def list_all_run_records(*, trace_home):
    records = []
    for path in runs_dir(trace_home=trace_home).glob("*.json"):
        try:
            record = json.loads(path.read_text(encoding="utf-8"))
            if isinstance(record, dict):
                records.append(record)
        except Exception:
            continue
    records.sort(key=lambda item: int(item.get("started_at_ms") or 0), reverse=True)
    return records


def touch_run_record(run_id, *, trace_home, now_ms, read_record, persist_record, **fields):
    run_key = str(run_id or "").strip()
    if not run_key:
        return None
    record = read_record(run_key)
    if not record:
        return None
    updates = dict(fields or {})
    updates["last_update_ms"] = int(now_ms())
    record.update(updates)
    persist_record(record)
    return record

