"""Liveness probe pentru worker (T6) — folosit de healthcheck-ul Docker.

Worker-ul nu e server HTTP, deci `restart: always` prinde doar procesul MORT,
nu si worker-ul AGATAT (proces viu care nu mai bate heartbeat). Acest probe
citeste `worker_heartbeat` din DB si pica daca ultimul beat e mai vechi decat
`worker_heartbeat_stale_s` -> Docker restarteaza containerul worker.

Utilizare (compose healthcheck):  python -m app.worker.healthcheck
Exit 0 = sanatos, 1 = invechit/lipsa.
"""

from __future__ import annotations

import sys
from datetime import datetime, timezone

from ..config import Settings, get_settings
from ..db import get_connection, read_heartbeat


def worker_healthy(conn, settings: Settings, *, now: datetime | None = None) -> bool:
    """True daca ultimul heartbeat e mai proaspat decat pragul de invechire."""
    hb = read_heartbeat(conn)
    if hb is None or not hb["last_beat"]:
        return False
    try:
        last = datetime.fromisoformat(hb["last_beat"])
    except (ValueError, TypeError):
        return False
    now = now or datetime.now(timezone.utc)
    return (now - last).total_seconds() <= settings.worker_heartbeat_stale_s


def main() -> int:
    settings = get_settings()
    conn = get_connection()
    try:
        ok = worker_healthy(conn, settings)
    finally:
        conn.close()
    if not ok:
        print("[healthcheck] worker invechit sau nepornit", flush=True)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
