"""THE SCHEDULING LAYER — signalling, not a daemon.

What this is
------------
A table of schedules (``schedules``) plus ``tick()``, which looks for schedules
whose ``next_run_at`` is due, performs the stored action, advances the schedule
and writes one audit row per run through ``orchestrator.audit.record()``.

What this is NOT
----------------
There is no background thread, no cron, no systemd unit and no process
supervisor here. ``tick()`` runs only when a request asks for it (the Schedules
page has a "Tick now" button; ``POST /api/scheduler/tick`` and the ``tick`` voice
command do the same). Nothing fires on its own in this sandbox — the page states
that plainly and shows the last tick time so the claim is checkable. A real
deployment would need a supervisor (cron, systemd timer, Celery beat, ...)
calling the tick endpoint, and this module makes no claim to be one.

Cadences (all wall-clock times are America/New_York)
---------------------------------------------------
``hourly``  at_minute
``daily``   at_hour + at_minute
``weekly``  days_of_week (0=Mon .. 6=Sun) + at_hour + at_minute

``next_run_at`` is computed deterministically from a given instant (default:
now) and stored as UTC ISO-8601 with a ``Z`` suffix — the same format the rest of
the system uses. Nothing is inferred from "whatever the last run did"; the next
occurrence is a pure function of (cadence, at_hour, at_minute, days_of_week,
after).

Idempotency per due time
------------------------
Firing is claimed with a single conditional UPDATE:

    UPDATE schedules SET last_run_at=?, next_run_at=?, run_count=run_count+1
    WHERE id=? AND enabled=1 AND next_run_at=?

If the row was already advanced (because the tick ran twice, or two ticks raced)
``rowcount`` is 0 and the schedule is skipped. So a schedule can never
double-fire for the same due time, even if ``tick()`` is called twice in a row
with the same clock.
"""

from __future__ import annotations

import json
import logging
from datetime import datetime, time as dtime, timedelta, timezone
from zoneinfo import ZoneInfo

from . import audit
from .db import LOCK, connect, ensure_schedule_schema, init_db as _db_init
from .errors import ValidationError
from .events import utcnow

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

COMPONENT_NAME = "SchedulerLayer"
TIMEZONE = "America/New_York"
TABLE = "schedules"

CADENCE_HOURLY = "hourly"
CADENCE_DAILY = "daily"
CADENCE_WEEKLY = "weekly"
CADENCES = (CADENCE_HOURLY, CADENCE_DAILY, CADENCE_WEEKLY)

TARGET_INGEST = "ingest"
TARGET_OPPORTUNITIES = "opportunities"
TARGET_VERIFY = "verify"
TARGET_MEASURE = "measure"
TARGET_KINDS = (TARGET_INGEST, TARGET_OPPORTUNITIES, TARGET_VERIFY, TARGET_MEASURE)

TARGET_DESCRIPTIONS = {
    TARGET_INGEST: "run the existing ingestion fetch across all sources",
    TARGET_OPPORTUNITIES: "run the existing opportunity engine",
    TARGET_VERIFY: "run the existing verification pass over unverified opportunities",
    TARGET_MEASURE: "recompute keep-or-kill verdicts for bots that have measurements",
}

WEEKDAY_LABELS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

HONESTY = (
    "Tick-driven, not a persistent cron daemon. Nothing runs on its own in this "
    "sandbox: a schedule only fires when a request calls the tick (the 'Tick now' "
    "button, POST /api/scheduler/tick, or the 'tick' voice command). A real "
    "deployment needs a process supervisor (cron / systemd timer / beat) calling "
    "that endpoint on a cadence."
)


# --------------------------------------------------------------------------
# time helpers
# --------------------------------------------------------------------------

def _tz() -> ZoneInfo:
    try:
        return ZoneInfo(TIMEZONE)
    except Exception:  # pragma: no cover - tzdata missing: fall back to fixed offset
        log.warning("zoneinfo has no %s; falling back to UTC-5 (no DST)", TIMEZONE)
        return timezone(timedelta(hours=-5))  # type: ignore[return-value]


def iso(dt: datetime) -> str:
    """UTC ISO-8601 with milliseconds and Z, matching orchestrator.events.utcnow()."""
    dt = dt.astimezone(timezone.utc)
    return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"


