"""Tests for the BOT FACTORY and the MEASUREMENT / KEEP-OR-KILL LOOP.

Covers, as required:
  (a) the factory refuses an unverified opportunity with 409 (component AND gate)
  (b) spec_hash is stable across two builds of the same opportunity
  (c) cost / value / ROI arithmetic matches the documented formula
  (d) KEEP, KILL and INCONCLUSIVE are each triggered by the right inputs
  (e) the divide-by-zero guards (runs = 0, cost = 0)
  (f) every decision stores the rule version it was made under
  (g) KILLED retires the spec but never deletes it
  (h) the audit chain still verifies after all of it

No test touches the network: signals are inserted straight into SQLite and the
verification fetcher is mocked.
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-bot-test-")
os.environ.setdefault("JARVIS_DB", os.path.join(_TMP, "test.db"))

from orchestrator import audit  # noqa: E402
from orchestrator import bot_factory  # noqa: E402
from orchestrator import ingestion  # noqa: E402
from orchestrator import measurement  # noqa: E402
from orchestrator import opportunity  # noqa: E402
from orchestrator import service  # noqa: E402
from orchestrator import state_machine as sm  # noqa: E402
from orchestrator import verification  # noqa: E402
from orchestrator.components import register_default_components  # noqa: E402
from orchestrator.db import connect, init_db  # noqa: E402
from orchestrator.errors import BotBuildBlocked, MeasurementBlocked, ValidationError  # noqa: E402
from orchestrator.registry import REGISTRY  # noqa: E402


# --------------------------------------------------------------------------
# fixtures / helpers
# --------------------------------------------------------------------------

@pytest.fixture(autouse=True)
def fresh_db():
    db = os.environ["JARVIS_DB"]
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(db + suffix)
        except FileNotFoundError:
            pass
    init_db()
    REGISTRY.clear()
    register_default_components(REGISTRY)
    yield
    REGISTRY.clear()
    register_default_components(REGISTRY)


def store_signal(source, title, url, summary="", rank=1):
    sig = ingestion.normalize_item(source, title=title, url=url, summary=summary, rank=rank)
    conn = connect()
    try:
        ingestion._insert_signal(conn, sig)
        conn.commit()
    finally:
        conn.close()
    return sig


def make_opportunity(n=3):
    """Store n signals in one topic cluster and run the engine -> one opportunity."""
    titles = [
        "OpenAI ships a new agent API for developers",
        "Google expands Gemini agent tasks for teams",
        "A local LLM agent inference tool ships",
        "Anthropic releases an agent SDK for models",
    ][:n]
    for i, title in enumerate(titles):
        store_signal(
            ["hackernews", "rss/techcrunch", "rss/lobsters", "rss/bbc-business"][i % 4],
            title,
            f"https://ex.invalid/{i}",
            "agent model tooling",
        )
    run = opportunity.run_engine()
    assert run["produced"] >= 1, run
    return opportunity.list_opportunities()[0]


def fetcher_from(mapping):
    def fetch(url, **_kw):
        value = mapping.get(url)
        if callable(value):
            return value(url)
        if value is None:
            return {"ok": False, "http_status": None, "body": b"", "content_type": "",
                    "error": "network error: no route to host", "error_kind": "network",
                    "final_url": url, "duration_ms": 1}
        return value
    return fetch


def ok(url, title):
    body = ("<html><body><h1>" + title + "</h1><p>" + ("context " * 60) +
            "</p></body></html>").encode()
    return {"ok": True, "http_status": 200, "body": body,
            "content_type": "text/html; charset=utf-8", "error": None,
            "error_kind": None, "final_url": url, "duration_ms": 1}


def fail(url, status=None, error="network error: connection refused", kind="network"):
    return {"ok": False, "http_status": status, "body": b"", "content_type": "",
            "error": error, "error_kind": kind, "final_url": url, "duration_ms": 1}


def verified_opportunity(monkeypatch, n=3):
    """A real opportunity whose citations all re-confirm -> stored verdict VERIFIED."""
    opp = make_opportunity(n)
    claims = {e["url"]: e["title"] for e in opp["evidence"]}
    monkeypatch.setattr(verification, "FETCHER",
                        fetcher_from({u: ok(u, t) for u, t in claims.items()}))
    run = verification.verify_opportunity(opp["id"], trigger="test")
    assert run["verdict"] == verification.VERIFIED
    return opportunity.get_opportunity(opp["id"])


def unverified_opportunity(monkeypatch):
    opp = make_opportunity(3)
    monkeypatch.setattr(verification, "FETCHER",
                        fetcher_from({e["url"]: fail(e["url"]) for e in opp["evidence"]}))
    run = verification.verify_opportunity(opp["id"], trigger="test")
    assert run["verdict"] == verification.UNVERIFIED
    return opportunity.get_opportunity(opp["id"])


# --------------------------------------------------------------------------
# (a) the factory refuses anything that is not VERIFIED — 409, at both points
# --------------------------------------------------------------------------

def test_factory_refuses_unverified_opportunity_with_409(monkeypatch):
    opp = unverified_opportunity(monkeypatch)
    with pytest.raises(BotBuildBlocked) as exc:
        bot_factory.build_bot(opp["id"], trigger="test")
    assert exc.value.status == 409
    assert exc.value.code == "bot_build_refused"
    # the message names the verdict and the blocking reason
    assert "UNVERIFIED" in str(exc.value)
    assert "Only a VERIFIED opportunity" in str(exc.value)
    assert exc.value.details["blocking_signal_ids"]
    # nothing was persisted
    assert bot_factory.counts()["total"] == 0


def test_factory_refuses_opportunity_with_no_verdict_at_all():
    opp = make_opportunity(3)  # never verified
    assert opp["verdict"] is None
    with pytest.raises(BotBuildBlocked) as exc:
        bot_factory.build_bot(opp["id"], trigger="test")
    assert exc.value.status == 409
    assert "NO VERDICT" in str(exc.value) or "not VERIFIED" in str(exc.value)
    assert bot_factory.counts()["total"] == 0


def test_state_machine_gate_refuses_verified_to_bot_built_without_verdict(monkeypatch):
    """Second enforcement point: the boundary itself refuses, inside advance()."""
    opp = unverified_opportunity(monkeypatch)
    job = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)["job"]
    # force the job into VERIFIED behind the gate's back (simulating old data)
    conn = connect()
    try:
        conn.execute("UPDATE jobs SET state = ? WHERE id = ?", (sm.VERIFIED, job["id"]))
        conn.commit()
    finally:
        conn.close()
    with pytest.raises(BotBuildBlocked) as exc:
        service.advance(job["id"], registry=REGISTRY)
    assert exc.value.status == 409
    assert service.get_job(job["id"])["state"] == sm.VERIFIED
    assert bot_factory.counts()["total"] == 0


def test_factory_refuses_a_job_with_no_opportunity():
    job = service.create_job("bare job", "pytest", {"k": "v"}, registry=REGISTRY)
    service.advance(job["id"], registry=REGISTRY)  # -> VERIFIED (cites nothing)
    with pytest.raises(BotBuildBlocked) as exc:
        service.advance(job["id"], registry=REGISTRY)  # -> BOT_BUILT
    assert exc.value.status == 409
    assert "no opportunity_id" in str(exc.value)
    assert service.get_job(job["id"])["state"] == sm.VERIFIED


def test_api_build_returns_409_json(monkeypatch):
    opp = unverified_opportunity(monkeypatch)
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        r = c.post("/api/bots/build", json={"opportunity_id": opp["id"]})
        assert r.status_code == 409
        body = r.get_json()
        assert body["error"] == "bot_build_refused"
        assert body["verdict"] == "UNVERIFIED"
        assert "Only a VERIFIED opportunity" in body["message"]


# --------------------------------------------------------------------------
# (b) determinism: same opportunity -> same spec -> same spec_hash
# --------------------------------------------------------------------------

def test_spec_hash_is_stable_across_two_builds(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    first = bot_factory.build_bot(opp["id"], trigger="test")
    second = bot_factory.build_bot(opp["id"], trigger="test", force=True)
    assert first["created"] is True and second["created"] is True
    assert first["bot"]["id"] != second["bot"]["id"]
    assert first["bot"]["spec_hash"] == second["bot"]["spec_hash"]
    # and the pure builder agrees, with no clock and no randomness involved
    assert bot_factory.spec_hash(bot_factory.build_spec(opp)) == first["bot"]["spec_hash"]
    assert first["spec"] == second["spec"]


def test_spec_hash_changes_when_the_spec_changes(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    spec = bot_factory.build_spec(opp)
    before = bot_factory.spec_hash(spec)
    spec["purpose"] = spec["purpose"] + " (edited)"
    assert bot_factory.spec_hash(spec) != before


def test_bot_name_is_deterministic_and_derived_from_the_topic(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    name = bot_factory.bot_name_for(opp)
    assert name == bot_factory.bot_name_for(dict(opp))
    assert name.startswith("bot-")
    assert name.endswith(bot_factory.hashlib.sha256(opp["id"].encode()).hexdigest()[:6])


def test_stored_hash_still_matches_the_stored_spec(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    bot = bot_factory.build_bot(opp["id"], trigger="test")["bot"]
    assert bot["hash_ok"] is True
    assert bot_factory.spec_hash(json.loads(bot["spec_json"])) == bot["spec_hash"]


# --------------------------------------------------------------------------
# (c) the arithmetic matches the documented formulas
# --------------------------------------------------------------------------

def test_cost_arithmetic_matches_the_documented_formula(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    spec = bot_factory.build_spec(opp)
    cost = spec["cost_model"]

    runs = cost["runs_per_month"]
    steps = len(spec["steps"])
    per_run = bot_factory.COST_PER_RUN_BASE_USD + bot_factory.COST_PER_STEP_USD * steps
    variable = runs * per_run
    expected_total = round(variable + bot_factory.FIXED_INFRA_USD, 2)

    assert cost["step_count"] == steps
    assert cost["cost_per_run_usd"] == pytest.approx(per_run)
    assert cost["variable_cost_usd"] == pytest.approx(round(variable, 2))
    assert cost["estimated_monthly_cost_usd"] == pytest.approx(expected_total)
    assert spec["estimated_monthly_cost_usd"] == pytest.approx(expected_total)
    # the arithmetic is stored as a string so it can be audited by eye
    assert f"{runs} runs * ${per_run:.4f}/run" in cost["arithmetic"]
    assert f"${bot_factory.FIXED_INFRA_USD:.2f} fixed" in cost["arithmetic"]


def test_value_arithmetic_matches_the_documented_formula(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    spec = bot_factory.build_spec(opp)
    value = spec["value_model"]
    money = spec["opportunity"]["scores"]["money_potential"]
    feas = spec["opportunity"]["scores"]["feasibility"]
    expected = round((money / 100.0) * (feas / 100.0) * bot_factory.VALUE_CEILING_USD, 2)

    assert value["money_potential"] == money
    assert value["feasibility"] == feas
    assert value["estimated_monthly_value_usd"] == pytest.approx(expected)
    assert spec["estimated_monthly_value_usd"] == pytest.approx(expected)
    assert value["arithmetic"] == (
        f"{money}/100 * {feas}/100 * ${bot_factory.VALUE_CEILING_USD:.2f} = ${expected:.2f}"
    )


def test_roi_is_value_over_cost(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    spec = bot_factory.build_spec(opp)
    expected = round(spec["estimated_monthly_value_usd"] / spec["estimated_monthly_cost_usd"], 2)
    assert spec["roi_ratio"] == pytest.approx(expected)
    assert spec["roi_arithmetic"] == (
        f"${spec['estimated_monthly_value_usd']:.2f} value / "
        f"${spec['estimated_monthly_cost_usd']:.2f} cost = {spec['roi_ratio']}"
    )


def test_allowlist_and_denylist_are_disjoint_and_stored(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    bot = bot_factory.build_bot(opp["id"], trigger="test")["bot"]
    spec = bot["spec"]
    assert spec["allowed_actions"], "the allowlist must never be empty"
    assert set(spec["allowed_actions"]) & set(spec["denied_actions"]) == set()
    for forbidden in ("send_money", "delete_data", "contact_list_without_approval"):
        assert forbidden in spec["denied_actions"]
    # the boundary is persisted with the spec, not just rendered
    assert spec["safety_boundary"]["allowlist"] == spec["allowed_actions"]
    assert spec["safety_boundary"]["denylist"] == spec["denied_actions"]


def test_high_risk_spec_requires_human_approval(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    spec = bot_factory.build_spec(opp)
    if spec["risk_level"] == "high":
        assert spec["requires_human_approval"] is True
        assert spec["approval_reason"]
    else:
        assert spec["requires_human_approval"] == bool(
            spec["safety_boundary"]["adjacent_denied_actions"]
        )


# --------------------------------------------------------------------------
# (d) KEEP / KILL / INCONCLUSIVE from the right inputs
# --------------------------------------------------------------------------

def test_keep_verdict_from_passing_inputs():
    d = measurement.decide({"runs": 40, "successes": 38, "revenue_usd": 1200, "cost_usd": 180})
    assert d["verdict"] == measurement.KEPT
    assert d["derived"]["success_rate"] == pytest.approx(0.95)
    assert d["derived"]["net_usd"] == pytest.approx(1020.0)
    assert d["derived"]["roi"] == pytest.approx(1200 / 180)
    assert d["checks"]["keep_success_rate"] and d["checks"]["keep_net_usd"] and d["checks"]["keep_runs"]


def test_kill_verdict_from_failing_inputs():
    d = measurement.decide({"runs": 60, "successes": 30, "revenue_usd": 90, "cost_usd": 240})
    assert d["verdict"] == measurement.KILLED
    assert d["derived"]["success_rate"] == pytest.approx(0.5)
    assert d["derived"]["net_usd"] == pytest.approx(-150.0)
    assert d["checks"]["kill_success_rate"] and d["checks"]["kill_net_usd"]
    assert d["checks"]["kill_roi"]


def test_inconclusive_when_there_is_too_little_data():
    d = measurement.decide({"runs": 8, "successes": 8, "revenue_usd": 240, "cost_usd": 32})
    assert d["verdict"] == measurement.INCONCLUSIVE
    assert d["checks"]["keep_runs"] is False
    assert "need more data" in d["reason"] or "runs 8 < 20" in d["reason"]


def test_kill_wins_over_keep_when_both_could_apply():
    """KILL is evaluated first: a high rate cannot save a large loss."""
    d = measurement.decide({"runs": 100, "successes": 95, "revenue_usd": 10, "cost_usd": 200})
    assert d["derived"]["success_rate"] == pytest.approx(0.95)
    assert d["verdict"] == measurement.KILLED
    assert d["checks"]["kill_net_usd"] is True


def test_keep_needs_the_run_floor():
    d = measurement.decide({"runs": 19, "successes": 19, "revenue_usd": 500, "cost_usd": 10})
    assert d["verdict"] == measurement.INCONCLUSIVE
    assert d["checks"]["keep_runs"] is False


def test_roi_kill_clause_needs_enough_runs():
    """The THIRD kill clause: runs >= 50 AND roi < 1.0.

    Isolated on purpose: the inputs below pass the other two kill clauses
    (success_rate >= 0.60, net_usd >= -50) and fail only the keep conditions, so
    only the roi clause can produce the KILL.
    """
    # runs = 60, rate 40/60 = 0.6667 (>= 0.60), net -40.00 (>= -50), roi 0.60 < 1.0
    enough = measurement.decide(
        {"runs": 60, "successes": 40, "failures": 20, "revenue_usd": 60, "cost_usd": 100}
    )
    assert enough["derived"]["success_rate"] >= measurement.THRESHOLDS["kill_success_rate_below"]
    assert enough["derived"]["net_usd"] >= measurement.THRESHOLDS["kill_net_usd_below"]
    assert enough["derived"]["roi"] < measurement.THRESHOLDS["kill_roi_below"]
    assert enough["checks"]["kill_success_rate"] is False
    assert enough["checks"]["kill_net_usd"] is False
    assert enough["checks"]["kill_roi"] is True
    assert enough["verdict"] == measurement.KILLED
    assert f"runs >= {measurement.THRESHOLDS['kill_runs_min']}" in enough["reason"]

    # Companion: runs = 49 with the SAME rate/net/roi -> the roi clause cannot fire.
    few = measurement.decide(
        {"runs": 49, "successes": 40, "failures": 9, "revenue_usd": 60, "cost_usd": 100}
    )
    assert few["inputs"]["runs"] == measurement.THRESHOLDS["kill_runs_min"] - 1
    assert few["derived"]["roi"] < measurement.THRESHOLDS["kill_roi_below"]
    assert few["derived"]["success_rate"] >= measurement.THRESHOLDS["kill_success_rate_below"]
    assert few["derived"]["net_usd"] >= measurement.THRESHOLDS["kill_net_usd_below"]
    assert few["checks"]["kill_roi"] is False
    assert few["checks"]["kill_success_rate"] is False
    assert few["checks"]["kill_net_usd"] is False
    assert few["verdict"] == measurement.INCONCLUSIVE
    assert not few["reason"].startswith("KILL matched")


# --------------------------------------------------------------------------
# (e) divide-by-zero guards
# --------------------------------------------------------------------------

def test_zero_runs_guard_makes_success_rate_none():
    d = measurement.decide({"runs": 0, "successes": 0, "revenue_usd": 0, "cost_usd": 0})
    assert d["derived"]["success_rate"] is None
    assert d["verdict"] == measurement.INCONCLUSIVE
    assert "undefined (runs = 0)" in d["arithmetic"]["success_rate"]
    assert any("runs = 0" in w for w in d["warnings"])


def test_zero_cost_guard_makes_roi_none():
    d = measurement.decide({"runs": 40, "successes": 38, "revenue_usd": 1200, "cost_usd": 0})
    assert d["derived"]["roi"] is None
    assert "undefined (cost_usd = 0)" in d["arithmetic"]["roi"]
    assert d["checks"]["kill_roi"] is False
    # a free bot with a good rate and positive net is still a KEEP
    assert d["verdict"] == measurement.KEPT


def test_zero_runs_and_zero_cost_together_never_raise():
    d = measurement.decide({"runs": 0, "successes": 0, "revenue_usd": 0, "cost_usd": 0})
    assert d["verdict"] == measurement.INCONCLUSIVE
    assert len(d["warnings"]) >= 2


def test_inconsistent_inputs_are_warned_about_not_hidden():
    d = measurement.decide({"runs": 10, "successes": 12, "revenue_usd": 0, "cost_usd": 0})
    assert any("exceed runs" in w for w in d["warnings"])


def test_record_measurement_rejects_successes_above_runs(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    bot = bot_factory.build_bot(opp["id"], trigger="test")["bot"]
    with pytest.raises(ValidationError):
        measurement.record_measurement(bot["id"], runs=5, successes=9, advance_job=False)
    with pytest.raises(ValidationError):
        measurement.record_measurement(bot["id"], runs=-1, successes=0, advance_job=False)


# --------------------------------------------------------------------------
# (f) every decision stores the rule version it was made under
# --------------------------------------------------------------------------

def test_decision_stores_the_rule_version_and_the_arithmetic(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    bot = bot_factory.build_bot(opp["id"], trigger="test")["bot"]
    result = measurement.record_measurement(
        bot["id"], runs=40, successes=38, revenue_usd=1200, cost_usd=180,
        notes="pytest", advance_job=False,
    )
    assert result["rule_version"] == measurement.RULE_VERSION
    stored = measurement.latest_decision(bot["id"])
    assert stored["rule_version"] == measurement.RULE_VERSION
    assert stored["verdict"] == measurement.KEPT
    assert stored["inputs"]["runs"] == 40
    assert stored["arithmetic"]["arithmetic"]["success_rate"] == "38 / 40 = 0.9500"
    assert stored["arithmetic"]["arithmetic"]["net_usd"] == "1200.00 - 180.00 = 1020.00"
    assert stored["measurement_id"] == result["measurement"]["id"]


def test_rule_version_row_is_published_with_the_thresholds():
    rule = measurement.active_rule()
    assert rule["version"] == measurement.RULE_VERSION
    assert rule["thresholds"]["keep_success_rate_min"] == 0.90
    assert rule["thresholds"]["kill_success_rate_below"] == 0.60
    assert rule["thresholds"]["kill_net_usd_below"] == -50.0
    assert rule["thresholds"]["keep_runs_min"] == 20
    assert rule["thresholds"]["kill_runs_min"] == 50
    doc = measurement.rules_document()
    assert doc["active_rule_version"] == measurement.RULE_VERSION
    assert doc["model_calls"] == 0


def test_measurement_rules_route_serves_the_active_version():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        r = c.get("/measurement/rules")
        assert r.status_code == 200
        body = r.get_json()
        assert body["active_rule_version"] == measurement.RULE_VERSION
        assert body["thresholds"]["keep_success_rate_min"] == 0.90


# --------------------------------------------------------------------------
# (g) KILLED retires the spec but never deletes it
# --------------------------------------------------------------------------

def test_killed_retires_but_does_not_delete(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    bot = bot_factory.build_bot(opp["id"], trigger="test")["bot"]
    result = measurement.record_measurement(
        bot["id"], runs=60, successes=30, revenue_usd=90, cost_usd=240,
        notes="pytest kill", advance_job=False,
    )
    assert result["decision"]["verdict"] == measurement.KILLED

    still_there = bot_factory.get_spec(bot["id"])
    assert still_there is not None, "a killed bot must never be deleted"
    assert still_there["retired"] is True
    assert still_there["retired_at"]
    assert still_there["status"] == measurement.KILLED
    # the history survives: spec, measurement and decision are all still readable
    assert still_there["spec_hash"] == bot["spec_hash"]
    assert measurement.list_measurements(bot["id"])
    assert measurement.list_decisions(bot["id"])
    # and it is still counted, not hidden
    assert bot_factory.counts()["retired"] >= 1


def test_kept_does_not_retire(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    bot = bot_factory.build_bot(opp["id"], trigger="test")["bot"]
    measurement.record_measurement(
        bot["id"], runs=40, successes=38, revenue_usd=1200, cost_usd=180, advance_job=False,
    )
    kept = bot_factory.get_spec(bot["id"])
    assert kept["status"] == measurement.KEPT
    assert kept["retired"] is False


def test_verdict_advances_the_job_through_the_state_machine(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    job = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)["job"]
    for _ in range(3):  # INGESTED -> VERIFIED -> BOT_BUILT -> RUNNING
        service.advance(job["id"], registry=REGISTRY)
    bot = bot_factory.find_spec_for_job(job["id"])
    assert bot is not None

    # RUNNING -> MEASURED is the measurement stub's dry run, not a verdict
    assert service.advance(job["id"], registry=REGISTRY)["job"]["state"] == sm.MEASURED

    # INCONCLUSIVE keeps the job at MEASURED
    measurement.record_measurement(
        bot["id"], runs=8, successes=8, revenue_usd=240, cost_usd=32, advance_job=False,
    )
    with pytest.raises(MeasurementBlocked):
        service.advance(job["id"], registry=REGISTRY)
    assert service.get_job(job["id"])["state"] == sm.MEASURED

    # KILLED advances it to KILLED and retires the spec
    measurement.record_measurement(
        bot["id"], runs=60, successes=30, revenue_usd=90, cost_usd=240, advance_job=False,
    )
    step = service.advance(job["id"], registry=REGISTRY)
    assert step["component"] == "KeepOrKillLoop"
    assert step["job"]["state"] == sm.KILLED
    assert sm.is_terminal(step["job"]["state"])
    assert bot_factory.get_spec(bot["id"])["retired"] is True


def test_kept_advances_the_job_to_kept(monkeypatch):
    """A KEEP verdict only moves a job that is already at MEASURED.

    INGESTED -> VERIFIED -> BOT_BUILT -> RUNNING -> MEASURED must happen first, and
    every one of those edges goes through the REAL registered component.
    """
    opp = verified_opportunity(monkeypatch)
    job = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)["job"]

    seen = []
    for _ in range(4):  # INGESTED -> VERIFIED -> BOT_BUILT -> RUNNING -> MEASURED
        service.advance(job["id"], registry=REGISTRY)
        seen.append(service.get_job(job["id"])["state"])
    assert seen == [sm.VERIFIED, sm.BOT_BUILT, sm.RUNNING, sm.MEASURED]

    bot = bot_factory.find_spec_for_job(job["id"])
    assert bot is not None
    measurement.record_measurement(
        bot["id"], runs=40, successes=38, revenue_usd=1200, cost_usd=180, advance_job=False,
    )
    step = service.advance(job["id"], registry=REGISTRY)
    assert step["component"] == "KeepOrKillLoop"
    assert step["job"]["state"] == sm.KEPT


# --------------------------------------------------------------------------
# (h) the audit chain still verifies after all of it
# --------------------------------------------------------------------------

def test_audit_chain_verifies_after_build_and_measurement(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    bot = bot_factory.build_bot(opp["id"], trigger="test")["bot"]
    measurement.record_measurement(
        bot["id"], runs=40, successes=38, revenue_usd=1200, cost_usd=180, advance_job=False,
    )
    measurement.record_measurement(
        bot["id"], runs=60, successes=30, revenue_usd=90, cost_usd=240, advance_job=False,
    )
    state = audit.verify()
    assert state["ok"] is True
    assert state["length"] > 0
    assert state["first_broken_seq"] is None


def test_every_bot_action_is_written_to_the_audit_log(monkeypatch):
    opp = verified_opportunity(monkeypatch)
    bot = bot_factory.build_bot(opp["id"], trigger="test")["bot"]
    measurement.record_measurement(
        bot["id"], runs=40, successes=38, revenue_usd=1200, cost_usd=180, advance_job=False,
    )
    events = audit.recent(limit=500)
    kinds = {e["action"] for e in events}
    assert "bot.spec.created" in kinds
    assert "measurement.recorded" in kinds
    assert "measurement.verdict" in kinds
    created = [e for e in events if e["action"] == "bot.spec.created"][0]
    assert created["payload"]["spec_hash"] == bot["spec_hash"]
    assert created["payload"]["model_calls"] == 0
    assert created["payload"]["deployed"] is False


# --------------------------------------------------------------------------
# the demo seed: three verdicts, all labelled SAMPLE
# --------------------------------------------------------------------------

#: One signal set per topic cluster. Each set lands in a DIFFERENT topic, so the
#: engine produces three separate opportunities (never one cluster pretending to
#: be three).
SEED_CLUSTERS = {
    "ai-tooling": [
        ("OpenAI ships a new agent API for developers", "agent model tooling"),
        ("Google expands Gemini agent tasks for teams", "agent model inference"),
    ],
    "dev-tools": [
        ("Rust compiler open source release adds a new tool", "developer programming code"),
        ("GitHub SDK framework ships for developer programming", "open source code tool"),
    ],
    "security-compliance": [
        ("Major breach exposes a vulnerability in office software", "security attack privacy"),
        ("Ransomware attack triggers a privacy investigation", "security compliance lawsuit"),
    ],
}


def _db_verified_ids():
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT id FROM opportunities WHERE verdict = ? ORDER BY id", ("VERIFIED",)
        ).fetchall()
        return [r["id"] for r in rows]
    finally:
        conn.close()


def ensure_three_verified_opportunities(monkeypatch):
    """Three DISTINCT VERIFIED opportunity ids, created the real way if missing.

    Reads the DB first. While fewer than three verified opportunities exist, it
    stores real signals for the next untouched topic and runs the real engine
    (never an invented opportunity row), then verifies each new opportunity
    through the real verification layer with a mocked fetcher.
    """
    ids = _db_verified_ids()
    pending = list(SEED_CLUSTERS.items())
    while len(ids) < 3:
        assert pending, f"only {len(ids)} verified opportunity(ies) could be produced"
        _topic, items = pending.pop(0)
        for j, (title, summary) in enumerate(items):
            store_signal(
                ["hackernews", "rss/techcrunch", "rss/lobsters"][j % 3],
                title,
                f"https://ex.invalid/seed-{_topic}-{j}",
                summary,
            )
        run = opportunity.run_engine()
        assert run["produced"] >= 1, run
        for opp in opportunity.list_opportunities():
            if opp["verdict"] == verification.VERIFIED:
                continue
            claims = {e["url"]: e["title"] for e in opp["evidence"]}
            monkeypatch.setattr(
                verification, "FETCHER", fetcher_from({u: ok(u, t) for u, t in claims.items()})
            )
            verification.verify_opportunity(opp["id"], trigger="test")
        ids = _db_verified_ids()
    assert len(ids) >= 3
    return ids


def test_demo_seed_produces_all_three_verdicts_and_labels_them_sample(monkeypatch):
    verified_ids = ensure_three_verified_opportunities(monkeypatch)
    assert len(set(verified_ids)) >= 3
    result = measurement.seed_demo_if_empty()
    assert result["created"] == 3
    # three SEPARATE specs, one per distinct verified opportunity
    assert len({b["bot_id"] for b in result["bots"]}) == 3
    assert len({b["opportunity_id"] for b in result["bots"]}) == 3
    assert {b["opportunity_id"] for b in result["bots"]} <= set(verified_ids)
    verdicts = [b["verdict"] for b in result["bots"]]
    assert set(verdicts) == {measurement.KEPT, measurement.KILLED, measurement.INCONCLUSIVE}
    assert sorted(verdicts) == sorted(
        [measurement.KEPT, measurement.KILLED, measurement.INCONCLUSIVE]
    )
    for b in result["bots"]:
        m = measurement.get_measurement(b["measurement_id"])
        assert m["sample"] is True
        assert "SAMPLE" in m["notes"]
    assert measurement.counts()["sample_measurements"] == 3
    # idempotent: a second call writes nothing
    assert measurement.seed_demo_if_empty()["created"] == 0


def test_demo_seed_does_not_invent_opportunities(monkeypatch):
    """No VERIFIED opportunity -> no bot specs. It never fabricates one."""
    make_opportunity(3)  # exists but is not verified
    result = measurement.seed_demo_if_empty()
    assert result["created"] == 0
    assert bot_factory.counts()["total"] == 0
