"""Tests for the SECRETS VAULT and the MAPBOX adapter.

The seven cases the brief asks for:

  1. no MAPBOX_TOKEN            -> DEGRADED "NEEDS KEY", zero claims, no request
  2. a secret value never reaches the audit ledger, a claim or an HTTP response
  3. secrets_vault resolution    -> env beats file, file when env is absent, None
  4. list_names()/status()       -> names and PRESENT/MISSING only, never a value
  5. Mapbox 401/403/429/non-200  -> DEGRADED and zero claims (mocked HTTP)
  6. a real (mocked) 200 with >=5 businesses -> MARKET SIZE signal + cited claims
  7. the rest of the app is unchanged when no Mapbox token is configured

Nothing here touches the network: the only HTTP layer that exists in the adapter
is ``mapbox_source._http``, and every test that expects a response monkeypatches
it. The no-token tests assert it is never called at all.
"""

from __future__ import annotations

import json
import os
import stat
import tempfile

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-mapbox-secrets-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 audit  # noqa: E402
from orchestrator import live_data  # noqa: E402
from orchestrator import live_ingest  # noqa: E402
from orchestrator import mapbox_source  # noqa: E402
from orchestrator import memory  # noqa: E402
from orchestrator import secrets_vault  # noqa: E402
from orchestrator.db import connect as db_connect, init_db  # noqa: E402

#: A sentinel that could only come from a leaked value. Long enough to be redacted
#: to four characters, distinctive enough that a grep cannot be a coincidence.
SENTINEL = "pk.SENTINEL-do-not-leak-6f4a1c9e"


# ---------------------------------------------------------------------------
# fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(autouse=True)
def fresh_state(monkeypatch, tmp_path):
    """Fresh sqlite files, fresh vault file, fresh in-memory live-data state."""
    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 credential in the environment unless a test puts one there.
    for name in ("MAPBOX_TOKEN", "MAPBOX_API_KEY", "MAPBOX_ACCESS_TOKEN",
                 "RENTCAST_API_KEY", "INTERFAZE_API_KEY", "PARALLEL_API_KEY"):
        monkeypatch.delenv(name, raising=False)
    # The vault is a throwaway file outside the repo, unique per test.
    vault_path = tmp_path / "vault" / "secrets.json"
    monkeypatch.setenv("JARVIS_SECRETS_FILE", str(vault_path))

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


def _probe_mapbox_into_live_data():
    """Run the registry's mapbox probe and make it the current capture.

    The other seven keep their seeded 2026-11-18 captures, so the snapshot looks
    exactly like the running app's.
    """
    live_data.seed_if_empty()
    entry = live_data._probe_one(live_data.SOURCE_BY_ID["mapbox"])
    live_data._record_capture(entry)
    return entry


def _mapbox_card() -> dict:
    return next(c for c in live_data.cards() if c["id"] == "mapbox")


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


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


def _feature(name: str, address: str, lat: float, lon: float, category="HVAC contractor"):
    return {
        "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [lon, lat]},
        "properties": {"name": name, "full_address": address, "poi_category": [category]},
    }


def _payload(*features):
    return {"type": "FeatureCollection", "features": list(features)}


def _rochester_businesses(n: int = 6):
    """n places inside 50 mi of Rochester, NY (plus one that is NOT)."""
    base = [
        ("Rochester Heating & Air", "210 South Ave, Rochester, NY 14604", 43.1560, -77.6100),
        ("Isaac Heating and Air Conditioning", "50 Holleder Pkwy, Rochester, NY 14615", 43.1900, -77.6300),
        ("Comfort Zone HVAC", "1900 Empire Blvd, Webster, NY 14580", 43.2100, -77.4500),
        ("T. Bell Heating & Cooling", "1200 Ridge Rd W, Greece, NY 14615", 43.2100, -77.7000),
        ("Pittsford Climate Control", "10 State St, Pittsford, NY 14534", 43.0900, -77.5100),
        ("Fairport Furnace Works", "5 Main St, Fairport, NY 14450", 43.1000, -77.4400),
        ("Way-Out-Of-Range HVAC", "999 Elsewhere Rd, Syracuse, NY", 45.5000, -77.6000),
    ]
    return [_feature(*row) for row in base[:n]] + [_feature(*base[-1])]