def parse_iso(ts: str | None) -> datetime | None:
    if not ts:
        return None
    text = str(ts).strip()
    for fmt in ("%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%dT%H:%M:%SZ"):
        try:
            return datetime.strptime(text, fmt).replace(tzinfo=timezone.utc)
        except ValueError:
            continue
    try:  # last resort: fromisoformat handles offsets and no suffix
        dt = datetime.fromisoformat(text.replace("Z", "+00:00"))
        return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
    except ValueError:
        return None


def _as_dt(after) -> datetime:
    if after is None:
        return datetime.now(timezone.utc)
    if isinstance(after, datetime):
        return after if after.tzinfo else after.replace(tzinfo=timezone.utc)
    parsed = parse_iso(str(after))
    if parsed is None:
        raise ValidationError(f"{after!r} is not a valid ISO-8601 timestamp")
    return parsed


def normalize_days(days_of_week) -> str:
    """'1,3,5' / [1,3,5] / '' -> canonical comma-separated string of 0..6."""
    if days_of_week in (None, ""):
        return ""
    if isinstance(days_of_week, (list, tuple, set)):
        parts = list(days_of_week)
    else:
        parts = str(days_of_week).replace(";", ",").split(",")
    days = sorted({int(str(p).strip()) for p in parts if str(p).strip() != ""})
    bad = [d for d in days if d < 0 or d > 6]
    if bad:
        raise ValidationError(f"days_of_week values must be 0..6 (0=Mon); got {bad}")
    return ",".join(str(d) for d in days)


def parse_days(days_of_week) -> list[int]:
    raw = normalize_days(days_of_week)
    return [int(p) for p in raw.split(",")] if raw else []


def _validate(cadence: str, at_hour, at_minute) -> tuple[int | None, int]:
    cadence = str(cadence or "").strip().lower()
    if cadence not in CADENCES:
        raise ValidationError(
            f"cadence must be one of {', '.join(CADENCES)}; got {cadence!r}"
        )
    try:
        minute = int(at_minute if at_minute not in (None, "") else 0)
    except (TypeError, ValueError):
        raise ValidationError(f"at_minute must be an integer 0..59; got {at_minute!r}")
    if not 0 <= minute <= 59:
        raise ValidationError(f"at_minute must be 0..59; got {minute}")
    if cadence == CADENCE_HOURLY:
        return None, minute
    try:
        hour = int(at_hour if at_hour not in (None, "") else 9)
    except (TypeError, ValueError):
        raise ValidationError(f"at_hour must be an integer 0..23; got {at_hour!r}")
    if not 0 <= hour <= 23:
        raise ValidationError(f"at_hour must be 0..23; got {hour}")
    return hour, minute


def next_run_at(
    cadence: str,
    *,
    at_minute=0,
    at_hour=9,
    days_of_week="",
    after=None,
) -> str:
    """The next occurrence strictly after ``after`` (default now), as UTC ISO.

    Pure and deterministic: same inputs -> same output. Times are wall-clock in
    America/New_York; the result is converted back to UTC.
    """
    cadence = str(cadence or "").strip().lower()
    hour, minute = _validate(cadence, at_hour, at_minute)
    tz = _tz()
    local_now = _as_dt(after).astimezone(tz)

    if cadence == CADENCE_HOURLY:
        cand = local_now.replace(minute=minute, second=0, microsecond=0)
        if cand <= local_now:
            cand = cand + timedelta(hours=1)
        return iso(cand)

    if cadence == CADENCE_DAILY:
        cand = local_now.replace(hour=hour, minute=minute, second=0, microsecond=0)
        if cand <= local_now:
            cand = cand + timedelta(days=1)
        return iso(cand)

    days = parse_days(days_of_week)
    if not days:
        raise ValidationError("weekly cadence needs at least one day in days_of_week (0=Mon)")
    for offset in range(0, 8):
        day = (local_now + timedelta(days=offset)).date()
        if day.weekday() not in days:
            continue
        cand = datetime.combine(day, dtime(hour=hour, minute=minute), tzinfo=tz)
        if cand > local_now:
            return iso(cand)
    # unreachable: a matching weekday always occurs within 7 days
    raise ValidationError("could not compute a weekly occurrence")  # pragma: no cover


