"""THE KEEP-OR-KILL LOOP — measure a bot, then decide on evidence.

Design
------
The decision is a PURE function of one measurement row plus a published rule
version. No model, no judgement, no clock inside the decision: the same numbers
always produce the same verdict, and the verdict can be re-derived by hand from
the arithmetic stored next to it.

Rules, version 1.0.0 (thresholds below):

    success_rate = successes / runs          (undefined when runs = 0)
    net_usd      = revenue_usd - cost_usd
    roi          = revenue_usd / cost_usd    (undefined when cost_usd = 0)

    KILL          if success_rate < 0.60 OR net_usd < -50 OR (runs >= 50 AND roi < 1.0)
    KEEP          if success_rate >= 0.90 AND net_usd > 0 AND runs >= 20
    INCONCLUSIVE  otherwise — stay at MEASURED, record more data

KILL is evaluated first. The two sets cannot overlap: a rate >= 0.90 with a
positive net implies roi > 1, so the third kill clause cannot fire on a
keep-shaped measurement.

Honesty
-------
Nothing here claims a real deployment. A measurement row records numbers that a
human (or a demo seed) supplied; rows marked ``sample`` are demonstration data
and are labelled SAMPLE everywhere they are shown.
"""

from __future__ import annotations

import json
import logging

from . import audit
from . import bot_factory
from . import state_machine as sm
from .db import CURRENT_CONN, LOCK, connect, init_db
from .errors import MeasurementBlocked, OrchestratorError, ValidationError
from .events import canonical, utcnow
from .registry import Component, Registry

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

COMPONENT_NAME = "KeepOrKillLoop"
RULE_VERSION = "1.0.0"
PUBLISHED_AT = "2026-11-01T00:00:00Z"

KEPT = "KEPT"
KILLED = "KILLED"
INCONCLUSIVE = "INCONCLUSIVE"
VERDICTS = (KEPT, KILLED, INCONCLUSIVE)

THRESHOLDS = {
    "keep_success_rate_min": 0.90,
    "keep_net_usd_above": 0.0,
    "keep_runs_min": 20,
    "kill_success_rate_below": 0.60,
    "kill_net_usd_below": -50.0,
    "kill_runs_min": 50,
    "kill_roi_below": 1.0,
}

RULE_DESCRIPTION = (
    "KEEP if success_rate >= 0.90 AND net_usd > 0 AND runs >= 20; "
    "KILL if success_rate < 0.60 OR net_usd < -50 OR (runs >= 50 AND roi < 1.0); "
    "otherwise INCONCLUSIVE (stays MEASURED, more data needed). KILL is evaluated first."
)

HONESTY = (
    "These are recorded measurements, not telemetry from a live bot: no bot built by this "
    "system has been deployed or executed. Rows marked SAMPLE are demonstration data."
)


# --------------------------------------------------------------------------
# Rule versions (published, versioned, stored with every decision)
# --------------------------------------------------------------------------

def ensure_rule_version(conn) -> None:
    conn.execute(
        """INSERT INTO rule_versions (version, component, description, thresholds_json, published_at)
           VALUES (?,?,?,?,?)
           ON CONFLICT(version) DO NOTHING""",
        (RULE_VERSION, COMPONENT_NAME, RULE_DESCRIPTION, canonical(THRESHOLDS), PUBLISHED_AT),
    )


def active_rule() -> dict:
    init_db()
    conn = connect()
    try:
        ensure_rule_version(conn)
        conn.commit()
        row = conn.execute(
            "SELECT * FROM rule_versions WHERE version = ?", (RULE_VERSION,)
        ).fetchone()
    finally:
        conn.close()
    d = dict(row)
    try:
        d["thresholds"] = json.loads(d.pop("thresholds_json") or "{}")
    except (ValueError, TypeError):
        d["thresholds"] = {}
    d["active"] = True
    return d


