"""Tests for the JARVIS Orchestrator.

Covers the four required areas:
  1. legal transition succeeds
  2. illegal transition is rejected
  3. event log hash chain is intact (and detects tampering)
  4. component registry routing works

Run:  pytest -q
"""

from __future__ import annotations

import os
import sqlite3
import tempfile

import pytest

# Point the DB at a throwaway file BEFORE importing the app modules.
_TMP = tempfile.mkdtemp(prefix="jarvis-test-")
os.environ["JARVIS_DB"] = os.path.join(_TMP, "test.db")

from orchestrator import bot_factory  # noqa: E402
from orchestrator import measurement  # 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 (  # noqa: E402
    BotBuildBlocked,
    IllegalTransition,
    MeasurementBlocked,
    NoComponent,
    RegistryError,
    ValidationError,
)
from orchestrator.events import GENESIS, verify_chain  # noqa: E402
from orchestrator.registry import REGISTRY, Component, Registry  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_db():
    """Fresh DB + fresh registry for every test."""
    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 make_job(title="test job", source="pytest"):
    return service.create_job(title, source, {"k": "v"}, registry=REGISTRY)


def make_verified_job(monkeypatch):
    """A queued job at INGESTED whose opportunity is really VERIFIED.

    Builds a real opportunity from stored signals, mocks the fetcher so every
    citation re-confirms its claim, runs the real verification layer, then queues
    the job through the normal intake. Nothing touches the network and nothing is
    fabricated: the VERIFIED verdict comes from real verification evidence, which
    the bot factory now requires before it will build a spec.
    """
    from orchestrator import ingestion, opportunity

    for i, title in enumerate([
        "OpenAI ships a new agent API for developers",
        "Google expands Gemini agent tasks for teams",
        "A local LLM agent inference tool ships",
    ]):
        sig = ingestion.normalize_item(
            ["hackernews", "rss/techcrunch", "rss/lobsters"][i],
            title=title, url=f"https://ex.invalid/{i}", summary="agent model tooling", rank=1,
        )
        conn = connect()
        try:
            ingestion._insert_signal(conn, sig)
            conn.commit()
        finally:
            conn.close()
    run = opportunity.run_engine()
    assert run["produced"] >= 1, run
    opp = opportunity.list_opportunities()[0]

    claims = {e["url"]: e["title"] for e in opp["evidence"]}

    def fetch(url, **_kw):
        title = claims.get(url, "")
        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}

    monkeypatch.setattr(verification, "FETCHER", fetch)
    assert verification.verify_opportunity(opp["id"], trigger="test")["verdict"] == \
        verification.VERIFIED

    job = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)["job"]
    assert job["state"] == sm.INGESTED
    assert service.get_job(job["id"])["payload"]["opportunity_id"] == opp["id"]
    return job


def make_decidable_job(monkeypatch, *, runs=40, successes=38, revenue=1200.0, cost=180.0):
    """A job that can legally reach KEPT/KILLED.

    The real loop only decides on evidence, so this starts from a job whose
    opportunity is VERIFIED, advances it with the real components, and records one
    measurement. The verdict is computed by the published rule from the numbers.
    """
    job = make_verified_job(monkeypatch)
    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
    measurement.record_measurement(
        bot["id"], runs=runs, successes=successes, revenue_usd=revenue, cost_usd=cost,
        notes="pytest fixture measurement", advance_job=False,
    )
    return service.get_job(job["id"])


# ---------------------------------------------------------------- 1. legal

def test_legal_transition_succeeds_full_loop(monkeypatch):
    job = make_decidable_job(monkeypatch)
    assert job["state"] == sm.RUNNING

    # RUNNING -> MEASURED is the measurement stub's dry run (no verdict yet)
    result = service.advance(job["id"], registry=REGISTRY)
    assert result["transition"]["to"] == sm.MEASURED

    # MEASURED -> KEPT or KILLED, decided by the REAL KeepOrKillLoop on the
    # recorded evidence (40 runs / 38 successes / $1200 revenue / $180 cost).
    result = service.advance(job["id"], registry=REGISTRY)
    assert result["component"] == "KeepOrKillLoop"
    assert result["job"]["state"] == sm.KEPT
    assert sm.is_terminal(result["job"]["state"])


