"""THE IN-PROCESS SCHEDULER LOOP — a real background thread inside this process.

What this is
------------
A daemon thread that ``app.py`` starts at boot. It sleeps for ``INTERVAL_SECONDS``
and then calls ``orchestrator.scheduling.tick()`` — the same tick the "Tick now"
button calls. It fires with no request, no browser and no cron: it is a genuine
background process *inside the Flask process*.

State survives a restart
------------------------
Every run writes its outcome to the ``scheduler_meta`` table in ``jarvis.db``
(key ``loop_state``), so ``last_run_at``, ``run_count`` and ``next_run_at`` are
still there after the process is killed and started again. ``run_count`` is
cumulative across restarts, not per-process.

What this is NOT
----------------
It is **not** an OS-level supervisor. There is no systemd unit, no cron entry, no
launchd plist and no separate worker process. If this Python process dies, the
loop dies with it and nothing restarts it. A real deployment needs a supervisor
(cron / systemd timer / Celery beat) to restart the process and/or call
``POST /api/scheduler/tick``. The UI states this plainly next to the status.

Honesty rules
-------------
* ``last_run_at`` is only set when a tick actually completed.
* ``next_run_at`` is computed from the persisted ``last_run_at`` (or the persisted
  ``started_at`` for the very first run) plus the interval — never guessed.
* A tick that raises is recorded as ``error`` with the real exception text; it is
  never reported as a success.
"""

from __future__ import annotations

import json
import logging
import os
import threading
from datetime import datetime, timedelta, timezone

from . import scheduling
from .context import traced

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

COMPONENT_NAME = "InProcessSchedulerLoop"

META_KEY = "loop_state"

#: How often the loop wakes up. Default: every 3 hours ("every few hours").
INTERVAL_SECONDS = int(os.environ.get("JARVIS_SCHEDULER_INTERVAL", str(3 * 3600)))

#: Delay before the very first tick after boot, so a restart does not stampede.
FIRST_DELAY_SECONDS = int(os.environ.get("JARVIS_SCHEDULER_FIRST_DELAY", "20"))

HONESTY = (
    "In-process scheduler: a daemon thread inside this Flask process calls "
    "scheduling.tick() every few hours. It is NOT an OS-level supervisor — there "
    "is no systemd unit, no cron entry and no separate worker. If this process "
    "dies the loop dies with it; a real deployment needs cron/systemd to restart "
    "the process. State (last run, next run, run count) is persisted in "
    "scheduler_meta and survives restarts."
)

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


# ---------------------------------------------------------------------------
# persisted state
# ---------------------------------------------------------------------------
def _now() -> datetime:
    return datetime.now(timezone.utc)


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