def list_rules() -> list[dict]:
    init_db()
    conn = connect()
    try:
        ensure_rule_version(conn)
        conn.commit()
        rows = conn.execute(
            "SELECT * FROM rule_versions ORDER BY published_at DESC, version DESC"
        ).fetchall()
    finally:
        conn.close()
    out = []
    for r in rows:
        d = dict(r)
        try:
            d["thresholds"] = json.loads(d.pop("thresholds_json") or "{}")
        except (ValueError, TypeError):
            d["thresholds"] = {}
        d["active"] = d["version"] == RULE_VERSION
        out.append(d)
    return out


# --------------------------------------------------------------------------
# The decision — a pure function of the measurement and the rule version
# --------------------------------------------------------------------------

def _f(value, default=0.0) -> float:
    try:
        return float(value)
    except (TypeError, ValueError):
        return default


def _i(value, default=0) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):
        return default


def decide(measurement: dict, thresholds: dict | None = None) -> dict:
    """Pure: measurement numbers + thresholds in, verdict and arithmetic out."""
    t = dict(THRESHOLDS if thresholds is None else thresholds)
    runs = _i(measurement.get("runs"))
    successes = _i(measurement.get("successes"))
    failures = _i(measurement.get("failures"), runs - successes)
    revenue = _f(measurement.get("revenue_usd"))
    cost = _f(measurement.get("cost_usd"))

    # --- guards (divide-by-zero is made explicit, never silently swallowed) ---
    success_rate = (successes / runs) if runs > 0 else None
    net_usd = round(revenue - cost, 2)
    roi = (revenue / cost) if cost > 0 else None

    arithmetic = {
        "success_rate": (
            f"{successes} / {runs} = {success_rate:.4f}" if success_rate is not None
            else f"{successes} / {runs} is undefined (runs = 0) -> success_rate = None"
        ),
        "net_usd": f"{revenue:.2f} - {cost:.2f} = {net_usd:.2f}",
        "roi": (
            f"{revenue:.2f} / {cost:.2f} = {roi:.4f}" if roi is not None
            else f"{revenue:.2f} / {cost:.2f} is undefined (cost_usd = 0) -> roi = None"
        ),
    }

    warnings = []
    if runs <= 0:
        warnings.append("runs = 0: success_rate cannot be computed, so no KEEP is possible")
    if cost <= 0:
        warnings.append("cost_usd = 0: roi cannot be computed, so the roi kill-clause cannot fire")
    if successes > runs:
        warnings.append(f"successes ({successes}) exceed runs ({runs}): inconsistent input")
    if successes + failures != runs:
        warnings.append(
            f"successes + failures ({successes + failures}) != runs ({runs}): input is inconsistent"
        )

    kill_rate = success_rate is not None and success_rate < t["kill_success_rate_below"]
    kill_net = net_usd < t["kill_net_usd_below"]
    kill_roi = (
        runs >= t["kill_runs_min"] and roi is not None and roi < t["kill_roi_below"]
    )
    keep_rate = success_rate is not None and success_rate >= t["keep_success_rate_min"]
    keep_net = net_usd > t["keep_net_usd_above"]
    keep_runs = runs >= t["keep_runs_min"]

    if kill_rate or kill_net or kill_roi:
        verdict = KILLED
        fired = [
            name for name, hit in (
                (f"success_rate < {t['kill_success_rate_below']}", kill_rate),
                (f"net_usd < {t['kill_net_usd_below']}", kill_net),
                (f"runs >= {t['kill_runs_min']} and roi < {t['kill_roi_below']}", kill_roi),
            ) if hit
        ]
        reason = "KILL matched: " + "; ".join(fired) + f" (rule v{RULE_VERSION})"
    elif keep_rate and keep_net and keep_runs:
        verdict = KEPT
        reason = (
            f"KEEP matched: success_rate {success_rate:.4f} >= {t['keep_success_rate_min']}, "
            f"net_usd {net_usd:.2f} > {t['keep_net_usd_above']}, "
            f"runs {runs} >= {t['keep_runs_min']} (rule v{RULE_VERSION})"
        )
    else:
        verdict = INCONCLUSIVE
        unmet = []
        if not keep_rate:
            unmet.append(
                "success_rate " + ("is undefined" if success_rate is None
                                   else f"{success_rate:.4f}") + f" < {t['keep_success_rate_min']}"
            )
        if not keep_net:
            unmet.append(f"net_usd {net_usd:.2f} is not > {t['keep_net_usd_above']}")
        if not keep_runs:
            unmet.append(f"runs {runs} < {t['keep_runs_min']} (need more data)")
        reason = "INCONCLUSIVE: no KEEP and no KILL condition met — " + "; ".join(unmet)

    return {
        "verdict": verdict,
        "rule_version": RULE_VERSION,
        "rule_description": RULE_DESCRIPTION,
        "thresholds": t,
        "inputs": {
            "runs": runs,
            "successes": successes,
            "failures": failures,
            "revenue_usd": round(revenue, 2),
            "cost_usd": round(cost, 2),
        },
        "derived": {"success_rate": success_rate, "net_usd": net_usd, "roi": roi},
        "arithmetic": arithmetic,
        "checks": {
            "kill_success_rate": kill_rate,
            "kill_net_usd": kill_net,
            "kill_roi": kill_roi,
            "keep_success_rate": keep_rate,
            "keep_net_usd": keep_net,
            "keep_runs": keep_runs,
        },
        "warnings": warnings,
        "reason": reason,
        "sample": bool(measurement.get("sample")),
    }