def test_plain_job_cannot_be_built_into_a_bot():
    """A job with no opportunity has nothing VERIFIED to build from -> 409."""
    job = make_job()
    service.advance(job["id"], registry=REGISTRY)  # -> VERIFIED
    with pytest.raises(BotBuildBlocked) as exc:
        service.advance(job["id"], registry=REGISTRY)  # -> BOT_BUILT
    assert exc.value.status == 409
    assert service.get_job(job["id"])["state"] == sm.VERIFIED


def test_every_legal_edge_in_table_is_accepted():
    for from_state, targets in sm.TRANSITIONS.items():
        for to_state in targets:
            sm.assert_transition(from_state, to_state)  # must not raise


def test_reject_from_any_active_state():
    for _ in range(5):
        job = make_job()
        for _ in range(sm.ACTIVE_STATES.index(job["state"])):
            service.advance(job["id"], registry=REGISTRY)
        res = service.reject(job["id"], reason="not worth it")
        assert res["job"]["state"] == sm.REJECTED


# -------------------------------------------------------------- 2. illegal

def test_illegal_transition_ingested_to_running_rejected():
    job = make_job()
    with pytest.raises(IllegalTransition) as exc:
        sm.assert_transition(sm.INGESTED, sm.RUNNING)
    assert "illegal transition INGESTED -> RUNNING" in str(exc.value)
    assert sm.VERIFIED in exc.value.allowed
    # the job itself must be untouched
    assert service.get_job(job["id"])["state"] == sm.INGESTED


def test_illegal_transition_skipping_states_rejected():
    for bad in [(sm.INGESTED, sm.BOT_BUILT), (sm.VERIFIED, sm.RUNNING), (sm.RUNNING, sm.KEPT)]:
        with pytest.raises(IllegalTransition):
            sm.assert_transition(*bad)


def test_terminal_states_have_no_outgoing_edges():
    for terminal in sm.TERMINAL_STATES:
        assert sm.allowed_from(terminal) == []
        for target in sm.ALL_STATES:
            with pytest.raises(IllegalTransition):
                sm.assert_transition(terminal, target)


def test_advance_on_terminal_job_raises():
    job = make_job()
    service.reject(job["id"], reason="done")
    with pytest.raises(IllegalTransition) as exc:
        service.advance(job["id"], registry=REGISTRY)
    assert "terminal" in str(exc.value)


def test_unknown_state_rejected():
    with pytest.raises(IllegalTransition):
        sm.assert_transition("NOPE", sm.VERIFIED)
    with pytest.raises(IllegalTransition):
        sm.assert_transition(sm.INGESTED, "NOPE")


def test_component_returning_illegal_target_is_rejected():
    """A badly written component cannot corrupt the state machine."""
    reg = Registry()
    register_default_components(reg)
    reg.unregister("VerificationLayer")
    reg.register(
        Component(
            name="BadVerifier",
            handles_state=sm.INGESTED,
            handler=lambda job: {"to_state": sm.KEPT, "note": "skips ahead"},
        )
    )
    job = service.create_job("bad", "pytest", {}, registry=reg)
    with pytest.raises(IllegalTransition):
        service.advance(job["id"], registry=reg)
    assert service.get_job(job["id"])["state"] == sm.INGESTED


# ------------------------------------------------------------ 3. hash chain

def test_event_log_hash_chain_is_intact(monkeypatch):
    # The factory refuses to move anything that is not VERIFIED, so the job is
    # driven through VERIFIED (with real verification evidence) first.
    job = make_verified_job(monkeypatch)
    for _ in range(3):  # INGESTED -> VERIFIED -> BOT_BUILT -> RUNNING
        service.advance(job["id"], registry=REGISTRY)
    assert service.get_job(job["id"])["state"] == sm.RUNNING

    conn = connect()
    try:
        rows = conn.execute("SELECT * FROM events ORDER BY id ASC").fetchall()
        assert len(rows) >= 4
        assert rows[0]["prev_hash"] == GENESIS
        for prev, cur in zip(rows, rows[1:]):
            assert cur["prev_hash"] == prev["hash"], "chain link broken"
        status = verify_chain(conn)
        assert status["ok"] is True
        assert status["length"] == len(rows)
    finally:
        conn.close()


def test_hash_chain_detects_tampering():
    job = make_job()
    service.advance(job["id"], registry=REGISTRY)

    conn = connect()
    try:
        assert verify_chain(conn)["ok"] is True
        # Tamper with the note of the first event.
        conn.execute("UPDATE events SET note = 'rewritten history' WHERE id = 1")
        conn.commit()
        status = verify_chain(conn)
        assert status["ok"] is False
        assert status["broken_at"] == 1
        assert "hash mismatch" in status["reason"]
    finally:
        conn.close()


