"""State persistence for heartbeat monitoring (pending messages and Stathera counts)."""

from __future__ import annotations

import json
import time

from heartbeat.config import STATE_DIR, STATE_FILE, STATHERA_STATE_FILE


def load_pending() -> list[dict]:
    """Load pending message records from state file."""
    if not STATE_FILE.exists():
        return []
    try:
        return json.loads(STATE_FILE.read_text())
    except (json.JSONDecodeError, OSError):
        return []


def save_pending(records: list[dict]) -> None:
    """Save pending message records to state file."""
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    STATE_FILE.write_text(json.dumps(records))


def load_stathera_counts() -> dict:
    """Load previous Stathera anomaly counts for delta tracking."""
    if not STATHERA_STATE_FILE.exists():
        return {}
    try:
        return json.loads(STATHERA_STATE_FILE.read_text())
    except (json.JSONDecodeError, OSError):
        return {}


def save_stathera_counts(overlap_count: int, gap_count: int) -> None:
    """Save current Stathera anomaly counts for next heartbeat comparison."""
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    STATHERA_STATE_FILE.write_text(
        json.dumps(
            {
                "overlap_count": overlap_count,
                "gap_count": gap_count,
                "timestamp": time.time(),
            }
        )
    )