# --------------------------------------------------------------------------
# Persistence
# --------------------------------------------------------------------------

def _measurement_row(row) -> dict:
    d = dict(row)
    d["sample"] = bool(d.get("sample"))
    return d


def _decision_row(row) -> dict:
    d = dict(row)
    for field in ("inputs_json", "arithmetic_json"):
        key = field.replace("_json", "")
        try:
            d[key] = json.loads(d.get(field) or "{}")
        except (ValueError, TypeError):
            d[key] = {}
        d.pop(field, None)
    return d


def _bot_row(row) -> dict:
    d = bot_factory._decode(row)
    d["status"] = d.get("status") or "SPEC"
    return d


def list_bots() -> list[dict]:
    """Every bot spec with its latest measurement and the verdict on it."""
    init_db()
    out = []
    for bot in bot_factory.list_specs(limit=1000):
        latest = latest_measurement(bot["id"])
        decision = latest_decision(bot["id"])
        bot["latest_measurement"] = latest
        bot["latest_decision"] = decision
        if latest is None:
            bot["current_verdict"] = INCONCLUSIVE
            bot["current_reason"] = "no measurement recorded yet"
        elif decision is not None and decision.get("measurement_id") == latest["id"]:
            bot["current_verdict"] = decision["verdict"]
            bot["current_reason"] = decision["reason"]
        else:
            fresh = decide(latest)
            bot["current_verdict"] = fresh["verdict"]
            bot["current_reason"] = fresh["reason"]
        out.append(bot)
    return out


def get_bot(bot_id: int) -> dict | None:
    bot = bot_factory.get_spec(bot_id)
    if bot is None:
        return None
    bot["measurements"] = list_measurements(bot_id)
    bot["decisions"] = list_decisions(bot_id)
    bot["latest_measurement"] = bot["measurements"][0] if bot["measurements"] else None
    bot["latest_decision"] = bot["decisions"][0] if bot["decisions"] else None
    if bot["latest_measurement"] is None:
        bot["current_verdict"] = INCONCLUSIVE
        bot["current_reason"] = "no measurement recorded yet"
    else:
        fresh = decide(bot["latest_measurement"])
        bot["fresh_decision"] = fresh
        bot["current_verdict"] = (
            bot["latest_decision"]["verdict"]
            if bot["latest_decision"]
            and bot["latest_decision"].get("measurement_id") == bot["latest_measurement"]["id"]
            else fresh["verdict"]
        )
        bot["current_reason"] = fresh["reason"]
    return bot


def list_measurements(bot_id: int, limit: int = 200) -> list[dict]:
    init_db()
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT * FROM bot_measurements WHERE bot_id = ? ORDER BY measured_at DESC, id DESC LIMIT ?",
            (int(bot_id), max(1, min(int(limit), 1000))),
        ).fetchall()
        return [_measurement_row(r) for r in rows]
    finally:
        conn.close()


