"""THE HEARTBEAT — a real in-process scheduler, with a heartbeat you can watch.

What this is
------------
A genuine background thread started by the process. Every 60 seconds it wakes,
writes one heartbeat row into a 50-slot ring buffer, and fires any named job
whose cadence has come due. The page shows the process uptime, the tick count,
the last tick, a live countdown to the next tick, and the last ten heartbeat
rows — all read from the same in-memory state the thread writes, so the display
cannot drift from the truth.

What this is NOT
----------------
It is not a supervisor. The thread lives inside the web process: when the
process dies, the scheduler dies with it, and nothing restarts it. A real
deployment needs systemd, launchd, supervisord or a container restart policy
around the process. The page says this plainly and the code makes no claim
otherwise — there is no persistence of "we were running", no catch-up on missed
ticks, and no restart logic.

Jobs
----
    scout    every  5 min   re-clusters stored signals into opportunities
    verify   every 15 min   re-runs the verification sweep over open opportunities
    measure  every 60 min   tallies measured bots into kept / killed / inconclusive

Each job run performs real work against the real stores and appends one row to
the hash-chained audit ledger (``scheduler.job.run``) with its outcome, duration
and the counts it produced. A job that raises is recorded as ``error`` with the
exception text — never as a success.
"""

from __future__ import annotations

import logging
import threading
import time
from collections import deque
from datetime import datetime, timedelta, timezone

from . import audit
from .context import traced

log = logging.getLogger("jarvis.heartbeat")

COMPONENT_NAME = "HeartbeatScheduler"

#: The tick interval. One heartbeat row per tick.
TICK_SECONDS = 60

#: How many heartbeat rows the ring buffer keeps.
RING_SIZE = 50

#: How many heartbeat rows the page shows.
VISIBLE_HEARTBEATS = 10

JOBS = [
    {
        "id": "scout",
        "name": "scout",
        "cadence_seconds": 300,
        "cadence_label": "every 5 min",
        "description": "Re-clusters stored signals into opportunities (idempotent).",
    },
    {
        "id": "verify",
        "name": "verify",
        "cadence_seconds": 900,
        "cadence_label": "every 15 min",
        "description": "Runs the verification sweep over open opportunities.",
    },
    {
        "id": "measure",
        "name": "measure",
        "cadence_seconds": 3600,
        "cadence_label": "every 60 min",
        "description": "Tallies measured bots into kept / killed / inconclusive.",
    },
    {
        "id": "proactive",
        "name": "proactive",
        "cadence_seconds": 3600,
        "cadence_label": "every 60 min",
        "description": "Surveys the ledger and speaks only when it is worth interrupting about.",
    },
]

JOB_BY_ID = {job["id"]: job for job in JOBS}

_LOCK = threading.RLock()
_THREAD: threading.Thread | None = None
_STOP = threading.Event()

_STATE = {
    "started_at": None,          # ISO-8601 UTC
    "started_monotonic": None,   # time.monotonic() at start
    "tick_count": 0,
    "last_tick_at": None,
    "last_tick_monotonic": None,
    "next_tick_monotonic": None,
    "heartbeats": deque(maxlen=RING_SIZE),
    "jobs": {},
}


def _now_iso() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def _iso_from_monotonic(mono: float) -> str:
    delta = mono - time.monotonic()
    return (datetime.now(timezone.utc) + timedelta(seconds=delta)).strftime("%Y-%m-%dT%H:%M:%SZ")


# ---------------------------------------------------------------------------
# The three jobs — each does real work against the real stores
# ---------------------------------------------------------------------------
def _job_scout() -> dict:
    from . import opportunity
    run = opportunity.run_engine(actor="scheduler:scout")
    return {
        "detail": (f"{run.get('signals_read', 0)} signals → {run.get('clusters', 0)} clusters → "
                   f"{run.get('created', 0)} new, {run.get('updated', 0)} updated, "
                   f"{run.get('rejected', 0)} rejected"),
        "counts": {k: run.get(k) for k in ("signals_read", "clusters", "produced", "created",
                                           "updated", "rejected")},
    }


def _job_verify() -> dict:
    from . import verification
    sweep = verification.verify_all(trigger="scheduler:verify")
    runs = sweep.get("runs") or []
    verdicts: dict[str, int] = {}
    for run in runs:
        verdict = run.get("verdict") or "UNKNOWN"
        verdicts[verdict] = verdicts.get(verdict, 0) + 1
    return {
        "detail": f"{len(runs)} opportunities verified" + (
            " · " + ", ".join(f"{k} {v}" for k, v in sorted(verdicts.items())) if verdicts else ""),
        "counts": {"runs": len(runs), **verdicts},
    }


def _job_measure() -> dict:
    from . import measurement
    counts = measurement.counts()
    by_verdict = counts.get("by_verdict") or {}
    return {
        "detail": (f"{counts.get('measurements', 0)} measurements · "
                   f"{counts.get('decisions', 0)} decisions · "
                   f"KEPT {by_verdict.get('KEPT', 0)} / KILLED {by_verdict.get('KILLED', 0)} / "
                   f"INCONCLUSIVE {by_verdict.get('INCONCLUSIVE', 0)}"),
        "counts": counts,
    }


