"""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,
    *,
    pipeline_gap_count: int | None = None,
    exchange_gap_count: int | None = None,
) -> None:
    """Save current Stathera anomaly counts for next heartbeat comparison."""
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    data: dict = {
        "overlap_count": overlap_count,
        "gap_count": gap_count,
        "timestamp": time.time(),
    }
    if pipeline_gap_count is not None:
        data["pipeline_gap_count"] = pipeline_gap_count
    if exchange_gap_count is not None:
        data["exchange_gap_count"] = exchange_gap_count
    STATHERA_STATE_FILE.write_text(json.dumps(data))