# ===========================================================================
# 1. no token -> NEEDS KEY, zero claims, and no HTTP request at all
# ===========================================================================
def test_missing_token_is_needs_key_and_writes_zero_claims(monkeypatch):
    calls = []
    monkeypatch.setattr(mapbox_source, "_http",
                        lambda *a, **k: calls.append(a) or pytest.fail("no request may be sent"))

    result = mapbox_source.count_businesses(
        mapbox_source.DEFAULT_CATEGORY, mapbox_source.DEFAULT_LAT,
        mapbox_source.DEFAULT_LON, mapbox_source.DEFAULT_RADIUS_MILES,
    )

    assert result["status"] == "NEEDS KEY"
    assert "MAPBOX_TOKEN not set" in result["reason"]
    assert result["count"] == 0
    assert result["businesses"] == []
    assert result["rows"] == []
    assert result["signals"] == []
    assert calls == [], "a missing credential must not produce a request"

    # The live-data card says the same thing, and the bridge turns it into zero
    # claims — the same structural guarantee every refused source gets.
    _probe_mapbox_into_live_data()
    card = _mapbox_card()
    assert card["status"] == live_data.NEEDS_KEY
    assert card["rows"] == []
    assert card["signals"] == []

    summary = _ingest(["mapbox"])
    assert summary["mapbox"]["status"] == "DEGRADED"
    assert summary["mapbox"]["claims_written"] == 0
    assert summary["mapbox"]["signals"] == 0
    assert "MAPBOX_TOKEN not set" in summary["mapbox"]["reason"]
    assert _claim_count() == 0


# ===========================================================================
# 2. a secret value never leaves the vault (ledger, claims, HTTP responses)
# ===========================================================================
def test_secret_value_never_reaches_audit_claims_or_http_responses(monkeypatch):
    secrets_vault.set("MAPBOX_TOKEN", SENTINEL)
    assert secrets_vault.get("MAPBOX_TOKEN") == SENTINEL  # the vault does hold it

    # (a) a successful call writes claims, an audit row and stored signals
    monkeypatch.setattr(mapbox_source, "_http", lambda *a, **k: (200, json.dumps(
        _payload(*_rochester_businesses(6)))))
    _probe_mapbox_into_live_data()
    summary = _ingest(["mapbox"])
    assert summary["mapbox"]["claims_written"] >= 1

    # (b) a failure whose exception text carries the credential (the URL does)
    #     must still be scrubbed before it is recorded anywhere.
    def _boom(url, **kwargs):
        raise RuntimeError(f"connection reset while calling {url}")

    monkeypatch.setattr(mapbox_source, "_http", _boom)
    failed = _probe_mapbox_into_live_data()
    assert failed["status"] == live_data.ERROR
    assert SENTINEL not in failed["detail"], "the adapter must scrub its own evidence"

    # -- the ledger: nothing, in any row, at any depth -----------------------
    ledger = json.dumps(audit.recent(limit=1000))
    assert SENTINEL not in ledger
    assert secrets_vault.redact(SENTINEL) not in ledger or SENTINEL not in ledger

    # The secrets.set row carries the NAME and presence, nothing else.
    rows = audit.recent(limit=50, action="secrets.set")
    assert rows, "storing a key is an auditable event"
    assert rows[0]["subject_id"] == "MAPBOX_TOKEN"
    assert set(rows[0]["payload"]) <= {"name", "present", "layer"}
    assert rows[0]["payload"]["present"] is True

    # -- the claims and the signals -----------------------------------------
    conn = memory.connect()
    try:
        claim_rows = conn.execute("SELECT text, source_url, source_turn FROM claims").fetchall()
        opp_rows = conn.execute("SELECT title, source_url FROM opportunities").fetchall()
    finally:
        conn.close()

    # The opportunity the claim hangs off lives in the main DB, whose schema
    # carries the narrative fields; check those too.
    main_conn = db_connect()
    try:
        main_opp_rows = main_conn.execute(
            "SELECT title, what_they_need, evidence, sources FROM opportunities").fetchall()
    finally:
        main_conn.close()
    assert claim_rows, "the successful call really did write claims"
    for row in claim_rows:
        for field in row:
            assert SENTINEL not in str(field)
        assert "access_token" not in str(row["source_url"])
    for row in list(opp_rows) + list(main_opp_rows):
        for field in row:
            assert SENTINEL not in str(field)

    # -- the raw stores, byte for byte --------------------------------------
    for path in (os.environ["JARVIS_DB"], os.environ["JARVIS_MEMORY_DB"]):
        for suffix in ("", "-wal", "-shm"):
            try:
                with open(path + suffix, "rb") as fh:
                    blob = fh.read()
            except FileNotFoundError:
                continue
            assert SENTINEL.encode() not in blob, f"secret found in {path + suffix}"

    # -- every HTTP response body -------------------------------------------
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as client:
        responses = {
            "live data page": client.get("/live-data"),
            "live data api": client.get("/api/live-data"),
            "secrets api": client.get("/api/secrets"),
            "ingest": client.post("/live-data/ingest"),
            "snapshot": client.get("/api/snapshot") if _has_route(app, "/api/snapshot") else None,
        }
    for label, resp in responses.items():
        if resp is None:
            continue
        assert resp.status_code < 500, label
        body = resp.get_data(as_text=True)
        assert SENTINEL not in body, f"secret leaked in the {label} response"

    # The secrets API is names + presence, and the page really does list them.
    with app.test_client() as client:
        payload = client.get("/api/secrets").get_json()
        page = client.get("/live-data").get_data(as_text=True)
    assert set(payload["keys"]) == set(secrets_vault.KNOWN_KEYS)
    assert payload["keys"]["MAPBOX_TOKEN"] == "PRESENT"
    assert SENTINEL not in json.dumps(payload)
    assert "MAPBOX_TOKEN" in page and "Secrets" in page