def _run_proactive() -> dict:
    """Run the proactive survey and record it. Never raises."""
    from . import proactive

    result = proactive.initiate(channel="ledger") or {}
    signals = result.get("signals")
    if signals is None:
        signals = len(result.get("items") or [])
    kinds = result.get("kinds") or []
    if result.get("initiated") or signals:
        detail = "%d signal(s): %s" % (signals, ", ".join(kinds))
    else:
        detail = "nothing worth interrupting about"
    return {"detail": detail, "counts": {"signals": signals}}


JOB_RUNNERS = {
    "scout": _job_scout,
    "verify": _job_verify,
    "measure": _job_measure,
    "proactive": _run_proactive,
}


@traced("scheduler", "heartbeat.run_job")
def run_job(job_id: str, trigger: str = "manual", write_audit: bool = True) -> dict:
    """Run one named job now. Records the real outcome, including failures."""
    job = JOB_BY_ID.get(job_id)
    if job is None:
        raise KeyError(job_id)
    started = time.monotonic()
    started_iso = _now_iso()
    status = "ok"
    detail = ""
    counts: dict = {}
    error = ""
    try:
        outcome = JOB_RUNNERS[job_id]()
        detail = outcome.get("detail", "")
        counts = outcome.get("counts", {})
    except Exception as exc:  # a failing job is an ERROR, never a pass
        status = "error"
        error = f"{type(exc).__name__}: {exc}"
        detail = error
        log.warning("job %s failed: %s", job_id, error)
    duration_ms = int((time.monotonic() - started) * 1000)
    finished_iso = _now_iso()

    with _LOCK:
        state = _STATE["jobs"].setdefault(job_id, {"run_count": 0})
        state.update({
            "id": job_id,
            "name": job["name"],
            "cadence_seconds": job["cadence_seconds"],
            "cadence_label": job["cadence_label"],
            "description": job["description"],
            "last_run_at": finished_iso,
            "last_started_at": started_iso,
            "last_status": status,
            "last_detail": detail,
            "last_error": error,
            "last_duration_ms": duration_ms,
            "run_count": state.get("run_count", 0) + 1,
            "next_run_monotonic": time.monotonic() + job["cadence_seconds"],
        })

    if write_audit:
        try:
            audit.record(
                actor=COMPONENT_NAME,
                action="scheduler.job.run",
                subject_type="job",
                subject_id=job_id,
                payload={
                    "job": job_id,
                    "trigger": trigger,
                    "status": status,
                    "started_at": started_iso,
                    "finished_at": finished_iso,
                    "duration_ms": duration_ms,
                    "detail": detail,
                    "counts": counts,
                    "error": error,
                },
            )
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("audit write failed for job %s: %s", job_id, exc)

    return {
        "job": job_id,
        "status": status,
        "detail": detail,
        "error": error,
        "duration_ms": duration_ms,
        "started_at": started_iso,
        "finished_at": finished_iso,
        "counts": counts,
    }


# ---------------------------------------------------------------------------
# The tick loop
# ---------------------------------------------------------------------------
@traced("scheduler", "heartbeat.tick")
def tick(trigger: str = "timer") -> dict:
    """One heartbeat: bump the counter, write a ring-buffer row, fire due jobs."""
    now_mono = time.monotonic()
    fired: list[str] = []
    with _LOCK:
        _STATE["tick_count"] += 1
        seq = _STATE["tick_count"]
        _STATE["last_tick_at"] = _now_iso()
        _STATE["last_tick_monotonic"] = now_mono
        _STATE["next_tick_monotonic"] = now_mono + TICK_SECONDS
        due = [job_id for job_id, state in _STATE["jobs"].items()
               if state.get("next_run_monotonic") is not None
               and now_mono >= state["next_run_monotonic"]]
        uptime = int(now_mono - (_STATE["started_monotonic"] or now_mono))
        row = {
            "seq": seq,
            "ts": _STATE["last_tick_at"],
            "tick": seq,
            "uptime_s": uptime,
            "trigger": trigger,
            "due": due,
            "note": "jobs due: " + ", ".join(due) if due else "no jobs due",
        }
        _STATE["heartbeats"].appendleft(row)

    for job_id in due:
        fired.append(job_id)
        run_job(job_id, trigger=f"timer:{trigger}")

    if fired:
        with _LOCK:
            row["note"] = "ran: " + ", ".join(fired)
    return row


def _loop() -> None:
    log.info("heartbeat thread started (tick every %ss)", TICK_SECONDS)
    # First heartbeat immediately, so the page proves liveness on load.
    try:
        tick(trigger="startup")
    except Exception as exc:  # pragma: no cover - defensive
        log.warning("startup tick failed: %s", exc)
    while not _STOP.is_set():
        # Wake every second so the countdown is accurate and stop() is prompt.
        if _STOP.wait(1.0):
            break
        with _LOCK:
            next_at = _STATE["next_tick_monotonic"]
        if next_at is not None and time.monotonic() >= next_at:
            try:
                tick(trigger="timer")
            except Exception as exc:  # pragma: no cover - defensive
                log.warning("tick failed: %s", exc)
    log.info("heartbeat thread stopped")


