"""Tests for the REAL opportunity engine.

Covers the required areas:
  (a) an uncited opportunity is REJECTED and never stored
  (b) scoring rules are deterministic (same input -> same scores)
  (c) clustering groups related signals
  (d) the engine handles an empty signal store honestly
  (e) the engine is registered as a tool component (not a pipeline state)
  (f) an opportunity can be turned into a job that enters at INGESTED

No test touches the network: signals are inserted straight into SQLite.
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-opp-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.errors import VerificationBlocked  # noqa: E402
from orchestrator.components import register_default_components  # noqa: E402
from orchestrator.db import connect, init_db  # noqa: E402
from orchestrator.registry import REGISTRY  # noqa: E402


@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="", score=None, rank=1):
    """Insert a real signal row through the ingestion persistence path."""
    sig = ingestion.normalize_item(
        source, title=title, url=url, summary=summary, score=score, rank=rank
    )
    conn = connect()
    try:
        ingestion._insert_signal(conn, sig)
        conn.commit()
    finally:
        conn.close()
    return sig


def fake_fetcher_for(opp):
    """Mocked fetcher: every cited URL returns a page containing its own claim."""
    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}

    return fetch


def store_ai_cluster():
    """Three signals that all belong to the ai-tooling topic, from 2 sources."""
    a = store_signal("hackernews", "OpenAI ships a new agent API", "https://ex.invalid/a",
                     "the model can call tools", score=300, rank=1)
    b = store_signal("rss/techcrunch", "Google expands Gemini Tasks for agents",
                     "https://ex.invalid/b", "AI assistant rollout", score=120, rank=2)
    c = store_signal("rss/lobsters", "A local LLM inference tool", "https://ex.invalid/c",
                     "open source model runner", score=80, rank=3)
    return [a, b, c]


# ------------------------------------------------- (d) empty store honesty

def test_empty_signal_store_produces_nothing_and_says_so():
    assert ingestion.signal_counts()["total"] == 0
    run = opportunity.run_engine()
    assert run["signals_read"] == 0
    assert run["produced"] == 0
    assert run["created"] == 0
    assert run["rejected"] == 0
    assert "0 real signals" in run["message"]
    assert "invented none" in run["message"]
    # nothing was stored anywhere
    assert opportunity.list_opportunities() == []
    assert opportunity.counts()["total"] == 0


def test_single_signal_cluster_is_not_an_opportunity():
    """One headline is not a cluster: the engine refuses to score it."""
    store_signal("hackernews", "OpenAI ships a new agent API", "https://ex.invalid/only")
    run = opportunity.run_engine()
    assert run["signals_read"] == 1
    assert run["produced"] == 0
    assert "no topic cluster reached the minimum" in run["message"]
    assert opportunity.list_opportunities() == []


def test_engine_run_is_audit_logged():
    store_ai_cluster()
    run = opportunity.run_engine()
    assert run["produced"] >= 1
    events = service.list_events(limit=50, kind="opportunity_run")
    assert events, "the engine run must be appended to the hash-chained audit log"
    assert events[0]["data"]["signals_read"] == 3
    assert service.chain_status()["ok"] is True


# ------------------------------------------------------- (c) clustering

def test_clustering_groups_related_signals():
    a, b, c = store_ai_cluster()
    store_signal("rss/bbc-business", "We can't afford to hire under-25s, say firms",
                 "https://ex.invalid/jobs", "hiring and wages", score=10, rank=4)

    signals = ingestion.list_signals(limit=100)
    clusters = opportunity.cluster_signals(signals)
    by_key = {cl["key"]: cl for cl in clusters}

    assert "ai-tooling" in by_key
    ai = by_key["ai-tooling"]
    assert ai["size"] == 3
    assert sorted(ai["signal_ids"]) == sorted([a["id"], b["id"], c["id"]])
    assert ai["sources"] == ["hackernews", "rss/lobsters", "rss/techcrunch"]

    assert "jobs-labour" in by_key
    assert by_key["jobs-labour"]["size"] == 1

    # deterministic ordering: biggest cluster first
    assert clusters[0]["key"] == "ai-tooling"


def test_clustering_is_stable_across_input_order():
    store_ai_cluster()
    signals = ingestion.list_signals(limit=100)
    first = opportunity.cluster_signals(signals)
    second = opportunity.cluster_signals(list(reversed(signals)))
    assert [c["key"] for c in first] == [c["key"] for c in second]
    assert [c["signal_ids"] for c in first] == [c["signal_ids"] for c in second]


# ------------------------------------------- (a) THE HARD CITATION RULE

def test_uncited_opportunity_is_rejected_and_never_stored():
    """A candidate with empty evidence must raise and must not reach the DB."""
    store_ai_cluster()
    signals = ingestion.list_signals(limit=100)
    signals_by_id = {s["id"]: s for s in signals}
    cluster = opportunity.cluster_signals(signals)[0]

    # Build a real one, then strip its evidence — exactly what a buggy or
    # dishonest producer would do.
    opp = opportunity.build_opportunity(cluster, signals_by_id)
    assert opp["evidence"], "sanity: a real cluster yields real evidence"
    opp["evidence"] = []

    with pytest.raises(opportunity.UncitedOpportunity) as exc:
        opportunity.validate_opportunity(opp, set(signals_by_id))
    assert "no evidence" in str(exc.value)

    # And it is not in the store.
    assert opportunity.get_opportunity(opp["id"]) is None


def test_evidence_citing_an_unknown_signal_id_is_rejected():
    store_ai_cluster()
    signals = ingestion.list_signals(limit=100)
    signals_by_id = {s["id"]: s for s in signals}
    cluster = opportunity.cluster_signals(signals)[0]
    opp = opportunity.build_opportunity(cluster, signals_by_id)

    opp["evidence"] = [{"signal_id": "deadbeefdeadbeef", "source": "x", "url": "https://x"}]
    with pytest.raises(opportunity.UncitedOpportunity) as exc:
        opportunity.validate_opportunity(opp, set(signals_by_id))
    assert "not in the signals store" in str(exc.value)


def test_evidence_row_without_signal_id_is_rejected():
    with pytest.raises(opportunity.UncitedOpportunity):
        opportunity.validate_opportunity({"evidence": [{"source": "x", "url": "y"}]}, set())


def test_run_engine_rejects_uncitable_cluster_and_logs_the_reason(monkeypatch):
    """Force the gate to fire inside a real run: 0 stored, 1 logged rejection."""
    store_ai_cluster()
    real_build = opportunity.build_opportunity

    def sabotaged(cluster, signals_by_id):
        opp = real_build(cluster, signals_by_id)
        opp["evidence"] = []  # simulate a producer that cannot cite anything
        return opp

    monkeypatch.setattr(opportunity, "build_opportunity", sabotaged)
    run = opportunity.run_engine()

    assert run["produced"] == 0
    assert run["rejected"] == 1
    assert opportunity.list_opportunities() == []
    rejections = opportunity.list_rejections()
    assert len(rejections) == 1
    assert "no evidence" in rejections[0]["reason"]
    # the rejection is in the audit log too
    events = service.list_events(limit=50, kind="opportunity_rejected")
    assert events and "REJECTED" in events[0]["note"]
    assert service.chain_status()["ok"] is True


def test_every_stored_opportunity_has_real_citable_evidence():
    store_ai_cluster()
    store_signal("rss/bbc-business", "Nvidia chip revenue hits record on AI demand",
                 "https://ex.invalid/nv", "gpu datacenter sales", score=50, rank=5)
    store_signal("rss/techcrunch", "Nvidia promises revenue will keep soaring",
                 "https://ex.invalid/nv2", "chip demand", score=40, rank=6)
    run = opportunity.run_engine()
    assert run["produced"] >= 2

    known = {s["id"] for s in ingestion.list_signals(limit=500)}
    for opp in opportunity.list_opportunities():
        assert opp["evidence"], f"{opp['id']} stored without evidence"
        for row in opp["evidence"]:
            assert row["signal_id"] in known
            assert row["source"]
            assert row["url"]


# ------------------------------------------------- (b) determinism

def test_scoring_is_deterministic():
    store_ai_cluster()
    signals = ingestion.list_signals(limit=100)
    signals_by_id = {s["id"]: s for s in signals}
    cluster = opportunity.cluster_signals(signals)[0]

    first = opportunity.build_opportunity(cluster, signals_by_id)
    second = opportunity.build_opportunity(cluster, signals_by_id)
    assert first == second

    # and a full re-run produces identical scores for the same signals
    run1 = opportunity.run_engine()
    scores1 = {o["id"]: o["composite_score"] for o in opportunity.list_opportunities()}
    run2 = opportunity.run_engine()
    scores2 = {o["id"]: o["composite_score"] for o in opportunity.list_opportunities()}
    assert scores1 == scores2
    assert run1["produced"] == run2["produced"]
    # idempotent: the second run refreshes, it does not duplicate
    assert run2["created"] == 0
    assert run2["updated"] == run1["produced"]


def test_scores_are_bounded_and_explained():
    store_ai_cluster()
    run = opportunity.run_engine()
    for opp in run["opportunities"]:
        for name in ("signal_strength", "money_potential", "feasibility", "confidence"):
            s = opp["scores"][name]
            assert 0 <= s["value"] <= 100
            assert s["rule"]
            assert s["working"]
        assert 0 <= opp["composite_score"] <= 100
        expected = round(
            0.30 * opp["scores"]["signal_strength"]["value"]
            + 0.30 * opp["scores"]["money_potential"]["value"]
            + 0.20 * opp["scores"]["feasibility"]["value"]
            + 0.20 * opp["scores"]["confidence"]["value"]
        )
        assert opp["composite_score"] == expected


def test_more_sources_raise_confidence():
    a = store_signal("hackernews", "AI agent tool one", "https://ex.invalid/1", score=10)
    b = store_signal("rss/lobsters", "AI agent tool two", "https://ex.invalid/2", score=10)
    signals = ingestion.list_signals(limit=10)
    by_id = {s["id"]: s for s in signals}
    two_source = opportunity.build_opportunity(opportunity.cluster_signals(signals)[0], by_id)

    store_signal("rss/techcrunch", "AI agent tool three", "https://ex.invalid/3", score=10)
    signals = ingestion.list_signals(limit=10)
    by_id = {s["id"]: s for s in signals}
    three_source = opportunity.build_opportunity(opportunity.cluster_signals(signals)[0], by_id)

    assert (
        three_source["scores"]["confidence"]["value"]
        > two_source["scores"]["confidence"]["value"]
    )


# ------------------------------------- (e) registry + (f) loop wiring

def test_engine_is_registered_as_a_tool_not_a_pipeline_state():
    comp = REGISTRY.get_tool("OpportunityEngine")
    assert comp.kind == "tool"
    assert comp.handles_state is None
    # it must not have stolen a pipeline state
    assert REGISTRY.get_for_state(sm.INGESTED).name == "VerificationLayer"
    assert REGISTRY.get_for_state(sm.MEASURED).name == "KeepOrKillLoop"
    # the transition table is untouched
    assert sm.TRANSITIONS[sm.INGESTED] == [sm.VERIFIED, sm.FAILED, sm.REJECTED]


def test_opportunity_becomes_a_job_that_enters_at_ingested(monkeypatch):
    store_ai_cluster()
    run = opportunity.run_engine()
    opp = run["opportunities"][0]

    result = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)
    job = result["job"]
    assert result["created"] is True
    assert job["state"] == sm.INGESTED
    assert job["payload"]["opportunity_id"] == opp["id"]
    assert job["payload"]["evidence"]

    # The INGESTED -> VERIFIED edge is now gated by the REAL verification layer.
    # These signals point at ex.invalid, which cannot be fetched, so the honest
    # verdict is UNVERIFIED and the gate refuses the advance with 409.
    with pytest.raises(VerificationBlocked) as blocked:
        service.advance(job["id"], registry=REGISTRY)
    assert blocked.value.status == 409
    assert blocked.value.verdict in (verification.UNVERIFIED, verification.CONTRADICTED)
    assert service.get_job(job["id"])["state"] == sm.INGESTED

    # With every network call mocked so each cited page really does contain its
    # claim, the verdict becomes VERIFIED and the same edge is allowed. The
    # component re-fetches on advance, so the module-level FETCHER is mocked.
    monkeypatch.setattr(verification, "FETCHER", fake_fetcher_for(opp))
    expected = [sm.VERIFIED, sm.BOT_BUILT, sm.RUNNING, sm.MEASURED]
    for want in expected:
        step = service.advance(job["id"], registry=REGISTRY)
        assert step["transition"]["to"] == want

    # The keep-or-kill loop decides on evidence only: with no measurement it
    # refuses (409) and the job stays at MEASURED rather than being guessed at.
    from orchestrator.errors import MeasurementBlocked
    with pytest.raises(MeasurementBlocked):
        service.advance(job["id"], registry=REGISTRY)
    assert service.get_job(job["id"])["state"] == sm.MEASURED

    # Record one measurement, then the same edge produces a real verdict.
    from orchestrator import bot_factory, measurement
    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,
        notes="pytest", advance_job=False,
    )
    final = service.advance(job["id"], registry=REGISTRY)
    assert final["job"]["state"] == sm.KEPT

    # queuing twice does not create a second job
    again = opportunity.opportunity_to_job(opp["id"], registry=REGISTRY)
    assert again["created"] is False
    assert again["job"]["id"] == job["id"]
    assert opportunity.get_opportunity(opp["id"])["status"] == opportunity.STATUS_QUEUED


def test_rules_document_is_exposed_and_complete():
    doc = opportunity.rules_document()
    assert doc["rules"]["deterministic"] is True
    assert doc["rules"]["model_calls"] == 0
    for name in ("signal_strength", "money_potential", "feasibility", "confidence"):
        assert doc["rules"]["scores"][name]["rule"]
    assert doc["rules"]["composite_score"]["weights"] == opportunity.COMPOSITE_WEIGHTS
    assert doc["rules"]["citation_rule"]
    assert len(doc["topics"]) == len(opportunity.TOPICS)


# ------------------------------------------------------------- API/UI

@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_run_and_list_opportunities(client):
    store_ai_cluster()
    r = client.post("/opportunities/run")
    assert r.status_code == 200
    body = r.get_json()
    assert body["signals_read"] == 3
    assert body["produced"] >= 1
    assert body["rejected"] == 0

    r = client.get("/api/opportunities")
    assert r.status_code == 200
    rows = r.get_json()["opportunities"]
    assert rows and rows[0]["evidence"]
    assert rows[0]["composite_score"] >= rows[-1]["composite_score"]


def test_api_rules_route(client):
    r = client.get("/opportunities/rules")
    assert r.status_code == 200
    assert r.get_json()["rules"]["citation_rule"]


def test_ui_opportunities_page_renders(client):
    store_ai_cluster()
    client.post("/ui/opportunities/run")
    r = client.get("/ui/opportunities")
    assert r.status_code == 200
    html = r.get_data(as_text=True)
    assert "Opportunity engine" in html
    assert "what they need" in html
    assert "rejected for lack of citation" in html
    assert "signal_strength" in html
    assert "https://ex.invalid/a" in html


def test_ui_opportunities_empty_state_is_honest(client):
    r = client.get("/ui/opportunities")
    html = r.get_data(as_text=True)
    assert r.status_code == 200
    assert "No opportunities yet" in html
    assert "will not" in html and "invent" in html