def latest_measurement(bot_id: int) -> dict | None:
    rows = list_measurements(bot_id, limit=1)
    return rows[0] if rows else None


def get_measurement(measurement_id: int) -> dict | None:
    init_db()
    conn = connect()
    try:
        row = conn.execute(
            "SELECT * FROM bot_measurements WHERE id = ?", (int(measurement_id),)
        ).fetchone()
        return _measurement_row(row) if row else None
    finally:
        conn.close()


def list_decisions(bot_id: int, limit: int = 200) -> list[dict]:
    init_db()
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT * FROM bot_decisions WHERE bot_id = ? ORDER BY id DESC LIMIT ?",
            (int(bot_id), max(1, min(int(limit), 1000))),
        ).fetchall()
        return [_decision_row(r) for r in rows]
    finally:
        conn.close()


def latest_decision(bot_id: int) -> dict | None:
    rows = list_decisions(bot_id, limit=1)
    return rows[0] if rows else None


def all_decisions(limit: int = 200) -> list[dict]:
    init_db()
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT * FROM bot_decisions ORDER BY id DESC LIMIT ?", (max(1, int(limit)),)
        ).fetchall()
        return [_decision_row(r) for r in rows]
    finally:
        conn.close()


def counts() -> dict:
    init_db()
    conn = connect()
    try:
        measurements = conn.execute("SELECT COUNT(*) AS n FROM bot_measurements").fetchone()["n"]
        samples = conn.execute(
            "SELECT COUNT(*) AS n FROM bot_measurements WHERE sample = 1"
        ).fetchone()["n"]
        by_verdict = {
            r["verdict"]: r["n"]
            for r in conn.execute(
                "SELECT verdict, COUNT(*) AS n FROM bot_decisions GROUP BY verdict"
            ).fetchall()
        }
        decisions = conn.execute("SELECT COUNT(*) AS n FROM bot_decisions").fetchone()["n"]
    finally:
        conn.close()
    return {
        "measurements": measurements,
        "sample_measurements": samples,
        "decisions": decisions,
        "by_verdict": {v: by_verdict.get(v, 0) for v in VERDICTS},
        "rule_version": RULE_VERSION,
    }


# --------------------------------------------------------------------------
# Recording a measurement + deciding
# --------------------------------------------------------------------------

def _advance_job(job_id: str, target_states: tuple[str, ...]) -> dict:
    """Push the job through the real state machine until it reaches a target state."""
    from . import service

    trail = []
    try:
        job = service.get_job(job_id)
    except OrchestratorError as exc:
        return {"advanced": False, "reason": str(exc), "trail": trail}
    for _ in range(3):
        state = job["state"]
        if state in target_states:
            return {"advanced": bool(trail), "state": state, "trail": trail}
        if state not in (sm.RUNNING, sm.MEASURED):
            return {
                "advanced": bool(trail),
                "state": state,
                "trail": trail,
                "reason": f"job is at {state}; it only advances from RUNNING/MEASURED here",
            }
        try:
            result = service.advance(job_id)
            trail.append({"from": state, "to": result["job"]["state"],
                          "component": result["component"]})
            job = result["job"]
        except OrchestratorError as exc:
            return {"advanced": bool(trail), "state": job["state"], "trail": trail,
                    "reason": str(exc)}
    return {"advanced": bool(trail), "state": job["state"], "trail": trail}