def _has_route(app, rule: str) -> bool:
    return any(r.rule == rule for r in app.url_map.iter_rules())


# ===========================================================================
# 3. resolution order: environment -> file -> None
# ===========================================================================
def test_resolution_order_env_beats_file_then_file_then_none(monkeypatch):
    secrets_vault.set("RENTCAST_API_KEY", "value-from-the-file")

    # No environment variable: the file answers.
    assert secrets_vault.get("RENTCAST_API_KEY") == "value-from-the-file"
    assert secrets_vault.source("RENTCAST_API_KEY") == "file"

    # The environment beats the file.
    monkeypatch.setenv("RENTCAST_API_KEY", "value-from-the-environment")
    assert secrets_vault.get("RENTCAST_API_KEY") == "value-from-the-environment"
    assert secrets_vault.source("RENTCAST_API_KEY") == "env"

    # Neither: None, and the same through a documented alias for MAPBOX.
    monkeypatch.delenv("RENTCAST_API_KEY")
    secrets_vault.delete("RENTCAST_API_KEY")
    assert secrets_vault.get("RENTCAST_API_KEY") is None
    assert secrets_vault.source("RENTCAST_API_KEY") is None
    assert secrets_vault.has("RENTCAST_API_KEY") is False

    secrets_vault.set("MAPBOX_TOKEN", "mapbox-from-file")
    monkeypatch.setenv("MAPBOX_API_KEY", "mapbox-from-environment")
    assert secrets_vault.get("MAPBOX_TOKEN") == "mapbox-from-environment"
    assert secrets_vault.source("MAPBOX_TOKEN") == "env"


