"""Tests for the Groq adapter — real generated text, gated by the vault.

    orchestrator/groq_source.py   hosted open-model drafts, one real probe

The required cases:

  (a) no key             -> DEGRADED, the literal MISSING_KEY_REASON, ZERO claims
  (b) a real 200 body    -> the completion is parsed into the text it carries
  (c) HTTP 429           -> retried with backoff (``_sleep`` patched), then either
                            a real completion or the literal 429 when exhausted
  (d) probe              -> reports the literal ``http_code`` it actually saw

Plus the registry wiring (``groq`` in ``live_data.SOURCES``, so it derives into
``live_ingest.BRIDGED_SOURCE_IDS``) and one guard proving the Overpass
``transport_note()`` sentence is read from the real constants instead of typed.

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-groq-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 groq_source  # noqa: E402
from orchestrator import live_data  # noqa: E402
from orchestrator import live_ingest  # noqa: E402
from orchestrator import memory  # noqa: E402
from orchestrator import overpass  # noqa: E402
from orchestrator import secrets_vault  # noqa: E402
from orchestrator.db import connect, init_db  # noqa: E402

#: A sentinel that could only come from a leaked value.
SENTINEL = "gsk_SENTINEL-do-not-leak-9d2f7b41c8"

#: A real-shaped chat-completions body: what the endpoint actually returns.
COMPLETION_BODY = {
    "id": "chatcmpl-9f2b",
    "object": "chat.completion",
    "model": groq_source.MODEL,
    "choices": [{
        "index": 0,
        "message": {"role": "assistant",
                    "content": "  Rochester HVAC demand rises when the overnight low "
                               "drops below 40F.  "},
        "finish_reason": "stop",
    }],
    "usage": {"prompt_tokens": 41, "completion_tokens": 18, "total_tokens": 59},
}

#: A real-shaped models body: what ``GET /openai/v1/models`` actually returns.
MODELS_BODY = {
    "object": "list",
    "data": [
        {"id": groq_source.MODEL, "object": "model", "owned_by": "openai"},
        {"id": "llama-3.3-70b-versatile", "object": "model", "owned_by": "Meta"},
    ],
}


# ---------------------------------------------------------------------------
# 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 Groq credential unless a test puts one there — and never the real one.
    for name in ("GROQ_API_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, so a test never touches the network."""
    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) no key -> DEGRADED, the literal reason, 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("GROQ_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(groq_source, "_http", _never)

    for result in (groq_source.draft("Write one sentence about HVAC demand."),
                   groq_source.probe(),
                   groq_source.snapshot()):
        assert result["status"] == groq_source.DEGRADED
        assert result["reason"] == "GROQ_API_KEY not set — no request sent"
        assert result["reason"] == groq_source.MISSING_KEY_REASON
        assert result["http_code"] is None, "there was no HTTP call, so there is no code"
        assert result["text"] == ""
        assert result["rows"] == []
        assert result["signals"] == []

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

    # And through the bridge: still zero claims, still a literal reason.
    entry = _probe_only("groq")
    assert entry["status"] == live_data.DEGRADED
    assert entry["detail"] == groq_source.MISSING_KEY_REASON
    assert entry["http_code"] is None
    assert entry["rows"] == []

    before = _claim_count()
    summary = _ingest(["groq"])
    assert summary["groq"]["status"] == "DEGRADED"
    assert summary["groq"]["claims_written"] == 0
    assert summary["groq"]["reason"] == groq_source.MISSING_KEY_REASON
    assert _claim_count() == before


def test_a_stored_key_is_used_and_never_echoed(monkeypatch):
    """A key in the vault makes the request; it never appears in any result."""
    secrets_vault.set("GROQ_API_KEY", SENTINEL)
    seen = {}

    def _fake_http(url, *, token, method="GET", body=None, timeout=None):
        seen["url"] = url
        seen["token"] = token
        seen["method"] = method
        return 401, '{"error": {"message": "Invalid API Key"}}'

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

    result = groq_source.draft("ping")
    assert seen["token"] == SENTINEL, "the vault value is the one that rides the header"
    assert seen["method"] == "POST"
    assert result["status"] == groq_source.DEGRADED
    assert result["http_code"] == 401
    assert result["reason"].startswith("HTTP 401: ")
    assert SENTINEL not in json.dumps(result), "the credential must never be echoed"


# ===========================================================================
# (b) a successful response is parsed into the text it really carries
# ===========================================================================
def test_successful_completion_is_parsed(monkeypatch):
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")

    def _fake_http(url, *, token, method="GET", body=None, timeout=None):
        assert url == groq_source.ENDPOINT
        assert method == "POST"
        sent = json.loads(body.decode("utf-8"))
        assert sent["model"] == groq_source.MODEL
        assert sent["messages"][-1]["content"] == "Write one sentence about HVAC demand."
        return 200, json.dumps(COMPLETION_BODY)

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

    result = groq_source.draft("Write one sentence about HVAC demand.")
    assert result["status"] == groq_source.OK
    assert result["http_code"] == 200
    assert result["text"] == ("Rochester HVAC demand rises when the overnight low "
                              "drops below 40F.")
    assert result["model"] == groq_source.MODEL
    assert result["usage"]["total_tokens"] == 59
    assert result["attempts"] == 1 and result["retries"] == 0
    assert result["source_url"] == groq_source.SOURCE_URL
    # A draft is prose, not a measurement: the adapter emits no signals.
    assert result["signals"] == []


def test_parse_completion_rejects_a_body_that_is_not_a_completion():
    for body in ({}, {"choices": []}, {"choices": [{"message": {"content": "  "}}]},
                 {"error": {"message": "bad request"}}):
        with pytest.raises(ValueError):
            groq_source.parse_completion(body)


def test_200_with_an_unparseable_body_is_degraded(monkeypatch):
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")
    monkeypatch.setattr(groq_source, "_http",
                        lambda *a, **k: (200, '{"error": {"message": "no choices"}}'))
    result = groq_source.draft("ping")
    assert result["status"] == groq_source.DEGRADED
    assert result["http_code"] == 200
    assert result["reason"].startswith("HTTP 200 but the body did not parse:")
    assert result["text"] == "" and result["rows"] == [] and result["signals"] == []


# ===========================================================================
# (c) 429 -> retried with backoff, then a real answer or the literal 429
# ===========================================================================
def test_429_is_retried_with_backoff_and_then_succeeds(monkeypatch):
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")
    slept: list[float] = []
    monkeypatch.setattr(groq_source, "_sleep", lambda seconds: slept.append(seconds))

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

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

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

    result = groq_source.draft("ping")
    assert len(calls) == 3, "two 429s then the real answer"
    assert slept == [groq_source.RETRY_BACKOFF_SECONDS,
                     groq_source.RETRY_BACKOFF_SECONDS * groq_source.BACKOFF_MULTIPLIER]
    assert result["status"] == groq_source.OK
    assert result["http_code"] == 200
    assert result["attempts"] == 3
    assert result["retries"] == 2
    assert result["text"].startswith("Rochester HVAC demand rises")


def test_429_exhausted_reports_the_literal_code_and_zero_text(monkeypatch):
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")
    monkeypatch.setattr(groq_source, "_sleep", lambda seconds: None)
    calls = []

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

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

    result = groq_source.draft("ping")
    assert len(calls) == groq_source.MAX_ATTEMPTS
    assert result["status"] == groq_source.DEGRADED
    assert result["http_code"] == 429
    assert result["reason"].startswith("HTTP 429: ")
    assert result["attempts"] == groq_source.MAX_ATTEMPTS
    assert result["text"] == "" and result["rows"] == [] and result["signals"] == []


def test_a_non_retryable_status_is_not_retried(monkeypatch):
    """A 401 is a real answer, not a rate limit: one attempt, literal code."""
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")
    slept: list[float] = []
    monkeypatch.setattr(groq_source, "_sleep", lambda seconds: slept.append(seconds))
    calls = []

    def _fake_http(url, *, token, method="GET", body=None, timeout=None):
        calls.append(url)
        return 401, '{"error": {"message": "Invalid API Key"}}'

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

    result = groq_source.draft("ping")
    assert len(calls) == 1
    assert slept == []
    assert result["status"] == groq_source.DEGRADED
    assert result["http_code"] == 401


def test_a_network_failure_is_degraded_not_raised(monkeypatch):
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")

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

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


# ===========================================================================
# (d) the probe reports the literal http_code it actually saw
# ===========================================================================
def test_probe_reports_the_literal_http_code(monkeypatch):
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")

    monkeypatch.setattr(groq_source, "_http",
                        lambda *a, **k: (200, json.dumps(MODELS_BODY)))
    ok = groq_source.probe()
    assert ok["status"] == groq_source.OK
    assert ok["http_code"] == 200
    assert [row[0] for row in ok["rows"]] == [groq_source.MODEL,
                                              "llama-3.3-70b-versatile"]
    assert ok["payload"]["model_available"] is True
    assert ok["signals"] == [], "a model listing is not a claim"

    for code in (401, 403, 429, 500):
        monkeypatch.setattr(groq_source, "_http",
                            lambda *a, _c=code, **k: (_c, '{"error": "nope"}'))
        result = groq_source.probe()
        assert result["status"] == groq_source.DEGRADED
        assert result["http_code"] == code, "the literal code, never smoothed into a pass"
        assert result["reason"].startswith(f"HTTP {code}: ")
        assert result["rows"] == [] and result["signals"] == []


def test_probe_uses_the_models_endpoint_not_the_completion_endpoint(monkeypatch):
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")
    seen = {}

    def _fake_http(url, *, token, method="GET", body=None, timeout=None):
        seen["url"], seen["method"] = url, method
        return 200, json.dumps(MODELS_BODY)

    monkeypatch.setattr(groq_source, "_http", _fake_http)
    groq_source.probe()
    assert seen["url"] == groq_source.MODELS_ENDPOINT
    assert seen["method"] == "GET"


# ===========================================================================
# wiring: groq is registered, bridged, and appears in the JSON payload
# ===========================================================================
def test_groq_is_registered_and_bridged():
    ids = {s["id"]: s for s in live_data.SOURCES}
    assert "groq" in ids
    assert ids["groq"]["credential_env"] == groq_source.TOKEN_NAME
    assert ids["groq"]["probe"] is live_data.probe_groq
    assert not ids["groq"].get("keyless"), "groq is vault-gated, not keyless"

    # Derived, not listed by hand.
    assert "groq" in live_ingest.BRIDGED_SOURCE_IDS
    assert len(live_ingest.BRIDGED_SOURCE_IDS) == len(live_data.SOURCES)


def test_groq_card_appears_in_the_snapshot_and_api(monkeypatch):
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")
    monkeypatch.setattr(groq_source, "_http",
                        lambda *a, **k: (200, json.dumps(MODELS_BODY)))
    _probe_only("groq")

    snap = live_data.snapshot()
    card = next(c for c in snap["sources"] if c["id"] == "groq")
    assert card["status"] == live_data.LIVE
    assert card["http_code"] == 200
    assert card["rows"], "the model inventory is the probe's real evidence"

    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"] == "groq")
    assert row["status"] == live_data.LIVE
    assert row["http_code"] == 200


def test_the_per_source_probe_route_records_one_real_probe(monkeypatch):
    """``POST /api/live-data/test/<id>`` probes exactly one adapter.

    The whole-registry route is honest but slow (the Overpass mirror failover can
    take a minute), so a single source can be re-checked on its own. An unknown id
    is a 404 — never an empty pass.
    """
    secrets_vault.set("GROQ_API_KEY", "test-key-not-a-real-credential")
    calls = []

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

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

    from app import create_app

    client = create_app().test_client()
    resp = client.post("/api/live-data/test/groq")
    assert resp.status_code == 200
    entry = resp.get_json()
    assert entry["source_id"] == "groq"
    assert entry["status"] == live_data.LIVE
    assert entry["http_code"] == 200
    assert calls == [groq_source.MODELS_ENDPOINT], "one real call, to the models endpoint"

    # The recorded capture is what /api/live-data now serves.
    row = next(c for c in client.get("/api/live-data").get_json()["sources"]
               if c["id"] == "groq")
    assert row["status"] == live_data.LIVE
    assert row["http_code"] == 200

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


# ===========================================================================
# the Overpass transport note is derived from the constants, not typed
# ===========================================================================
def test_overpass_transport_note_is_derived_from_the_constants(monkeypatch):
    """The sentence moves when the constants move — so it cannot drift.

    The constants themselves are untouched by this suite: the timeout stays 25s
    and the TTL stays six hours.
    """
    assert overpass.MIRROR_TIMEOUT_SECONDS == 25.0
    assert overpass.CACHE_TTL_SECONDS == 6 * 60 * 60

    baseline = overpass.transport_note()
    assert f"{overpass.MIRROR_TIMEOUT_SECONDS:g}s" in baseline
    assert f"{len(overpass.ENDPOINTS)}-mirror failover" in baseline
    assert "6-hour" in baseline

    monkeypatch.setattr(overpass, "MIRROR_TIMEOUT_SECONDS", 40.0)
    monkeypatch.setattr(overpass, "CACHE_TTL_SECONDS", 90 * 60)
    moved = overpass.transport_note()
    assert "40s per-query ceiling" in moved
    assert "90-min" in moved
    assert "25s" not in moved and "6-hour" not in moved
    # Nothing about the sentence is hardcoded: every number came from a constant.
    assert moved != baseline