def record_measurement(
    bot_id: int,
    *,
    runs: int,
    successes: int,
    failures: int | None = None,
    revenue_usd: float = 0.0,
    cost_usd: float = 0.0,
    notes: str = "",
    sample: bool = False,
    measured_at: str | None = None,
    advance_job: bool = True,
) -> dict:
    """Store one measurement, decide on it, and move the job when a verdict is reached."""
    init_db()
    bot = bot_factory.get_spec(bot_id)
    if bot is None:
        raise ValidationError(f"no bot spec with id {bot_id!r}")

    runs = _i(runs, None)
    successes = _i(successes, None)
    if runs is None or successes is None:
        raise ValidationError("runs and successes must be integers")
    if runs < 0 or successes < 0:
        raise ValidationError("runs and successes must be >= 0")
    if successes > runs:
        raise ValidationError(f"successes ({successes}) cannot exceed runs ({runs})")
    if failures is None:
        failures = runs - successes
    failures = _i(failures, None)
    if failures is None or failures < 0:
        raise ValidationError("failures must be an integer >= 0")
    if successes + failures > runs:
        raise ValidationError(
            f"successes + failures ({successes + failures}) cannot exceed runs ({runs})"
        )
    revenue = _f(revenue_usd)
    cost = _f(cost_usd)
    if revenue < 0 or cost < 0:
        raise ValidationError("revenue_usd and cost_usd must be >= 0")

    measured_at = measured_at or utcnow()
    inputs = {"runs": runs, "successes": successes, "failures": failures,
              "revenue_usd": revenue, "cost_usd": cost, "sample": bool(sample)}
    decision = decide(inputs)

    ambient = CURRENT_CONN.get()

    def _work(conn) -> dict:
        ensure_rule_version(conn)
        cur = conn.execute(
            """INSERT INTO bot_measurements
               (bot_id, measured_at, runs, successes, failures, revenue_usd, cost_usd, notes, sample)
               VALUES (?,?,?,?,?,?,?,?,?)""",
            (int(bot_id), measured_at, runs, successes, failures, revenue, cost,
             (notes or "").strip(), 1 if sample else 0),
        )
        measurement_id = cur.lastrowid
        conn.execute(
            """INSERT INTO bot_decisions
               (bot_id, measurement_id, decided_at, rule_version, verdict, inputs_json,
                arithmetic_json, reason)
               VALUES (?,?,?,?,?,?,?,?)""",
            (int(bot_id), measurement_id, measured_at, RULE_VERSION, decision["verdict"],
             canonical(decision["inputs"]), canonical({
                 "arithmetic": decision["arithmetic"],
                 "derived": decision["derived"],
                 "checks": decision["checks"],
                 "thresholds": decision["thresholds"],
                 "warnings": decision["warnings"],
             }), decision["reason"]),
        )
        verdict = decision["verdict"]
        if verdict in (KEPT, KILLED):
            conn.execute(
                "UPDATE bot_specs SET status = ?, retired = ?, retired_at = ? WHERE id = ?",
                (verdict, 1 if verdict == KILLED else 0,
                 measured_at if verdict == KILLED else None, int(bot_id)),
            )

        audit.record(
            COMPONENT_NAME, "measurement.recorded", "bot_spec", bot_id,
            {
                "bot_id": int(bot_id),
                "measurement_id": measurement_id,
                "bot_name": bot["bot_name"],
                "opportunity_id": bot["opportunity_id"],
                "inputs": decision["inputs"],
                "derived": decision["derived"],
                "rule_version": RULE_VERSION,
                "sample": bool(sample),
                "notes": (notes or "").strip(),
                "honesty": HONESTY,
            },
            conn=conn,
            legacy={
                "job_id": bot.get("job_id"),
                "kind": "measurement_recorded",
                "from_state": None,
                "to_state": None,
                "note": (
                    f"{'SAMPLE ' if sample else ''}measurement #{measurement_id} for bot "
                    f"{bot['bot_name']} (id {bot_id}): runs={runs} successes={successes} "
                    f"failures={failures} revenue=${revenue:.2f} cost=${cost:.2f}. "
                    f"success_rate {decision['arithmetic']['success_rate']}; "
                    f"net {decision['arithmetic']['net_usd']}; roi {decision['arithmetic']['roi']}"
                ),
                "data": {"bot_id": int(bot_id), "measurement_id": measurement_id,
                         "inputs": decision["inputs"], "sample": bool(sample)},
            },
        )
        audit.record(
            COMPONENT_NAME, "measurement.verdict", "bot_spec", bot_id,
            {
                "bot_id": int(bot_id),
                "measurement_id": measurement_id,
                "verdict": verdict,
                "rule_version": RULE_VERSION,
                "inputs": decision["inputs"],
                "derived": decision["derived"],
                "arithmetic": decision["arithmetic"],
                "checks": decision["checks"],
                "reason": decision["reason"],
                "sample": bool(sample),
            },
            conn=conn,
        )
        return {"measurement_id": measurement_id}

    if ambient is not None:
        written = _work(ambient)
    else:
        with LOCK:
            conn = connect()
            try:
                written = _work(conn)
                conn.commit()
            except Exception:
                conn.rollback()
                raise
            finally:
                conn.close()

    result = {
        "bot": bot_factory.get_spec(bot_id),
        "measurement": get_measurement(written["measurement_id"]),
        "decision": decision,
        "rule_version": RULE_VERSION,
        "job_advance": {"advanced": False, "reason": "advance_job disabled"},
    }

    if advance_job and bot.get("job_id"):
        verdict = decision["verdict"]
        targets = (sm.MEASURED,) if verdict == INCONCLUSIVE else (verdict,)
        advance = _advance_job(bot["job_id"], targets)
        result["job_advance"] = advance
        result["bot"] = bot_factory.get_spec(bot_id)
        result["job"] = _safe_job(bot["job_id"])
    else:
        result["job"] = _safe_job(bot.get("job_id")) if bot.get("job_id") else None
    return result