# ===========================================================================
# 4. list_names() / status() never return a value
# ===========================================================================
def test_list_names_and_status_never_return_values():
    for name in secrets_vault.KNOWN_KEYS:
        secrets_vault.set(name, f"{SENTINEL}-{name.lower()}")

    names = secrets_vault.list_names()
    st = secrets_vault.status()

    assert set(secrets_vault.KNOWN_KEYS) <= set(names)
    for name in secrets_vault.KNOWN_KEYS:
        assert SENTINEL not in name
        assert st[name] == "PRESENT"
    assert set(st.values()) <= {"PRESENT", "MISSING"}
    assert SENTINEL not in json.dumps(names)
    assert SENTINEL not in json.dumps(st)
    assert SENTINEL not in json.dumps(secrets_vault.summary())

    # A short value is masked completely; a longer one shows four characters.
    assert secrets_vault.redact("abc") == "…"
    assert secrets_vault.redact(SENTINEL) == "pk.S…"
    assert SENTINEL not in secrets_vault.redact(SENTINEL)

    # Status reports MISSING for a name nothing supplies.
    secrets_vault.delete("PARALLEL_API_KEY")
    assert secrets_vault.status()["PARALLEL_API_KEY"] == "MISSING"


# ===========================================================================
# 5. every refusal status -> DEGRADED and zero claims
# ===========================================================================
@pytest.mark.parametrize("code,expected", [
    (401, "NEEDS KEY"),
    (403, "NOT ENTITLED"),
    (429, "RATE LIMITED"),
    (500, "DEGRADED"),
    (418, "DEGRADED"),
])
def test_non_200_responses_are_degraded_and_write_zero_claims(monkeypatch, code, expected):
    secrets_vault.set("MAPBOX_TOKEN", SENTINEL)
    monkeypatch.setattr(mapbox_source, "_http",
                        lambda *a, **k: (code, '{"message":"refused by the endpoint"}'))

    result = mapbox_source.count_businesses("HVAC contractor", 43.1566, -77.6088, 50)
    assert result["status"] == expected
    assert result["http_code"] == code
    assert result["count"] == 0
    assert result["businesses"] == []
    assert result["rows"] == []
    assert result["signals"] == []
    assert str(code) in result["reason"]

    _probe_mapbox_into_live_data()
    card = _mapbox_card()
    assert card["status"] in (live_data.NEEDS_KEY, live_data.NOT_ENTITLED, live_data.ERROR)
    assert card["rows"] == []

    summary = _ingest(["mapbox"])
    assert summary["mapbox"]["claims_written"] == 0
    assert summary["mapbox"]["signals"] == 0
    assert summary["mapbox"]["reason"]
    if code == 401:
        assert summary["mapbox"]["status"] == "DEGRADED"
    if code == 403:
        assert summary["mapbox"]["status"] == "DEGRADED"
        assert summary["mapbox"]["http_code"] == 403
    assert _claim_count() == 0


def test_network_error_is_degraded_with_the_literal_error(monkeypatch):
    secrets_vault.set("MAPBOX_TOKEN", SENTINEL)

    def _down(url, **kwargs):
        raise TimeoutError("timed out after 8s")

    monkeypatch.setattr(mapbox_source, "_http", _down)
    result = mapbox_source.count_businesses("HVAC contractor", 43.1566, -77.6088, 50)
    assert result["status"] == "DEGRADED"
    assert "TimeoutError" in result["reason"] and "timed out after 8s" in result["reason"]
    assert result["rows"] == [] and result["signals"] == []
    assert SENTINEL not in result["reason"]


