"""Tests for the Tavily adapter — real web search, gated by the vault.

    orchestrator/tavily_source.py   authenticated POST /search, one probe

The required cases:

  (a) no key             -> DEGRADED, the literal MISSING_KEY_REASON, ZERO requests,
                            zero rows, zero claims; the same through live_data
  (b) response parsing   -> a real-shaped body becomes the rows/URLs/count it
                            really carries; an error-shaped 200 is refused, not
                            presented as results
  (c) HTTP 429           -> retried with exponential backoff (``_sleep`` patched),
                            then the real answer; an exhausted 429 keeps the
                            literal 429 and zero rows
  (d) the key            -> comes from the vault (``tavily``) / environment, rides
                            only the Authorization header, and never appears in
                            any result string

Plus the registry wiring: ``tavily`` is in ``live_data.SOURCES`` (so it derives
into ``live_ingest.BRIDGED_SOURCE_IDS``), the snapshot/API carry its real
``result_count``, and ``POST /api/live-data/test/tavily`` re-probes only it.

No test touches the network: every HTTP call is monkeypatched at the adapter's
own ``_http`` seam, and the vault is a throwaway file, so nothing here can see
or leak the operator's real key.
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest

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

from orchestrator import live_data  # noqa: E402
from orchestrator import live_ingest  # noqa: E402
from orchestrator import memory  # noqa: E402
from orchestrator import secrets_vault  # noqa: E402
from orchestrator import tavily_source  # noqa: E402
from orchestrator.db import connect, init_db  # noqa: E402

#: A sentinel shaped like a real key, so the "never echoed" guard is meaningful.
SENTINEL = "tvly-SENTINEL-do-not-leak-9d2f7b41c8e5a6"

#: A real-shaped search body: what ``POST /search`` actually returns.
SEARCH_BODY = {
    "query": "HVAC contractor demand Rochester NY winter",
    "answer": "",
    "results": [
        {
            "title": "Rochester Heating & AC Installation — Turnbull",
            "url": "https://www.turnbullheating.com/rochester-ny-heating-installation",
            "content": ("Furnace and heat-pump installs across Monroe County. "
                        "Emergency service is 24/7 through the winter."),
            "score": 0.9312,
            "raw_content": None,
        },
        {
            "title": "HVAC jobs in Rochester, NY — Indeed",
            "url": "https://www.indeed.com/q-hvac-l-rochester,-ny-jobs.html",
            "content": "142 HVAC openings within 25 miles of Rochester.",
            "score": 0.8145,
        },
        {
            # A hit with neither a title nor a URL cites nothing: it must be
            # dropped rather than rendered as an empty row.
            "title": "",
            "url": "",
            "content": "orphan",
            "score": 0.1,
        },
    ],
    "response_time": 0.87,
    "request_id": "req-2f9c1a",
}


# ---------------------------------------------------------------------------
# fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(autouse=True)
def fresh_state(monkeypatch, tmp_path):
    """Fresh sqlite files, a throwaway vault, and no credential in the env."""
    for path in (os.environ["JARVIS_DB"], os.environ["JARVIS_MEMORY_DB"]):
        for suffix in ("", "-wal", "-shm"):
            try:
                os.remove(path + suffix)
            except FileNotFoundError:
                pass
        os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)

    # No Tavily credential unless a test puts one there — never the real one.
    for name in ("TAVILY_API_KEY", "TAVILY_KEY"):
        monkeypatch.delenv(name, raising=False)
    monkeypatch.setenv("JARVIS_SECRETS_FILE", str(tmp_path / "vault" / "secrets.json"))

    init_db()
    memory.init_db()
    live_data.reset_for_tests()
    live_ingest.reset_for_tests()
    yield
    live_data.reset_for_tests()
    live_ingest.reset_for_tests()


def _claim_count() -> int:
    conn = memory.connect()
    try:
        return int(conn.execute("SELECT COUNT(*) AS n FROM claims").fetchone()["n"])
    finally:
        conn.close()


def _probe_only(source_id: str) -> dict:
    """Probe ONE adapter and record it — never with a live HTTP call in tests."""
    live_data.seed_if_empty()
    entry = live_data._probe_one(live_data.SOURCE_BY_ID[source_id])
    live_data._record_capture(entry)
    return entry


def _ingest(sources=None) -> dict:
    conn = connect()
    try:
        return live_ingest.ingest_live_signals(conn, sources=sources)
    finally:
        conn.close()


# ===========================================================================
# (a) missing key -> DEGRADED, the literal reason, zero requests, zero claims
# ===========================================================================
def test_missing_key_is_degraded_with_the_literal_reason_and_no_request(monkeypatch):
    """With no credential the adapter sends nothing and says exactly that."""
    assert secrets_vault.get("TAVILY_API_KEY") is None, "the fixture leaves no key behind"

    calls = []

    def _never(*args, **kwargs):  # pragma: no cover - it must not be reached
        calls.append(args)
        raise AssertionError("no request may be sent without a credential")

    monkeypatch.setattr(tavily_source, "_http", _never)

    for result in (tavily_source.search("HVAC demand Rochester"),
                   tavily_source.probe(),
                   tavily_source.health(),
                   tavily_source.snapshot()):
        assert result["status"] == tavily_source.DEGRADED
        assert result["reason"] == tavily_source.MISSING_KEY_REASON
        assert result["http_code"] is None, "there was no HTTP call, so there is no code"
        assert result["result_count"] == 0
        assert result["rows"] == []
        assert result["signals"] == []
        # The citation is the docs page, never a request URL.
        assert result["source_url"] == tavily_source.SOURCE_URL

    assert calls == [], "a missing key must send zero requests"

    # And through the live-data layer: DEGRADED, literal detail, zero rows.
    entry = _probe_only("tavily")
    assert entry["status"] == live_data.DEGRADED
    assert entry["detail"] == tavily_source.MISSING_KEY_REASON
    assert entry["http_code"] is None
    assert entry["rows"] == []

    before = _claim_count()
    summary = _ingest(["tavily"])
    assert summary["tavily"]["status"] == "DEGRADED"
    assert summary["tavily"]["claims_written"] == 0
    assert _claim_count() == before, "a search hit is a pointer, never a claim"


def test_the_key_comes_from_the_vault_alias(monkeypatch):
    """The stored spelling is ``tavily``; the adapter resolves it and uses it."""
    secrets_vault.set("tavily", SENTINEL)
    monkeypatch.delenv("TAVILY_API_KEY", raising=False)

    assert tavily_source._token() == SENTINEL
    assert tavily_source.credential_source() == "file"
    assert secrets_vault.status()["TAVILY_API_KEY"] == secrets_vault.PRESENT

    seen = {}

    def _fake_http(url, *, token, method="POST", body=None, timeout=None):
        seen["url"], seen["token"], seen["method"] = url, token, method
        seen["headers_used"] = tavily_source._headers(token)
        return 401, '{"detail": {"error": "Unauthorized"}}'

    monkeypatch.setattr(tavily_source, "_http", _fake_http)

    result = tavily_source.search("ping")
    assert seen["url"] == tavily_source.ENDPOINT
    assert seen["method"] == "POST"
    assert seen["token"] == SENTINEL
    assert seen["headers_used"]["Authorization"] == f"Bearer {SENTINEL}"
    assert result["status"] == tavily_source.DEGRADED
    assert result["http_code"] == 401, "a 401 is a real answer, not a rate limit"
    # The credential rides one header and never leaks into a result string.
    assert SENTINEL not in json.dumps(result)


def test_an_environment_key_wins_over_the_file(monkeypatch):
    secrets_vault.set("tavily", SENTINEL)
    monkeypatch.setenv("TAVILY_API_KEY", "tvly-from-the-environment-0001")
    assert tavily_source._token() == "tvly-from-the-environment-0001"
    assert tavily_source.credential_source() == "env"


# ===========================================================================
# (b) response parsing
# ===========================================================================
def test_parse_results_extracts_exactly_what_the_body_carries():
    parsed = tavily_source.parse_results(SEARCH_BODY)

    assert parsed["count"] == 2, "the empty title+url hit cites nothing and is dropped"
    assert parsed["query"] == SEARCH_BODY["query"]
    assert parsed["response_time"] == pytest.approx(0.87)
    assert parsed["request_id"] == "req-2f9c1a"
    assert [r["url"] for r in parsed["results"]] == [
        "https://www.turnbullheating.com/rochester-ny-heating-installation",
        "https://www.indeed.com/q-hvac-l-rochester,-ny-jobs.html",
    ]
    assert parsed["results"][0]["title"].startswith("Rochester Heating")
    assert parsed["results"][0]["score"] == pytest.approx(0.9312)
    assert "\n" not in parsed["results"][0]["content"]


@pytest.mark.parametrize("body", [
    ["not", "an", "object"],
    {"no_results_key": []},
    {"results": "not-a-list"},
])
def test_parse_results_refuses_a_body_that_is_not_a_search_response(body):
    with pytest.raises(ValueError):
        tavily_source.parse_results(body)


def test_search_returns_the_real_rows_and_count_on_200(monkeypatch):
    secrets_vault.set("tavily", SENTINEL)
    seen = {}

    def _fake_http(url, *, token, method="POST", body=None, timeout=None):
        seen["body"] = json.loads(body.decode("utf-8"))
        return 200, json.dumps(SEARCH_BODY)

    monkeypatch.setattr(tavily_source, "_http", _fake_http)

    result = tavily_source.search("HVAC demand Rochester", max_results=5)
    assert result["status"] == tavily_source.OK
    assert result["http_code"] == 200
    assert result["result_count"] == 2
    assert len(result["rows"]) == 2
    assert result["columns"] == list(tavily_source.COLUMNS)
    assert result["rows"][0][1].startswith("https://www.turnbullheating.com/")
    assert result["payload"]["urls"][1].startswith("https://www.indeed.com/")
    assert result["payload"]["result_count"] == 2
    assert result["query"] == SEARCH_BODY["query"]
    assert result["attempts"] == 1 and result["retries"] == 0
    # The key is in the header, never in the body.
    assert seen["body"]["query"] == "HVAC demand Rochester"
    assert "api_key" not in seen["body"]
    assert SENTINEL not in json.dumps(result)


def test_a_200_with_an_error_body_is_degraded_not_ok(monkeypatch):
    secrets_vault.set("tavily", SENTINEL)
    monkeypatch.setattr(tavily_source, "_http",
                        lambda *a, **k: (200, json.dumps({"detail": "Invalid API key"})))
    result = tavily_source.search("ping")
    assert result["status"] == tavily_source.DEGRADED
    assert result["http_code"] == 200
    assert result["reason"].startswith("HTTP 200 but the body did not parse")
    assert result["rows"] == [] and result["result_count"] == 0


# ===========================================================================
# (c) the 429 retry path
# ===========================================================================
def test_429_is_retried_with_backoff_and_then_succeeds(monkeypatch):
    secrets_vault.set("tavily", SENTINEL)
    slept: list[float] = []
    monkeypatch.setattr(tavily_source, "_sleep", lambda seconds: slept.append(seconds))

    responses = [(429, '{"detail": {"error": "rate limit exceeded"}}'),
                 (429, '{"detail": {"error": "rate limit exceeded"}}'),
                 (200, json.dumps(SEARCH_BODY))]
    calls = []

    def _fake_http(url, *, token, method="POST", body=None, timeout=None):
        calls.append(url)
        return responses[len(calls) - 1]

    monkeypatch.setattr(tavily_source, "_http", _fake_http)

    result = tavily_source.search("ping")
    assert len(calls) == 3, "two 429s then the real answer"
    assert slept == [tavily_source.RETRY_BACKOFF_SECONDS,
                     tavily_source.RETRY_BACKOFF_SECONDS * tavily_source.BACKOFF_MULTIPLIER]
    assert result["status"] == tavily_source.OK
    assert result["http_code"] == 200
    assert result["attempts"] == 3
    assert result["retries"] == 2
    assert result["result_count"] == 2
    assert "attempt 3" in result["reason"]


def test_429_exhausted_keeps_the_literal_code_and_zero_rows(monkeypatch):
    secrets_vault.set("tavily", SENTINEL)
    slept: list[float] = []
    monkeypatch.setattr(tavily_source, "_sleep", lambda seconds: slept.append(seconds))
    calls = []

    def _fake_http(url, *, token, method="POST", body=None, timeout=None):
        calls.append(url)
        return 429, '{"detail": {"error": "rate limit exceeded"}}'

    monkeypatch.setattr(tavily_source, "_http", _fake_http)

    result = tavily_source.search("ping")
    assert len(calls) == tavily_source.MAX_ATTEMPTS
    assert len(slept) == tavily_source.MAX_ATTEMPTS - 1
    assert result["status"] == tavily_source.DEGRADED
    assert result["http_code"] == 429
    assert result["reason"].startswith("HTTP 429: ")
    assert result["attempts"] == tavily_source.MAX_ATTEMPTS
    assert result["rows"] == [] and result["result_count"] == 0

    # And the probe reports the same literal code rather than smoothing it.
    entry = _probe_only("tavily")
    assert entry["status"] == live_data.DEGRADED
    assert entry["http_code"] == 429
    assert entry["rows"] == []


def test_a_network_failure_is_degraded_not_raised(monkeypatch):
    secrets_vault.set("tavily", SENTINEL)

    def _boom(*args, **kwargs):
        raise TimeoutError("timed out")

    monkeypatch.setattr(tavily_source, "_http", _boom)
    result = tavily_source.search("ping")
    assert result["status"] == tavily_source.DEGRADED
    assert result["reason"].startswith("TimeoutError: ")
    assert result["rows"] == [] and result["signals"] == []


# ===========================================================================
# (d) the probe reports the literal http_code, and the registry carries the count
# ===========================================================================
def test_probe_reports_the_literal_http_code(monkeypatch):
    secrets_vault.set("tavily", SENTINEL)
    monkeypatch.setattr(tavily_source, "_http", lambda *a, **k: (403, '{"detail": "nope"}'))
    result = tavily_source.probe()
    assert result["status"] == tavily_source.DEGRADED
    assert result["http_code"] == 403
    assert result["attempts"] == 1


def test_tavily_is_wired_into_the_registry_and_the_ingest_bridge():
    ids = [s["id"] for s in live_data.SOURCES]
    assert "tavily" in ids
    assert "tavily" in live_ingest.BRIDGED_SOURCE_IDS
    assert len(live_ingest.BRIDGED_SOURCE_IDS) == len(live_data.SOURCES)


def test_the_card_and_the_api_carry_the_real_result_count(monkeypatch):
    secrets_vault.set("tavily", SENTINEL)
    monkeypatch.setattr(tavily_source, "_http",
                        lambda *a, **k: (200, json.dumps(SEARCH_BODY)))
    _probe_only("tavily")

    snap = live_data.snapshot()
    card = next(c for c in snap["sources"] if c["id"] == "tavily")
    assert card["status"] == live_data.LIVE
    assert card["http_code"] == 200
    assert card["result_count"] == 2
    assert len(card["rows"]) == 2

    from app import create_app

    payload = create_app().test_client().get("/api/live-data").get_json()
    row = next(c for c in payload["sources"] if c["id"] == "tavily")
    assert (row["status"], row["http_code"], row["result_count"]) == ("LIVE", 200, 2)


def test_the_single_source_route_reprobes_only_tavily(monkeypatch):
    """POST /api/live-data/test/tavily probes tavily — and nothing else."""
    secrets_vault.set("tavily", SENTINEL)
    calls = []

    def _fake_http(url, *, token, method="POST", body=None, timeout=None):
        calls.append(url)
        return 200, json.dumps(SEARCH_BODY)

    monkeypatch.setattr(tavily_source, "_http", _fake_http)
    monkeypatch.setattr(live_data, "_probe_one",
                        lambda source: (_ for _ in ()).throw(AssertionError(
                            f"only tavily may be probed, saw {source['id']}"))
                        if source["id"] != "tavily" else _real_probe_one(source))

    from app import create_app

    client = create_app().test_client()
    resp = client.post("/api/live-data/test/tavily")
    assert resp.status_code == 200
    body = resp.get_json()
    assert body["source_id"] == "tavily"
    assert body["status"] == live_data.LIVE
    assert body["http_code"] == 200
    assert body["result_count"] == 2
    assert len(calls) == 1

    assert client.post("/api/live-data/test/not-a-source").status_code == 404


#: The route calls ``live_data._probe_one``; keep a handle on the real one.
_real_probe_one = live_data._probe_one


def test_the_api_probe_flag_sweeps_the_never_probed_sources(monkeypatch):
    """``GET /api/live-data?probe=1`` asks for a real sweep; no flag, no probe."""
    from app import create_app

    calls = []
    monkeypatch.setattr(live_data, "probe_never_probed",
                        lambda only=None: calls.append(only) or [])

    client = create_app().test_client()
    client.get("/api/live-data")
    assert calls == [], "a plain read must not start a probe"
    client.get("/api/live-data?probe=1")
    assert calls == [None], "the flag runs the first-probe sweep once"