def _safe_job(job_id):
    if not job_id:
        return None
    from . import service

    try:
        return service.get_job(job_id)
    except OrchestratorError:
        return None


def decide_for_job(job: dict) -> dict:
    """Latest measurement + verdict for the bot behind this job (no writes)."""
    payload = job.get("payload") or {}
    bot = None
    if payload.get("bot_id"):
        bot = bot_factory.get_spec(payload["bot_id"])
    if bot is None:
        bot = bot_factory.find_spec_for_job(job.get("id"))
    if bot is None:
        raise MeasurementBlocked(
            f"keep-or-kill refused for job {str(job.get('id'))[:8]}: no bot spec is linked to "
            f"this job. Build one from a VERIFIED opportunity first (POST /api/bots/build).",
            verdict=INCONCLUSIVE,
            details={"job_id": job.get("id"), "bot_id": None},
        )
    measurement = latest_measurement(bot["id"])
    if measurement is None:
        raise MeasurementBlocked(
            f"keep-or-kill refused for bot {bot['bot_name']} (id {bot['id']}): no measurement "
            f"has been recorded, and a verdict needs evidence. POST /api/measurement/record "
            f"with runs, successes, revenue and cost.",
            verdict=INCONCLUSIVE,
            details={"bot_id": bot["id"], "measurement": None},
        )
    decision = decide(measurement)
    if decision["verdict"] == INCONCLUSIVE:
        raise MeasurementBlocked(
            f"keep-or-kill stays at MEASURED for bot {bot['bot_name']}: {decision['reason']}. "
            f"Record another measurement when there is more data.",
            verdict=INCONCLUSIVE,
            details={"bot_id": bot["id"], "measurement_id": measurement["id"],
                     "decision": decision},
        )
    return {"bot": bot, "measurement": measurement, "decision": decision}


# --------------------------------------------------------------------------
# The component (handles MEASURED -> KEPT | KILLED)
# --------------------------------------------------------------------------