# ===========================================================================
# 6. a real 200 with >= 5 businesses -> MARKET SIZE + cited claims
# ===========================================================================
def test_successful_search_emits_market_size_and_writes_cited_claims(monkeypatch):
    secrets_vault.set("MAPBOX_TOKEN", SENTINEL)
    payload = _payload(*_rochester_businesses(6))
    monkeypatch.setattr(mapbox_source, "_http", lambda *a, **k: (200, json.dumps(payload)))

    result = mapbox_source.count_businesses("HVAC contractor", 43.1566, -77.6088, 50)
    assert result["status"] == "OK"
    assert result["count"] == 6, "the out-of-range place must be filtered out"
    assert all(b["name"] and b["address"] for b in result["businesses"])
    assert result["signals"], "6 businesses is a countable market"
    sig = result["signals"][0]
    assert sig["kind"] == "MARKET SIZE"
    assert "6" in sig["line"] and "HVAC contractor" in sig["line"]

    entry = _probe_mapbox_into_live_data()
    assert entry["status"] == live_data.LIVE
    card = _mapbox_card()
    assert len(card["rows"]) == 6
    assert [s["kind"] for s in card["signals"]] == ["MARKET SIZE"]

    summary = _ingest(["mapbox"])
    assert summary["mapbox"]["status"] == "OK"
    assert summary["mapbox"]["signals"] == 1
    assert summary["mapbox"]["claims_written"] == 1
    opp_id = summary["mapbox"]["opportunities"][0]

    claims = memory.list_claims(opportunity_id=opp_id, limit=20)
    assert len(claims) == 1
    claim = claims[0]
    assert "MARKET SIZE" in claim["text"]
    assert claim["source_url"] == mapbox_source.SOURCE_URL
    assert claim["source_turn"].startswith("live_data:mapbox@")
    assert SENTINEL not in claim["text"]

    # The evidence behind the claim is a real stored signal row.
    conn = db_connect()
    try:
        n = conn.execute("SELECT COUNT(*) AS n FROM signals WHERE source = ?",
                         ("live_data/mapbox",)).fetchone()["n"]
    finally:
        conn.close()
    assert n == 1


def test_four_businesses_does_not_emit_a_market_size_signal(monkeypatch):
    secrets_vault.set("MAPBOX_TOKEN", SENTINEL)
    monkeypatch.setattr(mapbox_source, "_http", lambda *a, **k: (200, json.dumps(
        _payload(*_rochester_businesses(4)))))

    result = mapbox_source.count_businesses("HVAC contractor", 43.1566, -77.6088, 50)
    assert result["status"] == "OK"
    assert result["count"] == 4
    assert result["signals"] == [], "fewer than five businesses is not a countable market"


# ===========================================================================
# 7. the rest of the app is unchanged with no Mapbox token configured
# ===========================================================================
def test_other_sources_are_unchanged_without_a_mapbox_token():
    live_data.seed_if_empty()
    snap = live_data.snapshot()

    # Twelve sources: the original eight, the two keyless adapters
    # (overpass, open_meteo) that need no credential at all, and the two
    # vault-gated adapters (Groq drafts, Tavily web search).
    assert len(snap["sources"]) == 12
    by_id = {c["id"]: c for c in snap["sources"]}
    assert set(by_id) == {"marketcheck", "xweather", "financial_datasets", "massive",
                          "mapbox", "overpass", "open_meteo", "rentcast",
                          "interfaze", "parallel", "groq", "tavily"}
    # The seeded captures are untouched.
    assert by_id["marketcheck"]["status"] == live_data.LIVE
    assert by_id["xweather"]["status"] == live_data.LIVE
    assert by_id["massive"]["status"] == live_data.NOT_ENTITLED
    # Mapbox is present and honest rather than missing or fabricated.
    assert by_id["mapbox"]["status"] == live_data.NEEDS_KEY
    assert by_id["mapbox"]["rows"] == []

    summary = _ingest(["marketcheck", "xweather"])
    assert summary["marketcheck"]["status"] == "OK"
    assert summary["marketcheck"]["claims_written"] >= 1
    assert summary["xweather"]["status"] == "OK"
    assert "mapbox" not in summary


def test_secrets_file_lives_outside_the_repo_with_strict_modes():
    secrets_vault.set("MAPBOX_TOKEN", SENTINEL)
    path = secrets_vault.secrets_path()
    assert not os.path.abspath(path).startswith(secrets_vault.REPO_ROOT + os.sep)
    assert secrets_vault.REPO_ROOT not in os.path.abspath(path).split(os.sep)
    assert stat.S_IMODE(os.stat(path).st_mode) == 0o600
    assert stat.S_IMODE(os.stat(os.path.dirname(path)).st_mode) == 0o700
    with open(path, "r", encoding="utf-8") as fh:
        assert json.load(fh)["keys"]["MAPBOX_TOKEN"] == SENTINEL
