"""Sidecar health checks for heartbeat monitoring."""

from __future__ import annotations

import logging
import time
from pathlib import Path

logger = logging.getLogger("health-heartbeat")

_DEAD_LETTER_DIR = Path("/tmp/opendeviationbar-dead-letter")


def check_dead_letters(results: dict[str, bool | str]) -> None:
    """Count dead-letter files and report oldest age.

    Dead letters accumulate when ClickHouse writes fail. A growing pile
    indicates a persistent write problem. Charon replays them every 5 min,
    so a healthy system should have 0 files most of the time.
    """
    if not _DEAD_LETTER_DIR.exists():
        results["dead_letter_count"] = "0"
        return

    files = list(_DEAD_LETTER_DIR.glob("*.parquet"))
    results["dead_letter_count"] = str(len(files))

    if not files:
        return

    # Oldest file age
    oldest_mtime = min(f.stat().st_mtime for f in files)
    age_h = (time.time() - oldest_mtime) / 3600
    if age_h < 1:
        results["dead_letter_oldest"] = f"{age_h * 60:.0f}m"
    elif age_h < 24:
        results["dead_letter_oldest"] = f"{age_h:.1f}h"
    else:
        results["dead_letter_oldest"] = f"{age_h / 24:.1f}d"