class KeepOrKillLoop:
    """Registered MEASURED handler: apply rule v1.0.0 to the latest measurement."""

    name = COMPONENT_NAME
    handles_state = sm.MEASURED

    def __call__(self, job: dict) -> dict:
        return self.handle(job)

    def handle(self, job: dict) -> dict:
        found = decide_for_job(job)
        decision = found["decision"]
        bot = found["bot"]
        verdict = decision["verdict"]
        note = (
            f"KEEP-OR-KILL rule v{RULE_VERSION}: {bot['bot_name']} (bot {bot['id']}) -> {verdict}. "
            f"success_rate {decision['arithmetic']['success_rate']}; "
            f"net {decision['arithmetic']['net_usd']}; roi {decision['arithmetic']['roi']}. "
            f"{decision['reason']}"
            + (" SAMPLE measurement (demo data)." if decision.get("sample") else "")
        )
        return {
            "to_state": verdict,
            "note": note,
            "payload_patch": {
                "_decision": {
                    "verdict": verdict,
                    "rule_version": RULE_VERSION,
                    "bot_id": bot["id"],
                    "measurement_id": found["measurement"]["id"],
                    "derived": decision["derived"],
                    "sample": decision.get("sample", False),
                }
            },
            "data": {
                "bot_id": bot["id"],
                "bot_name": bot["bot_name"],
                "measurement_id": found["measurement"]["id"],
                "verdict": verdict,
                "rule_version": RULE_VERSION,
                "inputs": decision["inputs"],
                "derived": decision["derived"],
                "arithmetic": decision["arithmetic"],
                "checks": decision["checks"],
                "reason": decision["reason"],
                "retired": verdict == KILLED,
            },
        }

    def describe(self) -> dict:
        return {
            "name": self.name,
            "handles_state": self.handles_state,
            "kind": "state",
            "description": "Keep-or-kill on evidence: published rule v1.0.0, no model judgement.",
            "rule_version": RULE_VERSION,
        }


def register_keep_or_kill(registry: Registry) -> Component:
    """Register the loop as the MEASURED handler, replacing DecisionStub."""
    loop = KeepOrKillLoop()
    for stale in ("DecisionStub", COMPONENT_NAME):
        if registry.has(stale):
            registry.unregister(stale)
    return registry.register(
        Component(
            name=COMPONENT_NAME,
            handles_state=sm.MEASURED,
            handler=loop,
            description=(
                "Keep-or-kill loop: applies published rule v1.0.0 to the latest recorded "
                "measurement. Refuses with 409 when there is no evidence or the evidence is "
                "inconclusive."
            ),
            produces_state=None,
        )
    )


def rules_document() -> dict:
    rule = active_rule()
    return {
        "component": COMPONENT_NAME,
        "active_rule_version": rule["version"],
        "rule": rule,
        "rule_versions": list_rules(),
        "thresholds": THRESHOLDS,
        "formula": {
            "success_rate": "successes / runs (None when runs = 0)",
            "net_usd": "revenue_usd - cost_usd",
            "roi": "revenue_usd / cost_usd (None when cost_usd = 0)",
        },
        "verdicts": {
            KEPT: "success_rate >= 0.90 AND net_usd > 0 AND runs >= 20",
            KILLED: "success_rate < 0.60 OR net_usd < -50 OR (runs >= 50 AND roi < 1.0)",
            INCONCLUSIVE: "no KEEP and no KILL condition met — stays MEASURED, record more data",
        },
        "precedence": "KILL is evaluated first; the KEEP and KILL sets cannot overlap",
        "deterministic": True,
        "model_calls": 0,
        "stores": "every decision stores the rule version, the exact inputs and the arithmetic",
        "honesty": HONESTY,
    }


# --------------------------------------------------------------------------
# Demo seed — the loop, visibly complete, and labelled as sample data
# --------------------------------------------------------------------------

#: Three scenarios that land on the three possible verdicts. Every row is
#: written with sample=1 and a "SAMPLE:" note, and the UI shows it as SAMPLE.
SAMPLE_SCENARIOS = [
    {
        "verdict": KEPT,
        "runs": 40, "successes": 38, "failures": 2,
        "revenue_usd": 1200.0, "cost_usd": 180.0,
        "notes": ("SAMPLE demonstration measurement (not telemetry): 40 runs, 38 successes, "
                  "$1200 revenue, $180 cost — passes every KEEP condition (rate .95, net +$1020, "
                  "runs >= 20)"),
    },
    {
        "verdict": KILLED,
        "runs": 60, "successes": 30, "failures": 30,
        "revenue_usd": 90.0, "cost_usd": 240.0,
        "notes": ("SAMPLE demonstration measurement (not telemetry): 60 runs, 30 successes, "
                  "$90 revenue, $240 cost — fails on success rate (.50 < .60), net (-$150 < -$50) "
                  "and roi (.375 < 1.0)"),
    },
    {
        "verdict": INCONCLUSIVE,
        "runs": 8, "successes": 8, "failures": 0,
        "revenue_usd": 240.0, "cost_usd": 32.0,
        "notes": ("SAMPLE demonstration measurement (not telemetry): only 8 runs — success rate "
                  "1.0 and net +$208, but runs (8) < 20, so the loop stays at MEASURED"),
    },
]