def _parse(ts: str | None) -> datetime | None:
    if not ts:
        return None
    try:
        return datetime.strptime(ts, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
    except (TypeError, ValueError):
        return None


def _load() -> dict:
    scheduling.init_db()
    conn = scheduling.connect()
    try:
        row = conn.execute(
            "SELECT value FROM scheduler_meta WHERE key = ?", (META_KEY,)
        ).fetchone()
    finally:
        conn.close()
    if not row:
        return {}
    try:
        return json.loads(row["value"])
    except (TypeError, ValueError):
        return {}


def _save(state: dict) -> None:
    scheduling.init_db()
    with scheduling.LOCK:
        conn = scheduling.connect()
        try:
            conn.execute(
                "INSERT INTO scheduler_meta (key, value) VALUES (?, ?) "
                "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
                (META_KEY, json.dumps(state, sort_keys=True)),
            )
            conn.commit()
        finally:
            conn.close()


# ---------------------------------------------------------------------------
# one run
# ---------------------------------------------------------------------------
@traced("scheduler", "scheduler_loop.run_once")
def run_once(trigger: str = "timer") -> dict:
    """Run exactly one tick and persist the outcome. Never raises."""
    with _RUN_LOCK:
        started = _now()
        state = _load()
        outcome = "ok"
        error = ""
        fired = 0
        message = ""
        try:
            result = scheduling.tick()
            fired = int(result.get("fired_count") or 0)
            message = result.get("message") or ""
            outcome = "ok"
        except Exception as exc:  # a broken tick must not kill the loop
            log.warning("scheduler loop tick failed: %s", exc)
            outcome = "error"
            error = f"{type(exc).__name__}: {exc}"
            message = error
        finished = _now()
        state.update({
            "last_run_at": _iso(finished),
            "last_run_outcome": outcome,
            "last_run_error": error,
            "last_run_message": message,
            "last_run_fired": fired,
            "last_run_trigger": trigger,
            "last_duration_ms": int((finished - started).total_seconds() * 1000),
            "run_count": int(state.get("run_count") or 0) + 1,
            "interval_seconds": INTERVAL_SECONDS,
            "started_at": state.get("started_at") or _iso(started),
        })
        _save(state)
        log.info("scheduler loop run #%s (%s): %s", state["run_count"], trigger, message)
        return state


# ---------------------------------------------------------------------------
# the thread
# ---------------------------------------------------------------------------
def _loop() -> None:
    log.info("in-process scheduler loop started: interval %ss, first run in %ss",
             INTERVAL_SECONDS, FIRST_DELAY_SECONDS)
    if _STOP.wait(FIRST_DELAY_SECONDS):
        return
    while True:
        try:
            run_once(trigger="timer")
        except Exception as exc:  # pragma: no cover - run_once already guards
            log.warning("scheduler loop iteration crashed: %s", exc)
        if _STOP.wait(INTERVAL_SECONDS):
            return


def start() -> bool:
    """Start the daemon thread. Idempotent. Returns True if it is running."""
    global _THREAD
    with _LOCK:
        if _THREAD is not None and _THREAD.is_alive():
            return True
        _STOP.clear()
        _THREAD = threading.Thread(target=_loop, name="jarvis-scheduler-loop", daemon=True)
        _THREAD.start()
        return True


def stop() -> None:
    global _THREAD
    with _LOCK:
        _STOP.set()
        _THREAD = None


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


# ---------------------------------------------------------------------------
# status for the UI / API
# ---------------------------------------------------------------------------
def status() -> dict:
    """Everything the UI needs, derived from persisted state + the live thread."""
    state = _load()
    running = is_running()
    last = _parse(state.get("last_run_at"))
    anchor = last or _parse(state.get("started_at"))
    next_at = _iso(anchor + timedelta(seconds=INTERVAL_SECONDS)) if anchor else None
    if last is None and anchor is not None:
        next_at = _iso(anchor + timedelta(seconds=FIRST_DELAY_SECONDS))
    return {
        "component": COMPONENT_NAME,
        "in_process": True,
        "os_supervisor": False,
        "thread_alive": running,
        "interval_seconds": INTERVAL_SECONDS,
        "interval_label": _label(INTERVAL_SECONDS),
        "first_delay_seconds": FIRST_DELAY_SECONDS,
        "last_run_at": state.get("last_run_at"),
        "last_run_outcome": state.get("last_run_outcome"),
        "last_run_error": state.get("last_run_error", ""),
        "last_run_message": state.get("last_run_message", ""),
        "last_run_fired": state.get("last_run_fired", 0),
        "last_run_trigger": state.get("last_run_trigger"),
        "last_duration_ms": state.get("last_duration_ms"),
        "run_count": int(state.get("run_count") or 0),
        "started_at": state.get("started_at"),
        "next_run_at": next_at,
        "persisted": bool(state),
        "honesty": HONESTY,
        "not_a_supervisor": (
            "No systemd unit, no cron entry, no launchd plist, no separate worker "
            "process. The loop is a thread inside this Flask process."
        ),
    }


def _label(seconds: int) -> str:
    if seconds % 3600 == 0:
        return f"every {seconds // 3600}h"
    if seconds % 60 == 0:
        return f"every {seconds // 60}m"
    return f"every {seconds}s"


def reset_for_tests() -> None:
    """Clear the persisted loop state. Tests only."""
    scheduling.init_db()
    with scheduling.LOCK:
        conn = scheduling.connect()
        try:
            conn.execute("DELETE FROM scheduler_meta WHERE key = ?", (META_KEY,))
            conn.commit()
        finally:
            conn.close()