def start() -> bool:
    """Start the background thread. Idempotent. Returns True if it started now."""
    global _THREAD
    with _LOCK:
        if _THREAD is not None and _THREAD.is_alive():
            return False
        _STOP.clear()
        now_mono = time.monotonic()
        _STATE["started_at"] = _now_iso()
        _STATE["started_monotonic"] = now_mono
        _STATE["next_tick_monotonic"] = now_mono
        for job in JOBS:
            state = _STATE["jobs"].setdefault(job["id"], {"run_count": 0})
            state.update({
                "id": job["id"],
                "name": job["name"],
                "cadence_seconds": job["cadence_seconds"],
                "cadence_label": job["cadence_label"],
                "description": job["description"],
                "last_run_at": state.get("last_run_at"),
                "last_status": state.get("last_status", "idle"),
                "last_detail": state.get("last_detail", "not run yet"),
                "last_error": state.get("last_error", ""),
                "last_duration_ms": state.get("last_duration_ms"),
                "run_count": state.get("run_count", 0),
                # First automatic run one full cadence after start.
                "next_run_monotonic": now_mono + job["cadence_seconds"],
            })
        _THREAD = threading.Thread(target=_loop, name="jarvis-heartbeat", daemon=True)
        _THREAD.start()
        return True


def stop() -> None:
    """Stop the thread (tests, and a clean shutdown)."""
    global _THREAD
    _STOP.set()
    thread = _THREAD
    if thread is not None and thread.is_alive():
        thread.join(timeout=3.0)
    with _LOCK:
        _THREAD = None


def is_running() -> bool:
    with _LOCK:
        return _THREAD is not None and _THREAD.is_alive()


def ensure_started() -> bool:
    """Start on first use, so the scheduler is alive whenever anyone looks."""
    return start()


# ---------------------------------------------------------------------------
# Read model
# ---------------------------------------------------------------------------
def status() -> dict:
    with _LOCK:
        now_mono = time.monotonic()
        started_mono = _STATE["started_monotonic"]
        uptime = int(now_mono - started_mono) if started_mono else 0
        next_at = _STATE["next_tick_monotonic"]
        countdown = max(0, int(round(next_at - now_mono))) if next_at else None
        jobs = []
        for job in JOBS:
            state = _STATE["jobs"].get(job["id"], {})
            next_mono = state.get("next_run_monotonic")
            jobs.append({
                "id": job["id"],
                "name": job["name"],
                "cadence_seconds": job["cadence_seconds"],
                "cadence_label": job["cadence_label"],
                "description": job["description"],
                "last_run_at": state.get("last_run_at"),
                "next_run_at": _iso_from_monotonic(next_mono) if next_mono else None,
                "next_run_in_s": max(0, int(round(next_mono - now_mono))) if next_mono else None,
                "run_count": state.get("run_count", 0),
                "status": state.get("last_status", "idle"),
                "detail": state.get("last_detail", "not run yet"),
                "error": state.get("last_error", ""),
                "duration_ms": state.get("last_duration_ms"),
            })
        heartbeats = list(_STATE["heartbeats"])[:VISIBLE_HEARTBEATS]
        return {
            "running": is_running(),
            "started_at": _STATE["started_at"],
            "uptime_s": uptime,
            "uptime": _fmt_duration(uptime),
            "tick_count": _STATE["tick_count"],
            "tick_seconds": TICK_SECONDS,
            "last_tick_at": _STATE["last_tick_at"],
            "next_tick_in_s": countdown,
            "ring_size": RING_SIZE,
            "ring_used": len(_STATE["heartbeats"]),
            "jobs": jobs,
            "heartbeats": heartbeats,
            "supervisor_note": (
                "In-process scheduler. It runs inside this web process and dies with it. "
                "A real deployment needs a supervisor (systemd / launchd / supervisord) so it "
                "survives restarts — this does not."
            ),
        }


def _fmt_duration(seconds: int) -> str:
    seconds = max(0, int(seconds))
    hours, rem = divmod(seconds, 3600)
    minutes, secs = divmod(rem, 60)
    if hours:
        return f"{hours}h {minutes:02d}m {secs:02d}s"
    if minutes:
        return f"{minutes}m {secs:02d}s"
    return f"{secs}s"


def reset_for_tests() -> None:
    """Test hook: stop the thread and clear all state."""
    stop()
    with _LOCK:
        _STATE.update({
            "started_at": None,
            "started_monotonic": None,
            "tick_count": 0,
            "last_tick_at": None,
            "last_tick_monotonic": None,
            "next_tick_monotonic": None,
            "heartbeats": deque(maxlen=RING_SIZE),
            "jobs": {},
        })