def _verified_opportunities(limit: int = 3) -> list[dict]:
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT * FROM opportunities WHERE verdict = 'VERIFIED' "
            "ORDER BY composite_score DESC, id ASC LIMIT ?",
            (limit,),
        ).fetchall()
        return [dict(r) for r in rows]
    finally:
        conn.close()


def _drive_job_to_measured(job_id: str) -> dict:
    """Advance VERIFIED -> BOT_BUILT -> RUNNING -> MEASURED through the real machine.

    Every edge here is deterministic and offline: the factory reuses the spec that
    already carries this job_id, RunnerStub is a dry run and MeasurementStub only
    counts structure. No network call is made.
    """
    from . import service

    trail = []
    try:
        job = service.get_job(job_id)
    except OrchestratorError as exc:
        return {"advanced": False, "reason": str(exc), "trail": trail}
    for _ in range(4):
        if job["state"] == sm.MEASURED:
            return {"advanced": True, "state": sm.MEASURED, "trail": trail}
        if job["state"] not in (sm.VERIFIED, sm.BOT_BUILT, sm.RUNNING):
            return {"advanced": bool(trail), "state": job["state"], "trail": trail}
        try:
            result = service.advance(job_id)
            trail.append({"from": job["state"], "to": result["job"]["state"],
                          "component": result["component"]})
            job = result["job"]
        except OrchestratorError as exc:
            return {"advanced": bool(trail), "state": job["state"], "trail": trail,
                    "reason": str(exc)}
    return {"advanced": bool(trail), "state": job["state"], "trail": trail}


def seed_demo_if_empty(write_audit: bool = True) -> dict:
    """Build specs and SAMPLE measurements for the real VERIFIED opportunities.

    Uses only opportunities that already exist and are already VERIFIED — it does
    not invent opportunities. Runs once: if any bot spec exists it does nothing.
    """
    init_db()
    if bot_factory.counts()["total"]:
        return {"created": 0, "reason": "bot specs already exist"}

    opps = _verified_opportunities(limit=3)
    if not opps:
        return {"created": 0, "reason": "no VERIFIED opportunities in the database yet"}

    created = []
    for index, opp in enumerate(opps):
        # Link a job only when one already exists at VERIFIED; never create a job
        # here (that would need a fresh network verification).
        job_id = opp.get("job_id")
        if job_id:
            job = _safe_job(job_id)
            if job is None or job["state"] != sm.VERIFIED:
                job_id = None
        built = bot_factory.build_bot(opp["id"], trigger="demo-seed", job_id=job_id,
                                      write_audit=write_audit)
        bot = built["bot"]
        job_trail = None
        if job_id:
            job_trail = _drive_job_to_measured(job_id)

        scenario = SAMPLE_SCENARIOS[index % len(SAMPLE_SCENARIOS)]
        result = record_measurement(
            bot["id"],
            runs=scenario["runs"],
            successes=scenario["successes"],
            failures=scenario["failures"],
            revenue_usd=scenario["revenue_usd"],
            cost_usd=scenario["cost_usd"],
            notes=scenario["notes"],
            sample=True,
        )
        created.append({
            "bot_id": bot["id"],
            "bot_name": bot["bot_name"],
            "opportunity_id": opp["id"],
            "job_id": job_id,
            "job_trail": job_trail,
            "expected_verdict": scenario["verdict"],
            "verdict": result["decision"]["verdict"],
            "measurement_id": result["measurement"]["id"],
            "job_advance": result["job_advance"],
        })
    log.info("demo seed: %d bot spec(s) + sample measurement(s)", len(created))
    return {"created": len(created), "bots": created, "sample": True}