def describe_cadence(row: dict) -> str:
    cadence = row.get("cadence")
    minute = row.get("at_minute") or 0
    if cadence == CADENCE_HOURLY:
        return f"hourly at minute {int(minute):02d}"
    hour = row.get("at_hour")
    hour = 9 if hour is None else int(hour)
    if cadence == CADENCE_DAILY:
        return f"daily at {hour:02d}:{int(minute):02d} {TIMEZONE}"
    days = parse_days(row.get("days_of_week"))
    labels = ",".join(WEEKDAY_LABELS[d] for d in days) or "no days"
    return f"weekly on {labels} at {hour:02d}:{int(minute):02d} {TIMEZONE}"


# --------------------------------------------------------------------------
# schema + row helpers
# --------------------------------------------------------------------------

def init_db() -> str:
    path = _db_init()
    with LOCK:
        conn = connect()
        try:
            ensure_schedule_schema(conn)
        finally:
            conn.close()
    return path


def _row(row) -> dict:
    d = dict(row)
    d["enabled"] = bool(d.get("enabled"))
    d["seeded"] = bool(d.get("seeded"))
    d["at_minute"] = int(d.get("at_minute") or 0)
    d["at_hour"] = None if d.get("at_hour") is None else int(d["at_hour"])
    d["days_of_week"] = d.get("days_of_week") or ""
    d["days"] = parse_days(d.get("days_of_week"))
    d["run_count"] = int(d.get("run_count") or 0)
    d["cadence_label"] = describe_cadence(d)
    d["target_description"] = TARGET_DESCRIPTIONS.get(d.get("target_kind"), "")
    d["due"] = _is_due(d.get("next_run_at"))
    return d


def _is_due(next_ts, now: datetime | None = None) -> bool:
    parsed = parse_iso(next_ts)
    if parsed is None:
        return False
    return parsed <= (now or datetime.now(timezone.utc))


def list_schedules(enabled: bool | None = None, limit: int = 200) -> list[dict]:
    init_db()
    limit = max(1, min(int(limit), 1000))
    sql = f"SELECT * FROM {TABLE}"
    args: list = []
    if enabled is not None:
        sql += " WHERE enabled = ?"
        args.append(1 if enabled else 0)
    sql += " ORDER BY id ASC LIMIT ?"
    args.append(limit)
    conn = connect()
    try:
        return [_row(r) for r in conn.execute(sql, tuple(args)).fetchall()]
    finally:
        conn.close()


def get_schedule(schedule_id) -> dict | None:
    init_db()
    conn = connect()
    try:
        row = conn.execute(f"SELECT * FROM {TABLE} WHERE id = ?", (int(schedule_id),)).fetchone()
        return _row(row) if row else None
    finally:
        conn.close()


def _meta_get(key: str, default=None):
    conn = connect()
    try:
        row = conn.execute("SELECT value FROM scheduler_meta WHERE key = ?", (key,)).fetchone()
        return row["value"] if row else default
    finally:
        conn.close()


def _meta_set(conn, key: str, value: str) -> None:
    conn.execute(
        "INSERT INTO scheduler_meta (key, value) VALUES (?, ?) "
        "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
        (key, value),
    )


def last_tick() -> dict:
    """When the tick last ran, and what it did. Empty dict if it never ran."""
    init_db()
    raw = _meta_get("last_tick")
    if not raw:
        return {}
    try:
        return json.loads(raw)
    except (TypeError, ValueError):  # pragma: no cover - defensive
        return {}


# --------------------------------------------------------------------------
# create / toggle
# --------------------------------------------------------------------------

