"""Append-only JSONL telemetry log for checksum operations.

All checksum verify/skip/fail/retry events from the seeder and integrity sweep
are recorded here for post-mortem analysis and heartbeat 24h failure detection.

Log path: ``~/.cache/opendeviationbar/checksum-telemetry.jsonl``

Per feedback-local-telemetry-log.md: wire ALL telemetry to local log file.
"""

from __future__ import annotations

import json
import logging
from datetime import UTC, datetime
from pathlib import Path

logger = logging.getLogger(__name__)

_LOG_PATH = Path.home() / ".cache" / "opendeviationbar" / "checksum-telemetry.jsonl"


def log_checksum_event(
    event: str,
    symbol: str,
    date: str,
    *,
    expected_hash: str | None = None,
    actual_hash: str | None = None,
    source: str | None = None,
    reason: str | None = None,
) -> None:
    """Append a checksum operation event to the JSONL telemetry log.

    Parameters
    ----------
    event
        Event type: ``"verify_pass"``, ``"verify_fail"``, ``"verify_skip"``,
        ``"verify_retry"``, ``"sweep_pass"``, ``"sweep_fail"``, ``"sweep_skip"``.
    symbol
        Trading pair symbol (e.g., ``"BTCUSDT"``).
    date
        ISO date string ``YYYY-MM-DD``.
    expected_hash
        Expected SHA-256 hex digest (truncated or full).
    actual_hash
        Actual computed SHA-256 hex digest (truncated or full).
    source
        Origin of the operation: ``"seeder"`` or ``"sweep"``.
    reason
        Reason for skip or failure.

    Notes
    -----
    This function NEVER raises. All errors are suppressed to debug-level logging
    so that telemetry cannot crash the caller (seeder, sweep, or heartbeat).
    """
    try:
        entry: dict[str, str] = {
            "timestamp": datetime.now(UTC).isoformat(),
            "event": event,
            "symbol": symbol,
            "date": date,
        }
        if expected_hash is not None:
            entry["expected_hash"] = expected_hash
        if actual_hash is not None:
            entry["actual_hash"] = actual_hash
        if source is not None:
            entry["source"] = source
        if reason is not None:
            entry["reason"] = reason

        _LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
        with _LOG_PATH.open("a") as f:
            f.write(json.dumps(entry) + "\n")
    except Exception:
        logger.debug("Failed to write checksum telemetry event", exc_info=True)
