"""Warn independently when the daily brief has gone silent."""

from __future__ import annotations

import json
from datetime import datetime, timedelta, timezone

from error_reporting import record_failure
from notify import ROOT, send


LAST_BRIEF_PATH = ROOT / "state" / "last_brief.json"
HEARTBEAT_LOG = ROOT / "state" / "heartbeat.jsonl"


def _receipt(verdict: str, detail: str) -> None:
    """Leave a trace, every run, whether or not it had anything to say.

    The 2026-07-29 injected-silence drill proved the heartbeat alerts — but only by
    inference from a scheduled task's exit code, because the watchman ran unattended
    and left nothing behind. A watchman whose only evidence is "it exited 0" cannot
    be audited, and this is the component whose whole job is to be trusted when
    everything else has gone quiet.

    One line per run. No message bodies, no secrets — a verdict and a timestamp.
    """
    HEARTBEAT_LOG.parent.mkdir(parents=True, exist_ok=True)
    record = {
        "at": datetime.now(timezone.utc).isoformat(),
        "verdict": verdict,
        "detail": detail,
    }
    with HEARTBEAT_LOG.open("a", encoding="utf-8", newline="\n") as handle:
        handle.write(json.dumps(record) + "\n")


def main() -> int:
    last_success: datetime | None = None
    state_error: str | None = None
    if LAST_BRIEF_PATH.exists():
        try:
            value = json.loads(LAST_BRIEF_PATH.read_text(encoding="utf-8"))
            last_success = datetime.fromisoformat(value["sent_at_utc"])
        except (KeyError, ValueError, json.JSONDecodeError) as error:
            last_success = None
            state_error = record_failure("Heartbeat state read failed", error)

    now = datetime.now(timezone.utc)
    if last_success and now - last_success <= timedelta(hours=26):
        age = (now - last_success).total_seconds() / 3600
        _receipt("quiet", f"brief is {age:.1f}h old, nothing to say")
        return 0
    last_text = (
        last_success.astimezone().strftime("%a %d %b %H:%M %Z")
        if last_success
        else "no successful brief recorded"
    )
    message = f"PERSONAL BRIEF HEARTBEAT\nLast successful brief: {last_text}."
    if state_error:
        message += f"\nState error: {state_error}"
    if send(message):
        _receipt("alerted", f"last brief: {last_text}")
        return 0
    # The watchman could not reach him. That is the worst state the system can be in,
    # and it must not exit 0 and look like a quiet night.
    _receipt("ALERT FAILED", f"could not deliver; last brief: {last_text}")
    return 1


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as error:
        summary = record_failure("Heartbeat failed", error)
        print(f"Heartbeat failed: {summary}")
        raise SystemExit(1)