def test_hash_chain_detects_deleted_row(monkeypatch):
    # Same prerequisite as above: a real VERIFIED opportunity behind the job, so
    # the VERIFIED -> BOT_BUILT edge is legal and the chain keeps its rows.
    job = make_verified_job(monkeypatch)
    for _ in range(2):  # INGESTED -> VERIFIED -> BOT_BUILT
        service.advance(job["id"], registry=REGISTRY)
    assert service.get_job(job["id"])["state"] == sm.BOT_BUILT
    conn = connect()
    try:
        conn.execute("DELETE FROM events WHERE id = 2")
        conn.commit()
        status = verify_chain(conn)
        assert status["ok"] is False
        assert "prev_hash mismatch" in status["reason"]
    finally:
        conn.close()


def test_every_transition_is_logged_with_actor_and_states():
    job = make_job()
    service.advance(job["id"], registry=REGISTRY)
    events = service.list_events(limit=100, job_id=job["id"])
    kinds = [e["kind"] for e in events]
    assert "job_created" in kinds
    assert "component_invoked" in kinds
    invoked = [e for e in events if e["kind"] == "component_invoked"]
    # INGESTED is handled by the REAL verification layer, not the retired stub.
    assert invoked[0]["actor"] == "VerificationLayer"
    assert invoked[0]["from_state"] == sm.INGESTED
    assert invoked[0]["to_state"] == sm.VERIFIED
    # A job that cites no signals makes no factual claim: the layer says so plainly
    # and does NOT pretend to have verified anything.
    assert "NO CITATIONS TO VERIFY" in invoked[0]["note"]
    assert "real_fetch" in invoked[0]["note"] or "NO factual claim" in invoked[0]["note"]


# --------------------------------------------------------------- 4. routing

def test_registry_routes_each_state_to_expected_component():
    expected = {
        sm.INGESTED: "VerificationLayer",
        sm.VERIFIED: "BotFactory",
        sm.BOT_BUILT: "RunnerStub",
        sm.RUNNING: "MeasurementStub",
        sm.MEASURED: "KeepOrKillLoop",
    }
    for state, name in expected.items():
        assert REGISTRY.get_for_state(state).name == name


def test_registry_has_intake_component():
    """The INGESTED handler is now the REAL ingestion layer, not a stub."""
    intake = REGISTRY.get_intake(sm.INGESTED)
    assert intake is not None and intake.name == "IngestionLayer"
    assert REGISTRY.get("IngestionStub") is None


def test_new_component_can_be_registered_without_touching_router(monkeypatch):
    """Swap the RUNNING stage for a custom component: no router edit needed."""
    job = make_decidable_job(monkeypatch)  # already at RUNNING, with evidence recorded
    assert service.get_job(job["id"])["state"] == sm.RUNNING

    reg = Registry()
    register_default_components(reg)
    reg.unregister("MeasurementStub")

    seen = {}

    def custom_handler(j):
        seen["id"] = j["id"]
        return {"to_state": sm.MEASURED, "note": "custom measurement ran", "data": {"custom": True}}

    reg.register(Component("CustomMeasurer", sm.RUNNING, custom_handler, "test component"))

    result = service.advance(job["id"], registry=reg)
    assert result["component"] == "CustomMeasurer"
    assert result["job"]["state"] == sm.MEASURED
    assert seen["id"] == job["id"]


def test_registry_rejects_duplicate_state_handler():
    reg = Registry()
    register_default_components(reg)
    with pytest.raises(RegistryError):
        reg.register(Component("AnotherVerifier", sm.INGESTED, lambda j: {}))


def test_registry_rejects_unknown_state():
    with pytest.raises(RegistryError):
        Component("Weird", "NOT_A_STATE", lambda j: {})


def test_missing_component_raises_no_component():
    reg = Registry()
    register_default_components(reg)
    reg.unregister("BotFactory")  # nothing handles VERIFIED any more
    job = service.create_job("x", "pytest", {}, registry=reg)
    service.advance(job["id"], registry=reg)  # -> VERIFIED
    with pytest.raises(NoComponent):
        service.advance(job["id"], registry=reg)


# ------------------------------------------------------------ 5. intake/API

def test_create_job_validation():
    with pytest.raises(ValidationError):
        service.create_job("", "pytest", {})
    with pytest.raises(ValidationError):
        service.create_job("t", "", {})
    with pytest.raises(ValidationError):
        service.create_job("t", "s", ["not", "a", "dict"])


