# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""EchoRefine metrics persistence — load/save cycle metrics JSON."""
import json
import os
from pathlib import Path

from pulse.core.brain_utils import STATE_DIR

METRICS_FILE = STATE_DIR / "health" / "echo_refine_metrics.json"

_EMPTY: dict = {
    "last_run": "", "runs": 0, "entries_scanned": 0,
    "golden_aligned": 0, "constraint_conflicts": 0, "domain_sensitivity": {},
}


def _load_metrics() -> dict:
    if not METRICS_FILE.exists():
        return dict(_EMPTY)
    try:
        return json.loads(METRICS_FILE.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError):
        return dict(_EMPTY)


def _save_metrics(metrics: dict) -> None:
    METRICS_FILE.parent.mkdir(parents=True, exist_ok=True)
    tmp = METRICS_FILE.with_suffix(".tmp")
    try:
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(metrics, f, indent=2, ensure_ascii=False)
        os.replace(str(tmp), str(METRICS_FILE))
    except OSError:
        if tmp.exists():
            tmp.unlink()
