"""Tests for the LIVE-DATA -> OPPORTUNITY bridge (orchestrator/live_ingest.py).

The four required cases:
  (a) a DEGRADED source (401/403/402) writes ZERO claims and keeps its literal reason
  (b) a successful source writes real, cited claims
  (c) opportunity creation with claims=None is unchanged (byte-for-byte)
  (d) POST /live-data/ingest answers 200 with the {status, signals, claims_written}

No test touches the network: the eight 2026-11-18 captures are already seeded in
``live_data``, so ``snapshot()`` is honest without a single request.
"""

from __future__ import annotations

import json
import os
import tempfile

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-live-ingest-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 opportunity  # noqa: E402
from orchestrator.db import connect, init_db  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_stores():
    """Fresh sqlite files + fresh live-data/ingest memory for every test."""
    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)
    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(opportunity_id: str | None = None) -> int:
    conn = memory.connect()
    try:
        if opportunity_id:
            row = conn.execute(
                "SELECT COUNT(*) AS n FROM claims WHERE opportunity_id = ?", (opportunity_id,)
            ).fetchone()
        else:
            row = conn.execute("SELECT COUNT(*) AS n FROM claims").fetchone()
        return int(row["n"])
    finally:
        conn.close()


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


# ---------------------------------------------------------------- (a) degraded

def test_degraded_source_writes_zero_claims_and_keeps_its_literal_reason():
    """401/403/402 => DEGRADED, verbatim reason, zero claims. Never a fabricated claim."""
    summary = _ingest(sources=["massive", "mapbox", "rentcast"])

    assert set(summary) == {"massive", "mapbox", "rentcast"}
    for sid, entry in summary.items():
        assert entry["status"] == "DEGRADED", sid
        assert entry["claims_written"] == 0, sid
        assert entry["signals"] == 0, sid
        assert entry["reason"], sid

    # The literal reasons the endpoints gave — not paraphrases.
    assert summary["massive"]["reason"] == live_data.MASSIVE_NOT_ENTITLED_REASON
    assert summary["massive"]["http_code"] == 403
    assert summary["mapbox"]["reason"].startswith("HTTP 401")
    assert summary["mapbox"]["http_code"] == 401

    # And nothing at all was written.
    assert _claim_count() == 0


# ---------------------------------------------------------------- (b) success

def test_successful_source_writes_cited_claims():
    """A LIVE source's signals become real claims, each carrying url + turn."""
    summary = _ingest(sources=["marketcheck", "xweather"])
    marketcheck = summary["marketcheck"]

    assert marketcheck["status"] == "OK"
    assert marketcheck["signals"] >= 1
    assert marketcheck["claims_written"] >= 1
    assert marketcheck["opportunities"], "a claim must hang off a real opportunity"

    claims = memory.list_claims(opportunity_id=marketcheck["opportunities"][0], limit=50)
    assert len(claims) == marketcheck["claims_written"]
    for claim in claims:
        assert claim["source_url"] == live_data.SOURCE_BY_ID["marketcheck"]["docs"]
        assert claim["source_turn"].startswith("live_data:marketcheck@")
        assert "STALE INVENTORY" in claim["text"]

    # The evidence rows behind the claims are real stored signals.
    conn = connect()
    try:
        stored = conn.execute(
            "SELECT COUNT(*) AS n FROM signals WHERE source = ?", ("live_data/marketcheck",)
        ).fetchone()["n"]
    finally:
        conn.close()
    assert stored == marketcheck["signals"]

    # Re-running is idempotent: the same claims are not written twice.
    again = _ingest(sources=["marketcheck"])
    assert again["marketcheck"]["claims_written"] == 0
    assert again["marketcheck"]["claims_skipped"] == marketcheck["claims_written"]
    assert _claim_count() == marketcheck["claims_written"] + summary["xweather"]["claims_written"]


# ------------------------------------------------------- (c) claims=None intact

def test_build_opportunity_with_claims_none_is_unchanged():
    """The optional parameter must not change the default output in any way."""
    signals = [
        {"id": "sig-a", "source": "hackernews", "url": "https://example.com/a",
         "title": "Stripe raises prices for small business invoicing", "summary": "", "score": 10},
        {"id": "sig-b", "source": "reddit", "url": "https://example.com/b",
         "title": "Small business owners complain about payments pricing", "summary": "",
         "score": 20},
    ]
    signals_by_id = {s["id"]: s for s in signals}
    cluster = {
        "key": "commerce-payments",
        "label": "Commerce & payments",
        "topic": next(t for t in opportunity.TOPICS if t["key"] == "commerce-payments"),
        "signal_ids": ["sig-a", "sig-b"],
        "sources": ["hackernews", "reddit"],
        "size": 2,
    }

    default = opportunity.build_opportunity(cluster, signals_by_id)
    explicit = opportunity.build_opportunity(cluster, signals_by_id, claims=None)

    assert json.dumps(default, sort_keys=True) == json.dumps(explicit, sort_keys=True)
    assert "claims" not in default

    # Passing claims attaches them, but an uncited claim is still refused.
    cited = [{"text": "Stripe raised prices", "source_url": "https://example.com/a",
              "source_turn": "live_data:marketcheck@2026-11-18T06:12:00Z"}]
    with_claims = opportunity.build_opportunity(cluster, signals_by_id, claims=cited)
    assert with_claims["claims"] == cited
    assert with_claims["evidence"] == default["evidence"]
    assert with_claims["composite_score"] == default["composite_score"]

    with pytest.raises(opportunity.UncitedOpportunity):
        opportunity.build_opportunity(
            cluster, signals_by_id, claims=[{"text": "no citation at all"}]
        )


# ------------------------------------------------------------------ (d) route

def test_post_live_data_ingest_route_returns_summary_shape():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    with app.test_client() as client:
        resp = client.post("/live-data/ingest")

    assert resp.status_code == 200
    body = resp.get_json()
    assert isinstance(body, dict) and body, "the summary is a per-source mapping"
    assert "marketcheck" in body
    for sid, entry in body.items():
        assert set(("status", "signals", "claims_written")) <= set(entry), sid
        assert isinstance(entry["signals"], int)
        assert isinstance(entry["claims_written"], int)
        if entry["status"] == "DEGRADED":
            assert entry["claims_written"] == 0

    # The degraded source in the seed set is reported as DEGRADED, not smoothed over.
    assert body["massive"]["status"] == "DEGRADED"
    assert body["massive"]["claims_written"] == 0
    assert "DEGRADED" in json.dumps(body)