def test_list_jobs_filters_by_state():
    a = make_job("a")
    b = make_job("b")
    service.advance(b["id"], registry=REGISTRY)
    ingested = service.list_jobs(state=sm.INGESTED)
    verified = service.list_jobs(state=sm.VERIFIED)
    assert [j["id"] for j in ingested] == [a["id"]]
    assert [j["id"] for j in verified] == [b["id"]]
    with pytest.raises(ValidationError):
        service.list_jobs(state="BOGUS")


def test_get_job_includes_history_and_events():
    job = make_job()
    service.advance(job["id"], registry=REGISTRY)
    detail = service.get_job(job["id"])
    assert detail["history"] and detail["events"]
    assert detail["allowed_transitions"] == sm.allowed_from(detail["state"])
    assert detail["terminal"] is False


def test_counts_by_state():
    make_job("a")
    b = make_job("b")
    service.advance(b["id"], registry=REGISTRY)
    counts = service.counts_by_state()
    assert counts[sm.INGESTED] == 1
    assert counts[sm.VERIFIED] == 1


def test_seed_creates_three_jobs_at_different_states():
    created = service.seed_if_empty(REGISTRY)
    assert created == 3
    jobs = service.list_jobs()
    assert len(jobs) == 3
    assert all(j["is_seed"] for j in jobs)
    # Seed jobs carry no opportunity, so the REAL bot factory refuses to invent a
    # spec for them: they stop at VERIFIED instead of pretending to be BOT_BUILT.
    states = [j["state"] for j in jobs]
    assert states.count(sm.INGESTED) == 1
    assert states.count(sm.VERIFIED) == 2
    assert sm.BOT_BUILT not in states
    # idempotent
    assert service.seed_if_empty(REGISTRY) == 0


# --------------------------------------------------------------- 6. HTTP API

@pytest.fixture
def client():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        yield c


def test_api_health(client):
    r = client.get("/health")
    assert r.status_code == 200
    body = r.get_json()
    assert body["status"] == "ok"
    assert body["event_chain_ok"] is True


def test_api_create_list_advance_detail(client):
    r = client.post("/jobs", json={"title": "api job", "source": "pytest", "payload": {"a": 1}})
    assert r.status_code == 201
    job = r.get_json()
    assert job["state"] == sm.INGESTED

    r = client.get("/jobs?state=INGESTED")
    assert r.status_code == 200
    assert any(j["id"] == job["id"] for j in r.get_json()["jobs"])

    r = client.post(f"/jobs/{job['id']}/advance")
    assert r.status_code == 200
    assert r.get_json()["job"]["state"] == sm.VERIFIED

    r = client.get(f"/jobs/{job['id']}")
    detail = r.get_json()
    assert detail["history"] and detail["events"]

    r = client.get("/events")
    assert r.status_code == 200
    assert r.get_json()["chain"]["ok"] is True


def test_api_illegal_advance_returns_409(client):
    r = client.post("/jobs", json={"title": "t", "source": "s"})
    job = r.get_json()
    client.post(f"/jobs/{job['id']}/reject", json={"reason": "nope"})
    r = client.post(f"/jobs/{job['id']}/advance")
    assert r.status_code == 409
    body = r.get_json()
    assert body["error"] == "illegal_transition"
    assert "terminal" in body["message"]


def test_api_unknown_job_404(client):
    assert client.get("/jobs/does-not-exist").status_code == 404
    assert client.post("/jobs/does-not-exist/advance").status_code == 404


def test_api_bad_payload_400(client):
    r = client.post("/jobs", json={"title": "", "source": "s"})
    assert r.status_code == 400
    assert r.get_json()["error"] == "bad_request"


def test_dashboard_renders(client):
    client.post("/jobs", json={"title": "dash job", "source": "pytest"})
    r = client.get("/")
    assert r.status_code == 200
    html = r.get_data(as_text=True)
    assert "JARVIS Orchestrator" in html
    assert "BOT_BUILT" in html
    assert "dash job" in html
    assert "advance" in html
    assert "Cache-Control" in r.headers


def test_job_detail_page_renders(client):
    job = client.post("/jobs", json={"title": "detail job", "source": "pytest"}).get_json()
    r = client.get(f"/ui/jobs/{job['id']}")
    assert r.status_code == 200
    assert "detail job" in r.get_data(as_text=True)