def create_schedule(
    name: str,
    target_kind: str,
    *,
    target_id: str | None = None,
    cadence: str = CADENCE_DAILY,
    at_minute=0,
    at_hour=9,
    days_of_week="",
    enabled: bool = True,
    seeded: bool = False,
    after=None,
) -> dict:
    """Insert one schedule and audit its creation. Returns the stored row."""
    init_db()
    name = (name or "").strip()
    if not name:
        raise ValidationError("name is required and must be a non-empty string")
    kind = str(target_kind or "").strip().lower()
    if kind not in TARGET_KINDS:
        raise ValidationError(
            f"target_kind must be one of {', '.join(TARGET_KINDS)}; got {target_kind!r}"
        )
    cadence = str(cadence or "").strip().lower()
    hour, minute = _validate(cadence, at_hour, at_minute)
    days = normalize_days(days_of_week)
    if cadence == CADENCE_WEEKLY and not days:
        raise ValidationError("weekly cadence needs days_of_week, e.g. \"0,3\" (0=Mon)")

    next_ts = next_run_at(cadence, at_minute=minute, at_hour=hour or 9,
                          days_of_week=days, after=after)
    created_at = utcnow()
    with LOCK:
        conn = connect()
        try:
            cur = conn.execute(
                f"""INSERT INTO {TABLE}
                    (name, target_kind, target_id, cadence, at_minute, at_hour,
                     days_of_week, enabled, last_run_at, next_run_at, run_count,
                     created_at, seeded)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                (
                    name, kind, (target_id or "").strip(), cadence, minute,
                    hour, days, 1 if enabled else 0, None, next_ts, 0, created_at,
                    1 if seeded else 0,
                ),
            )
            schedule_id = cur.lastrowid
            audit.record(
                COMPONENT_NAME, "schedule.created", "schedule", schedule_id,
                {
                    "name": name, "target_kind": kind, "target_id": (target_id or "").strip(),
                    "cadence": cadence, "at_minute": minute, "at_hour": hour,
                    "days_of_week": days, "enabled": bool(enabled),
                    "next_run_at": next_ts, "timezone": TIMEZONE, "seeded": bool(seeded),
                },
                conn=conn,
            )
            conn.commit()
        except Exception:
            conn.rollback()
            raise
        finally:
            conn.close()
    return get_schedule(schedule_id)


def toggle_schedule(schedule_id, enabled: bool | None = None) -> dict:
    """Flip (or set) the enabled flag. Disabled schedules never fire."""
    init_db()
    current = get_schedule(schedule_id)
    if current is None:
        raise ValidationError(f"no schedule with id {schedule_id!r}")
    target = (not current["enabled"]) if enabled is None else bool(enabled)
    with LOCK:
        conn = connect()
        try:
            # Re-enabling recomputes the next occurrence from now, so a schedule
            # that was off for a week does not fire a week of backlog.
            next_ts = current["next_run_at"]
            if target:
                next_ts = next_run_at(
                    current["cadence"],
                    at_minute=current["at_minute"],
                    at_hour=current["at_hour"] if current["at_hour"] is not None else 9,
                    days_of_week=current["days_of_week"],
                )
            conn.execute(
                f"UPDATE {TABLE} SET enabled = ?, next_run_at = ? WHERE id = ?",
                (1 if target else 0, next_ts, int(schedule_id)),
            )
            audit.record(
                COMPONENT_NAME, "schedule.toggled", "schedule", int(schedule_id),
                {
                    "name": current["name"], "enabled_before": current["enabled"],
                    "enabled": target,
                    "note": ("enabled" if target else "disabled") + " via API",
                    "next_run_at": next_ts,
                },
                conn=conn,
            )
            conn.commit()
        except Exception:
            conn.rollback()
            raise
        finally:
            conn.close()
    return get_schedule(schedule_id)


# --------------------------------------------------------------------------
# the scheduled actions (all reused from the existing layers)
# --------------------------------------------------------------------------

def perform_target(target_kind: str, target_id: str | None = None) -> dict:
    """Perform one scheduled action by delegating to the existing component."""
    kind = str(target_kind or "").strip().lower()
    if kind == TARGET_INGEST:
        from . import ingestion

        run = ingestion.run_ingest(trigger="schedule")
        ok = not run["errors"]
        summary = (
            f"ingestion fetched {run['fetched_total']} item(s), {run['new_total']} new, "
            f"across {len(run['sources'])} source(s)"
            + (f"; {len(run['errors'])} source error(s)" if run["errors"] else "")
        )
        return {
            "ok": ok,
            "summary": summary,
            "run_id": run["id"],
            "detail": {
                "fetched_total": run["fetched_total"],
                "new_total": run["new_total"],
                "sources": run["sources"],
                "errors": run["errors"],
            },
        }

    if kind == TARGET_OPPORTUNITIES:
        from . import opportunity

        run = opportunity.run_engine(actor=COMPONENT_NAME)
        return {
            "ok": True,
            "summary": run["message"],
            "run_id": run["id"],
            "detail": {
                "signals_read": run["signals_read"],
                "clusters": run["clusters"],
                "produced": run["produced"],
                "created": run["created"],
                "updated": run["updated"],
                "rejected": run["rejected"],
            },
        }

    if kind == TARGET_VERIFY:
        from . import opportunity, verification

        unverified = [
            opp["id"]
            for opp in opportunity.list_opportunities(limit=1000)
            if (opp.get("verdict") or "") != verification.VERIFIED
        ]
        if not unverified:
            return {
                "ok": True,
                "summary": "no unverified opportunities; nothing was re-fetched",
                "run_id": None,
                "detail": {"verified_count": 0, "opportunity_ids": []},
            }
        sweep = verification.verify_all(unverified, trigger="schedule")
        return {
            "ok": not sweep["errors"],
            "summary": sweep["message"],
            "run_id": sweep["runs"][0]["id"] if sweep["runs"] else None,
            "detail": {
                "verified_count": sweep["count"],
                "tally": sweep["tally"],
                "errors": sweep["errors"],
                "opportunity_ids": unverified,
            },
        }

    if kind == TARGET_MEASURE:
        from . import measurement

        bots = measurement.list_bots()
        measured = [b for b in bots if b.get("latest_measurement")]
        verdicts = [
            {
                "bot_id": b["id"],
                "bot_name": b.get("bot_name"),
                "verdict": b.get("current_verdict"),
                "reason": b.get("current_reason"),
                "measurement_id": (b.get("latest_measurement") or {}).get("id"),
            }
            for b in measured
        ]
        tally = {v: 0 for v in measurement.VERDICTS}
        for v in verdicts:
            tally[v["verdict"]] = tally.get(v["verdict"], 0) + 1
        if not verdicts:
            summary = "no bot has a measurement yet; nothing to recompute"
        else:
            summary = (
                f"recomputed rule v{measurement.RULE_VERSION} for {len(verdicts)} bot(s) with "
                f"measurements -> {tally['KEPT']} KEPT, {tally['KILLED']} KILLED, "
                f"{tally['INCONCLUSIVE']} INCONCLUSIVE"
            )
        # The replay itself is a fact worth recording: one ledger row per bot so a
        # single verdict can be traced back to the schedule that recomputed it.
        for v in verdicts:
            audit.record(
                COMPONENT_NAME, "schedule.measure.verdict", "bot", v["bot_id"],
                v,
            )
        return {
            "ok": True,
            "summary": summary,
            "run_id": None,
            "detail": {"bots": verdicts, "tally": tally,
                       "rule_version": measurement.RULE_VERSION},
        }

    raise ValidationError(
        f"unknown target_kind {target_kind!r}; valid: {', '.join(TARGET_KINDS)}"
    )


# --------------------------------------------------------------------------
# tick
# --------------------------------------------------------------------------

def _claim(schedule: dict, now: datetime, next_ts: str) -> bool:
    """Atomically claim one due occurrence. False = somebody already did."""
    with LOCK:
        conn = connect()
        try:
            cur = conn.execute(
                f"""UPDATE {TABLE}
                    SET last_run_at = ?, next_run_at = ?, run_count = run_count + 1
                    WHERE id = ? AND enabled = 1 AND next_run_at = ?""",
                (iso(now), next_ts, int(schedule["id"]), schedule["next_run_at"]),
            )
            conn.commit()
            return cur.rowcount == 1
        finally:
            conn.close()


def tick(now=None, *, write_audit: bool = True) -> dict:
    """Run ONE tick: fire every enabled schedule whose next_run_at is due.

    Idempotent per due time — a schedule is claimed with a conditional UPDATE on
    the exact due timestamp it was selected for, so calling tick() twice with the
    same clock fires once.
    """
    init_db()
    now_dt = _as_dt(now)
    schedules = list_schedules(limit=1000)
    enabled = [s for s in schedules if s["enabled"]]

    fired: list[dict] = []
    skipped: list[dict] = []
    due: list[dict] = []

    for sched in enabled:
        due_at = parse_iso(sched["next_run_at"])
        if due_at is None or due_at > now_dt:
            continue
        last = parse_iso(sched.get("last_run_at"))
        if last is not None and last >= due_at:
            # Belt and braces: this due time was already handled. The conditional
            # claim below would also refuse, but say why instead of silently
            # skipping.
            skipped.append({
                "schedule_id": sched["id"], "name": sched["name"],
                "due_at": sched["next_run_at"],
                "reason": "already fired for this due time (last_run_at >= next_run_at)",
            })
            continue
        due.append(sched)

    for sched in due:
        next_ts = next_run_at(
            sched["cadence"],
            at_minute=sched["at_minute"],
            at_hour=sched["at_hour"] if sched["at_hour"] is not None else 9,
            days_of_week=sched["days_of_week"],
            after=now_dt,
        )
        claimed = _claim(sched, now_dt, next_ts)
        if not claimed:
            skipped.append({
                "schedule_id": sched["id"], "name": sched["name"],
                "due_at": sched["next_run_at"],
                "reason": "already claimed by another tick (conditional update matched 0 rows)",
            })
            continue

        started = datetime.now(timezone.utc)
        try:
            result = perform_target(sched["target_kind"], sched.get("target_id"))
            outcome = "ok" if result.get("ok", True) else "degraded"
            summary = result.get("summary", "")
            detail = result.get("detail") or {}
            run_id = result.get("run_id")
        except Exception as exc:  # a failing action must not stop the tick
            log.warning("schedule %s (%s) failed: %s", sched["id"], sched["name"], exc)
            outcome = "error"
            summary = f"{type(exc).__name__}: {exc}"
            detail = {"error": summary}
            run_id = None

        fired_at = utcnow()
        record = {
            "schedule_id": sched["id"],
            "name": sched["name"],
            "target_kind": sched["target_kind"],
            "due_at": sched["next_run_at"],
            "fired_at": fired_at,
            "outcome": outcome,
            "summary": summary,
            "run_id": run_id,
            "next_run_at": next_ts,
        }
        if write_audit:
            row = audit.record(
                COMPONENT_NAME, "schedule.run", "schedule", sched["id"],
                {
                    "schedule_id": sched["id"],
                    "name": sched["name"],
                    "target_kind": sched["target_kind"],
                    "target_id": sched.get("target_id") or "",
                    "cadence": sched["cadence"],
                    "cadence_label": sched["cadence_label"],
                    "due_at": sched["next_run_at"],
                    "fired_at": fired_at,
                    "outcome": outcome,
                    "summary": summary,
                    "run_id": run_id,
                    "detail": detail,
                    "next_run_at": next_ts,
                    "run_count": sched["run_count"] + 1,
                    "trigger": "tick",
                    "scheduled_by": "tick",
                    "duration_ms": int(
                        (datetime.now(timezone.utc) - started).total_seconds() * 1000
                    ),
                },
                legacy={
                    "job_id": None,
                    "kind": "schedule_run",
                    "from_state": None,
                    "to_state": None,
                    "note": (
                        f"scheduled {sched['target_kind']} fired for schedule "
                        f"{sched['id']} ({sched['name']!r}): {outcome} — {summary}"
                    ),
                    "data": {
                        "schedule_id": sched["id"],
                        "target_kind": sched["target_kind"],
                        "outcome": outcome,
                        "summary": summary,
                        "next_run_at": next_ts,
                    },
                },
            )
            record["audit_seq"] = row["seq"]
        record["detail"] = detail
        fired.append(record)

    tick_at = utcnow()
    message = (
        f"tick at {tick_at}: {len(enabled)} enabled schedule(s), {len(due)} due, "
        f"{len(fired)} fired, {len(skipped)} skipped"
    )
    if write_audit:
        with LOCK:
            conn = connect()
            try:
                _meta_set(conn, "last_tick", json.dumps({
                    "tick_at": tick_at,
                    "at": iso(now_dt),
                    "enabled": len(enabled),
                    "due": len(due),
                    "fired": len(fired),
                    "skipped": len(skipped),
                    "message": message,
                }, sort_keys=True))
                conn.commit()
            finally:
                conn.close()
        audit.record(
            COMPONENT_NAME, "schedule.tick", "scheduler", None,
            {
                "tick_at": tick_at,
                "clock": iso(now_dt),
                "enabled": len(enabled),
                "due": len(due),
                "fired": len(fired),
                "skipped": len(skipped),
                "fired_schedules": [
                    {"schedule_id": f["schedule_id"], "name": f["name"],
                     "target_kind": f["target_kind"], "outcome": f["outcome"]}
                    for f in fired
                ],
                "message": message,
                "trigger": "request",
                "background_daemon": False,
            },
        )

    return {
        "tick_at": tick_at,
        "clock": iso(now_dt),
        "timezone": TIMEZONE,
        "checked": len(schedules),
        "enabled": len(enabled),
        "due": len(due),
        "fired": fired,
        "skipped": skipped,
        "fired_count": len(fired),
        "message": message,
        "background_daemon": False,
    }


def run_now(schedule_id, *, write_audit: bool = True) -> dict:
    """Fire one schedule immediately, regardless of next_run_at.

    A manual run also resets the cadence clock (next_run_at is recomputed from
    now) so pressing "run now" on a due schedule cannot make the next tick do the
    same work twice. run_count increments either way.
    """
    init_db()
    sched = get_schedule(schedule_id)
    if sched is None:
        raise ValidationError(f"no schedule with id {schedule_id!r}")
    now_dt = datetime.now(timezone.utc)
    next_ts = next_run_at(
        sched["cadence"],
        at_minute=sched["at_minute"],
        at_hour=sched["at_hour"] if sched["at_hour"] is not None else 9,
        days_of_week=sched["days_of_week"],
        after=now_dt,
    )

    started = datetime.now(timezone.utc)
    try:
        result = perform_target(sched["target_kind"], sched.get("target_id"))
        outcome = "ok" if result.get("ok", True) else "degraded"
        summary = result.get("summary", "")
        detail = result.get("detail") or {}
        run_id = result.get("run_id")
    except Exception as exc:
        log.warning("run-now failed for schedule %s: %s", schedule_id, exc)
        outcome = "error"
        summary = f"{type(exc).__name__}: {exc}"
        detail = {"error": summary}
        run_id = None

    fired_at = utcnow()
    with LOCK:
        conn = connect()
        try:
            conn.execute(
                f"""UPDATE {TABLE}
                    SET last_run_at = ?, next_run_at = ?, run_count = run_count + 1
                    WHERE id = ?""",
                (fired_at, next_ts, int(schedule_id)),
            )
            record = None
            if write_audit:
                record = audit.record(
                    COMPONENT_NAME, "schedule.run", "schedule", int(schedule_id),
                    {
                        "schedule_id": sched["id"],
                        "name": sched["name"],
                        "target_kind": sched["target_kind"],
                        "target_id": sched.get("target_id") or "",
                        "cadence": sched["cadence"],
                        "cadence_label": sched["cadence_label"],
                        "due_at": sched["next_run_at"],
                        "fired_at": fired_at,
                        "outcome": outcome,
                        "summary": summary,
                        "run_id": run_id,
                        "detail": detail,
                        "next_run_at": next_ts,
                        "run_count": sched["run_count"] + 1,
                        "trigger": "manual",
                        "duration_ms": int(
                            (datetime.now(timezone.utc) - started).total_seconds() * 1000
                        ),
                    },
                    conn=conn,
                    legacy={
                        "job_id": None,
                        "kind": "schedule_run",
                        "from_state": None,
                        "to_state": None,
                        "note": (
                            f"MANUAL run of schedule {sched['id']} ({sched['name']!r}) "
                            f"-> {sched['target_kind']}: {outcome} — {summary}"
                        ),
                        "data": {
                            "schedule_id": sched["id"],
                            "target_kind": sched["target_kind"],
                            "outcome": outcome,
                            "summary": summary,
                            "trigger": "manual",
                            "next_run_at": next_ts,
                        },
                    },
                )
            conn.commit()
            audit_seq = record["seq"] if record else None
        except Exception:
            conn.rollback()
            raise
        finally:
            conn.close()

    return {
        "schedule": get_schedule(schedule_id),
        "schedule_id": sched["id"],
        "name": sched["name"],
        "target_kind": sched["target_kind"],
        "outcome": outcome,
        "summary": summary,
        "detail": detail,
        "run_id": run_id,
        "fired_at": fired_at,
        "trigger": "manual",
        "next_run_at": next_ts,
        "audit_seq": audit_seq,
    }


# --------------------------------------------------------------------------
# seed
# --------------------------------------------------------------------------

SEED_SCHEDULES = [
    {
        "name": "Seeded: hourly ingest",
        "target_kind": TARGET_INGEST,
        "cadence": CADENCE_HOURLY,
        "at_minute": 5,
        "at_hour": None,
        "days_of_week": "",
    },
    {
        "name": "Seeded: daily opportunities",
        "target_kind": TARGET_OPPORTUNITIES,
        "cadence": CADENCE_DAILY,
        "at_minute": 15,
        "at_hour": 7,
        "days_of_week": "",
    },
    {
        "name": "Seeded: daily verification pass",
        "target_kind": TARGET_VERIFY,
        "cadence": CADENCE_DAILY,
        "at_minute": 30,
        "at_hour": 8,
        "days_of_week": "",
    },
]


def seed_if_empty() -> int:
    """Seed the three example schedules, only if the table has no rows."""
    init_db()
    conn = connect()
    try:
        n = conn.execute(f"SELECT COUNT(*) AS n FROM {TABLE}").fetchone()["n"]
    finally:
        conn.close()
    if n:
        return 0
    created = 0
    for spec in SEED_SCHEDULES:
        create_schedule(
            spec["name"], spec["target_kind"],
            cadence=spec["cadence"], at_minute=spec["at_minute"],
            at_hour=spec["at_hour"], days_of_week=spec["days_of_week"],
            enabled=True, seeded=True,
        )
        created += 1
    log.info("seeded %d schedule(s)", created)
    return created


# --------------------------------------------------------------------------
# the registry component (a tool: owns no pipeline state)
# --------------------------------------------------------------------------

class SchedulingLayer:
    """Registered capability. Not a pipeline state — looked up by name."""

    name = COMPONENT_NAME

    def __call__(self, job: dict | None = None) -> dict:
        return self.handle(job or {})

    def handle(self, job: dict) -> dict:
        result = tick()
        return {
            "to_state": None,  # a tool never transitions a job
            "note": result["message"],
            "payload_patch": {},
            "data": {
                "fired": [
                    {"schedule_id": f["schedule_id"], "name": f["name"],
                     "outcome": f["outcome"]}
                    for f in result["fired"]
                ],
                "fired_count": result["fired_count"],
            },
        }


def register_scheduling(registry) -> object:
    """Register the scheduling layer as a tool component. Idempotent."""
    from .registry import Component

    if registry.has(COMPONENT_NAME):
        return registry.get(COMPONENT_NAME)
    return registry.register(
        Component(
            name=COMPONENT_NAME,
            handles_state=None,
            handler=SchedulingLayer(),
            description=(
                "Tick-driven scheduling: hourly/daily/weekly schedules that run the existing "
                "ingest / opportunity / verify / measure actions. No background daemon — every "
                "run is caused by a request and recorded in the audit ledger."
            ),
            kind="tool",
        )
    )


def describe() -> dict:
    """What the UI/API says about this layer, including what it is not."""
    schedules = list_schedules()
    return {
        "component": COMPONENT_NAME,
        "table": TABLE,
        "timezone": TIMEZONE,
        "cadences": list(CADENCES),
        "target_kinds": list(TARGET_KINDS),
        "target_descriptions": TARGET_DESCRIPTIONS,
        "weekdays": list(WEEKDAY_LABELS),
        "count": len(schedules),
        "enabled": sum(1 for s in schedules if s["enabled"]),
        "due_now": sum(1 for s in schedules if s["enabled"] and s["due"]),
        "last_tick": last_tick(),
        "tick_driven": True,
        "background_daemon": False,
        "honesty": HONESTY,
    }
