"""Tests for the VERIFICATION LAYER — the immune-system gate.

Covers the required areas:
  (a) the three verdict rules: VERIFIED, UNVERIFIED, CONTRADICTED
  (b) the 409 gate at BOTH enforcement points (component + state-machine boundary)
  (c) determinism: same fetched content -> same verdict
  (d) the hash-chained audit log survives verification runs
  (e) honesty: unreachable/blocked sources are inconclusive, never a pass

NO test touches the network. Every fetch goes through a mocked ``FETCHER``.
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest

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

from orchestrator import ingestion  # 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 VerificationBlocked  # noqa: E402
from orchestrator.registry import REGISTRY  # noqa: E402


# --------------------------------------------------------------------------
# fixtures
# --------------------------------------------------------------------------

@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 page(title: str, filler: int = 60) -> bytes:
    """A readable HTML page whose visible text contains ``title``."""
    return (
        "<html><head><title>" + title + "</title></head><body><h1>" + title +
        "</h1><p>" + ("context words here " * filler) + "</p></body></html>"
    ).encode()


def ok(url: str, title: str) -> dict:
    return {
        "ok": True, "http_status": 200, "body": page(title),
        "content_type": "text/html; charset=utf-8", "error": None,
        "error_kind": None, "final_url": url, "duration_ms": 3,
    }


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


def store_signal(source, title, url, summary=""):
    sig = ingestion.normalize_item(source, title=title, url=url, summary=summary, rank=1)
    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):
    """Mocked fetcher: url -> response dict (or callable)."""
    def fetch(url, **_kw):
        value = mapping.get(url)
        if callable(value):
            return value(url)
        if value is None:
            return fail(url, error="network error: no route to host")
        return value
    return fetch


# --------------------------------------------------------------------------
# (a) the three verdict rules
# --------------------------------------------------------------------------

def test_verdict_verified_when_two_citations_reconfirmed(monkeypatch):
    opp = make_opportunity(3)
    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
    assert run["counts"]["confirmed"] >= 2
    assert run["counts"]["contradicted"] == 0
    assert run["rule_version"] == verification.RULE_VERSION
    # every citation carries the full evidence record
    for c in run["citations"]:
        assert c["reachable"] is True
        assert c["content_present"] is True
        assert c["supports_claim"] is True
        assert c["http_status"] == 200
        assert c["fetched_at"]
        assert c["saw"]
    # the verdict is stored on the opportunity
    stored = opportunity.get_opportunity(opp["id"])
    assert stored["verdict"] == verification.VERIFIED
    assert stored["verdict_rule_version"] == verification.RULE_VERSION
    assert stored["verification_run_id"] == run["id"]


def test_verdict_unverified_when_only_one_citation_confirmed(monkeypatch):
    opp = make_opportunity(3)
    ev = opp["evidence"]
    mapping = {ev[0]["url"]: ok(ev[0]["url"], ev[0]["title"])}
    for e in ev[1:]:
        mapping[e["url"]] = fail(e["url"], error="network error: timed out")
    monkeypatch.setattr(verification, "FETCHER", fetcher_from(mapping))

    run = verification.verify_opportunity(opp["id"], trigger="test")

    assert run["verdict"] == verification.UNVERIFIED
    assert run["counts"]["confirmed"] == 1
    assert run["counts"]["inconclusive"] == len(ev) - 1
    assert run["blocking_signal_ids"]
    assert opportunity.get_opportunity(opp["id"])["verdict"] == verification.UNVERIFIED


def test_verdict_unverified_when_everything_unreachable(monkeypatch):
    """The honest sandbox case: nothing fetchable -> UNVERIFIED, never a pass."""
    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
    assert run["counts"]["confirmed"] == 0
    assert run["counts"]["inconclusive"] == len(opp["evidence"])
    for c in run["citations"]:
        assert c["reachable"] is False
        assert c["supports_claim"] is False
        assert c["outcome"] == verification.INCONCLUSIVE
        assert "INCONCLUSIVE" in c["saw"]


def test_verdict_contradicted_when_content_is_gone(monkeypatch):
    opp = make_opportunity(3)
    ev = opp["evidence"]
    mapping = {e["url"]: ok(e["url"], e["title"]) for e in ev}
    mapping[ev[0]["url"]] = fail(ev[0]["url"], status=404, error="HTTP 404 Not Found",
                                 kind="http")
    monkeypatch.setattr(verification, "FETCHER", fetcher_from(mapping))

    run = verification.verify_opportunity(opp["id"], trigger="test")

    assert run["verdict"] == verification.CONTRADICTED
    assert run["counts"]["contradicted"] == 1
    gone = [c for c in run["citations"] if c["outcome"] == verification.CONTRADICTED_OUTCOME]
    assert gone and gone[0]["http_status"] == 404
    assert gone[0]["content_present"] is False


def test_verdict_contradicted_when_source_says_something_different(monkeypatch):
    """A 2xx page with plenty of text that contains none of the claim tokens."""
    opp = make_opportunity(3)
    ev = opp["evidence"]
    mapping = {e["url"]: ok(e["url"], e["title"]) for e in ev}
    mapping[ev[0]["url"]] = ok(ev[0]["url"], "Completely unrelated weather report")
    monkeypatch.setattr(verification, "FETCHER", fetcher_from(mapping))

    run = verification.verify_opportunity(opp["id"], trigger="test")

    assert run["verdict"] == verification.CONTRADICTED
    changed = [c for c in run["citations"] if c["outcome"] == verification.CONTRADICTED_OUTCOME]
    assert changed and changed[0]["reason"] == "content_changed"
    assert changed[0]["claim_coverage"] == 0.0


def test_blocked_source_is_inconclusive_not_a_pass_and_not_a_fail(monkeypatch):
    """Reddit-style 403 from a sandbox IP: honest 'unreachable', never green."""
    opp = make_opportunity(3)
    ev = opp["evidence"]
    mapping = {e["url"]: ok(e["url"], e["title"]) for e in ev}
    mapping[ev[0]["url"]] = fail(ev[0]["url"], status=403,
                                 error="HTTP Error 403: Forbidden", kind="http")
    monkeypatch.setattr(verification, "FETCHER", fetcher_from(mapping))

    run = verification.verify_opportunity(opp["id"], trigger="test")

    blocked = [c for c in run["citations"] if c["http_status"] == 403][0]
    assert blocked["outcome"] == verification.INCONCLUSIVE
    assert blocked["reachable"] is False
    assert blocked["supports_claim"] is False
    assert blocked["reason"] == "source_blocked"
    assert "403" in blocked["saw"]
    # 2 confirmed + 1 blocked is still VERIFIED (a block is not a contradiction)
    assert run["verdict"] == verification.VERIFIED


def test_contradiction_outranks_confirmations(monkeypatch):
    opp = make_opportunity(3)
    ev = opp["evidence"]
    mapping = {e["url"]: ok(e["url"], e["title"]) for e in ev}
    mapping[ev[0]["url"]] = fail(ev[0]["url"], status=410, error="HTTP 410 Gone", kind="http")
    monkeypatch.setattr(verification, "FETCHER", fetcher_from(mapping))

    run = verification.verify_opportunity(opp["id"], trigger="test")
    assert run["counts"]["confirmed"] >= 2
    assert run["verdict"] == verification.CONTRADICTED


# --------------------------------------------------------------------------
# (b) the 409 gate — BOTH enforcement points
# --------------------------------------------------------------------------

def test_gate_enforced_by_the_component(monkeypatch):
    """Enforcement point 1: the verifier itself refuses to return VERIFIED."""
    opp = make_opportunity(3)
    monkeypatch.setattr(verification, "FETCHER",
                        fetcher_from({e["url"]: fail(e["url"]) for e in opp["evidence"]}))
    job = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)["job"]

    layer = REGISTRY.get_for_state(sm.INGESTED)
    assert layer.name == verification.COMPONENT_NAME
    with pytest.raises(VerificationBlocked) as exc:
        layer.handler(job)

    assert exc.value.status == 409
    assert exc.value.verdict == verification.UNVERIFIED
    assert "UNVERIFIED" in str(exc.value)
    assert exc.value.details["blocking_signal_ids"]
    # the job did not move
    assert service.get_job(job["id"])["state"] == sm.INGESTED


def test_gate_enforced_at_the_state_machine_boundary(monkeypatch):
    """Enforcement point 2: a buggy component that lies cannot bypass the gate."""
    opp = make_opportunity(3)
    monkeypatch.setattr(verification, "FETCHER",
                        fetcher_from({e["url"]: fail(e["url"]) for e in opp["evidence"]}))
    job = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)["job"]
    # record an honest UNVERIFIED verdict on the opportunity
    verification.verify_opportunity(opp["id"], trigger="test")

    reg = REGISTRY.__class__()
    register_default_components(reg)
    reg.unregister(verification.COMPONENT_NAME)
    reg.register(
        verification.Component(
            name="LyingVerifier",
            handles_state=sm.INGESTED,
            handler=lambda j: {"to_state": sm.VERIFIED, "note": "trust me, it's fine"},
        )
    )

    with pytest.raises(VerificationBlocked) as exc:
        service.advance(job["id"], registry=reg)

    assert exc.value.status == 409
    assert exc.value.verdict == verification.UNVERIFIED
    assert "verification gate refused" in str(exc.value)
    assert service.get_job(job["id"])["state"] == sm.INGESTED


def test_gate_blocks_verified_to_bot_built_without_verdict(monkeypatch):
    """The gate also covers VERIFIED -> BOT_BUILT, not just the first edge."""
    opp = make_opportunity(3)
    monkeypatch.setattr(verification, "FETCHER",
                        fetcher_from({e["url"]: fail(e["url"]) for e in opp["evidence"]}))
    job = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)["job"]
    verification.verify_opportunity(opp["id"], trigger="test")

    # 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()

    # Both gates are 409. The bot-factory gate runs first on this edge and names
    # the verdict; the verification gate would refuse it too.
    from orchestrator.errors import BotBuildBlocked
    with pytest.raises((VerificationBlocked, BotBuildBlocked)) as exc:
        service.advance(job["id"], registry=REGISTRY)
    assert exc.value.status == 409
    assert exc.value.verdict in (verification.UNVERIFIED, verification.CONTRADICTED)
    assert service.get_job(job["id"])["state"] == sm.VERIFIED


def test_gate_allows_advance_when_verdict_is_verified(monkeypatch):
    opp = make_opportunity(3)
    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()}))
    job = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)["job"]

    step = service.advance(job["id"], registry=REGISTRY)
    assert step["transition"]["to"] == sm.VERIFIED
    assert step["job"]["payload"]["_verification"]["verdict"] == verification.VERIFIED


def test_gate_returns_409_over_http(monkeypatch):
    """The API surface must answer 409 with the verdict and blocking citations."""
    from app import create_app

    opp = make_opportunity(3)
    monkeypatch.setattr(verification, "FETCHER",
                        fetcher_from({e["url"]: fail(e["url"]) for e in opp["evidence"]}))
    job = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)["job"]

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as client:
        r = client.post(f"/jobs/{job['id']}/advance")
        assert r.status_code == 409
        body = r.get_json()
        assert body["error"] == "verification_failed"
        assert body["verdict"] == verification.UNVERIFIED
        assert body["details"]["blocking_signal_ids"]
        assert "UNVERIFIED" in body["message"]


# --------------------------------------------------------------------------
# (c) determinism
# --------------------------------------------------------------------------

def test_same_content_yields_same_verdict(monkeypatch):
    opp = make_opportunity(3)
    claims = {e["url"]: e["title"] for e in opp["evidence"]}
    mapping = {u: ok(u, t) for u, t in claims.items()}
    monkeypatch.setattr(verification, "FETCHER", fetcher_from(mapping))

    first = verification.verify_opportunity(opp["id"], trigger="test")
    second = verification.verify_opportunity(opp["id"], trigger="test")

    assert first["verdict"] == second["verdict"] == verification.VERIFIED
    assert first["counts"] == second["counts"]
    assert first["rule_version"] == second["rule_version"]
    # per-citation decisions are identical (timestamps aside)
    strip = lambda cs: [
        {k: v for k, v in c.items() if k not in ("fetched_at", "duration_ms")} for c in cs
    ]
    assert strip(first["citations"]) == strip(second["citations"])


def test_decide_verdict_is_a_pure_function():
    """No clock, no randomness: the same records always decide the same way."""
    def rec(sid, outcome):
        return {"signal_id": sid, "outcome": outcome, "source": "s", "url": "u"}

    cases = [
        ([rec("a", "confirmed"), rec("b", "confirmed")], verification.VERIFIED),
        ([rec("a", "confirmed")], verification.UNVERIFIED),
        ([rec("a", "inconclusive"), rec("b", "inconclusive")], verification.UNVERIFIED),
        ([rec("a", "confirmed"), rec("b", "contradicted")], verification.CONTRADICTED),
        ([], verification.UNVERIFIED),
    ]
    for citations, expected in cases:
        for _ in range(5):
            assert verification.decide_verdict(citations)["verdict"] == expected


def test_evaluate_citation_is_deterministic_for_the_same_bytes():
    cite = {"signal_id": "s1", "source": "hackernews", "url": "https://ex.invalid/a"}
    claim = "OpenAI ships a new agent API"
    fetched = ok("https://ex.invalid/a", claim)
    a = verification.evaluate_citation(cite, claim, fetched, fetched_at="T")
    b = verification.evaluate_citation(cite, claim, fetched, fetched_at="T")
    assert a == b
    assert a["outcome"] == verification.CONFIRMED


# --------------------------------------------------------------------------
# (d) the hash chain survives verification runs
# --------------------------------------------------------------------------

def test_audit_hash_chain_survives_verification_runs(monkeypatch):
    opp = make_opportunity(3)
    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()}))

    before = service.chain_status()
    assert before["ok"] is True

    run = verification.verify_opportunity(opp["id"], trigger="test")
    assert run["event_id"] is not None

    after = service.chain_status()
    assert after["ok"] is True
    assert after["length"] > before["length"]

    # the audit event carries run id, opportunity id, verdict, rule version, citations
    events = service.list_events(limit=50, kind="verification_run")
    assert events, "verification run must append an audit event"
    data = events[0]["data"]
    assert data["run_id"] == run["id"]
    assert data["opportunity_id"] == opp["id"]
    assert data["verdict"] == verification.VERIFIED
    assert data["rule_version"] == verification.RULE_VERSION
    assert data["citations"] and data["citations"][0]["signal_id"]
    assert data["real_fetch"] is True


def test_chain_survives_a_verify_all_sweep(monkeypatch):
    make_opportunity(3)
    monkeypatch.setattr(verification, "FETCHER",
                        fetcher_from({}) if False else (lambda url, **kw: fail(url)))

    sweep = verification.verify_all(trigger="test-all")
    assert sweep["count"] >= 1
    assert sweep["tally"][verification.UNVERIFIED] == sweep["count"]
    assert service.chain_status()["ok"] is True


def test_events_verify_endpoint_still_passes(monkeypatch):
    from app import create_app

    opp = make_opportunity(3)
    monkeypatch.setattr(verification, "FETCHER", lambda url, **kw: fail(url))
    verification.verify_opportunity(opp["id"], trigger="test")

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        r = c.get("/events/verify")
        assert r.status_code == 200
        assert r.get_json()["ok"] is True


# --------------------------------------------------------------------------
# (e) honesty + registry wiring + UI
# --------------------------------------------------------------------------

def test_verifier_is_registered_through_the_registry():
    comp = REGISTRY.get_for_state(sm.INGESTED)
    assert comp.name == verification.COMPONENT_NAME
    assert comp.handles_state == sm.INGESTED
    assert comp.produces_state == sm.VERIFIED
    assert REGISTRY.get("VerificationStub") is None
    # it is a state component, not a tool
    assert comp.kind == "state"


def test_no_verdict_is_invented_before_a_run():
    opp = make_opportunity(3)
    stored = opportunity.get_opportunity(opp["id"])
    assert stored["verdict"] is None
    assert stored["verification"] is None
    counts = verification.verdict_counts()
    assert counts["with_verdict"] == 0
    assert counts["never_verified"] == counts["opportunities"]


def test_verification_ui_renders_honest_empty_state():
    from app import create_app

    make_opportunity(3)
    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        r = c.get("/ui/verification")
        assert r.status_code == 200
        html = r.get_data(as_text=True)
        assert "Verification" in html
        assert "Nothing has been verified yet" in html
        assert "NO VERDICT" in html
        assert "Verify all" in html
        assert "Verify now" in html
        assert verification.RULE_VERSION in html
        # no invented green badge
        assert 'badge VERIFIED' not in html


def test_verification_ui_shows_real_evidence_after_a_run(monkeypatch):
    from app import create_app

    opp = make_opportunity(3)
    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")

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        html = c.get("/ui/verification").get_data(as_text=True)
        assert "badge VERIFIED" in html
        assert "supports_claim yes" in html
        assert "what it saw" in html
        assert "Nothing has been verified yet" not in html


def test_verify_now_endpoint_runs_and_returns_live_result(monkeypatch):
    from app import create_app

    opp = make_opportunity(3)
    monkeypatch.setattr(verification, "FETCHER", lambda url, **kw: fail(url, status=403,
                        error="HTTP Error 403: Forbidden", kind="http"))
    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        r = c.post(f"/opportunities/{opp['id']}/verify")
        assert r.status_code == 200
        body = r.get_json()
        assert body["verdict"] == verification.UNVERIFIED
        assert body["counts"]["inconclusive"] == len(opp["evidence"])
        assert all(c["http_status"] == 403 for c in body["citations"])
        assert all(c["supports_claim"] is False for c in body["citations"])


def test_verify_all_endpoint_returns_a_tally(monkeypatch):
    from app import create_app

    make_opportunity(3)
    monkeypatch.setattr(verification, "FETCHER", lambda url, **kw: fail(url))
    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        r = c.post("/verification/run-all")
        assert r.status_code == 200
        body = r.get_json()
        assert body["count"] >= 1
        assert body["rule_version"] == verification.RULE_VERSION
        assert sum(body["tally"].values()) == body["count"]


def test_rules_document_is_served():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as c:
        body = c.get("/verification/rules").get_json()
        assert body["component"] == verification.COMPONENT_NAME
        assert body["rules"]["version"] == verification.RULE_VERSION
        assert set(body["verdicts"]) == {"VERIFIED", "UNVERIFIED", "CONTRADICTED"}
        assert body["rules"]["deterministic"] is True
