"""Tests for the durable memory store.

Covers the required guarantees:
  1. schema exists in a file-backed SQLite DB with the five tables
  2. a claim without source_url and/or source_turn is refused (API + module + SQL)
  3. JSON endpoints round-trip for all five record types
  4. LIKE search covers claims.text and opportunities.title, with citations
  5. first run seeds 3 opportunities + 6 claims, all cited (100%)

Run:  pytest -q
"""

from __future__ import annotations

import os
import sqlite3
import tempfile

import pytest

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

from orchestrator import memory  # noqa: E402
from orchestrator.errors import ValidationError  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_store():
    path = os.environ["JARVIS_MEMORY_DB"]
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(path + suffix)
        except FileNotFoundError:
            pass
    memory.init_db()
    yield
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(path + suffix)
        except FileNotFoundError:
            pass


@pytest.fixture()
def seeded():
    memory.seed_if_empty()
    return memory


def test_db_is_file_backed_with_all_tables(fresh_store):
    memory.init_db()
    path = memory.db_path()
    assert path.endswith(os.path.join("data", "jarvis.db"))
    assert os.path.exists(path)
    conn = sqlite3.connect(path)
    try:
        tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
        cols = {
            "opportunities": {"id", "title", "source_url", "found_at", "status"},
            "claims": {"id", "opportunity_id", "text", "source_url", "source_turn", "captured_at"},
            "decisions": {"id", "opportunity_id", "verdict", "rule_version", "rationale", "decided_at"},
            "outcomes": {"id", "opportunity_id", "metric", "value", "measured_at"},
            "rule_versions": {"version", "description", "precision", "recall", "published_at"},
        }
        for table, expected in cols.items():
            assert table in tables, table
            actual = {r[1] for r in conn.execute(f"PRAGMA table_info({table})")}
            assert expected <= actual, (table, expected - actual)
        # NOT NULL is declared at the schema level too.
        claim_cols = {r[1]: r for r in conn.execute("PRAGMA table_info(claims)")}
        assert claim_cols["source_url"][3] == 1
        assert claim_cols["source_turn"][3] == 1
    finally:
        conn.close()


def test_seed_creates_three_opportunities_and_six_cited_claims(seeded):
    opps = seeded.list_opportunities()
    claims = seeded.list_claims()
    assert len(opps) == 3
    assert len(claims) == 6
    assert all(c["has_citation"] for c in claims)
    stats = seeded.stats()
    assert stats["total_opportunities"] == 3
    assert stats["total_claims"] == 6
    assert stats["pct_claims_with_citations"] == 100.0
    assert stats["sample_opportunities"] == 3
    assert all(o["sample"] for o in opps)


def test_seed_is_idempotent(seeded):
    seeded.seed_if_empty()
    seeded.seed_if_empty()
    assert len(seeded.list_opportunities()) == 3
    assert len(seeded.list_claims()) == 6


@pytest.mark.parametrize(
    "url,turn",
    [(None, "t1"), ("https://example.com/a", None), (None, None), ("   ", "t1"), ("https://example.com/a", "  ")],
)
def test_claim_without_citation_is_refused(seeded, url, turn):
    with pytest.raises(memory.CitationError) as exc:
        seeded.create_claim(
            opportunity_id="sample-opp-1", text="an uncited assertion", source_url=url, source_turn=turn
        )
    assert exc.value.status == 400
    assert exc.value.code == "citation_required"
    assert len(seeded.list_claims()) == 6, "nothing may be written"


def test_sql_cannot_store_null_citation(seeded):
    conn = seeded.connect()
    try:
        with pytest.raises(sqlite3.IntegrityError):
            conn.execute(
                "INSERT INTO claims (opportunity_id, text, source_url, source_turn, captured_at)"
                " VALUES ('sample-opp-1','x',NULL,'t1','2026-11-01T00:00:00Z')"
            )
            conn.commit()
    finally:
        conn.close()


def test_claim_with_citation_roundtrips(seeded):
    row = seeded.create_claim(
        opportunity_id="sample-opp-1",
        text="The owner repeats the two-day reconciliation complaint.",
        source_url="https://example.com/thread/1",
        source_turn="turn-7",
    )
    assert row["source_url"] == "https://example.com/thread/1"
    assert row["source_turn"] == "turn-7"
    assert row["has_citation"] is True
    assert seeded.stats()["total_claims"] == 7


def test_decision_requires_known_rule_and_valid_verdict(seeded):
    with pytest.raises(ValidationError):
        seeded.create_decision(opportunity_id="sample-opp-1", verdict="maybe", rule_version="v0.3.0")
    with pytest.raises(memory.NotFound):
        seeded.create_decision(opportunity_id="sample-opp-1", verdict="keep", rule_version="v9.9.9")
    row = seeded.create_decision(
        opportunity_id="sample-opp-1", verdict="kill", rule_version="v0.2.0", rationale="pricing floor"
    )
    assert row["verdict"] == "kill"
    assert seeded.latest_decisions()["sample-opp-1"]["rule_version"] == "v0.2.0"


def test_search_matches_claim_text_and_opportunity_title(seeded):
    by_claim = seeded.search("questionnaire")
    assert by_claim["claim_count"] == 2
    assert by_claim["citations_visible"] == 2
    assert all(c["source_url"] and c["source_turn"] for c in by_claim["claims"])
    by_title = seeded.search("restaurant")
    assert by_title["opportunity_count"] == 1
    assert by_title["claim_count"] >= 1
    assert seeded.search("")["claim_count"] == 0


def test_search_escapes_like_wildcards(seeded):
    assert seeded.search("%")["claim_count"] == 0
    assert seeded.search("_")["claim_count"] == 0


# ---------------------------- HTTP surface --------------------------------

@pytest.fixture()
def client(seeded):
    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_get_endpoints(client):
    for path, key in [
        ("/api/memory/opportunities", "opportunities"),
        ("/api/memory/claims", "claims"),
        ("/api/memory/decisions", "decisions"),
        ("/api/memory/outcomes", "outcomes"),
        ("/api/memory/rules", "rules"),
    ]:
        resp = client.get(path)
        assert resp.status_code == 200, path
        body = resp.get_json()
        assert key in body and body["count"] == len(body[key])


def test_api_rejects_uncited_claim(client):
    before = client.get("/api/memory/claims").get_json()["count"]
    resp = client.post(
        "/api/memory/claims", json={"opportunity_id": "sample-opp-2", "text": "no citation here"}
    )
    assert resp.status_code == 400
    body = resp.get_json()
    assert body["error"] == "citation_required"
    assert "source_url" in body["message"] and "source_turn" in body["message"]
    assert client.get("/api/memory/claims").get_json()["count"] == before


def test_api_post_roundtrip(client):
    opp = client.post(
        "/api/memory/opportunities",
        json={"title": "API opportunity", "source_url": "https://example.com/opp", "status": "open"},
    )
    assert opp.status_code == 201
    opp_id = opp.get_json()["id"]

    claim = client.post(
        "/api/memory/claims",
        json={
            "opportunity_id": opp_id,
            "text": "cited via API",
            "source_url": "https://example.com/opp#c1",
            "source_turn": "turn-3",
        },
    )
    assert claim.status_code == 201
    assert claim.get_json()["source_turn"] == "turn-3"

    decision = client.post(
        "/api/memory/decisions",
        json={"opportunity_id": opp_id, "verdict": "keep", "rule_version": "v0.3.0", "rationale": "test"},
    )
    assert decision.status_code == 201

    outcome = client.post(
        "/api/memory/outcomes",
        json={"opportunity_id": opp_id, "metric": "calls", "value": 4},
    )
    assert outcome.status_code == 201
    assert outcome.get_json()["value"] == 4.0

    rule = client.post(
        "/api/memory/rules",
        json={"version": "v9.0.0", "description": "test rule", "precision": 0.9, "recall": 0.5},
    )
    assert rule.status_code == 201
    assert any(r["version"] == "v9.0.0" for r in client.get("/api/memory/rules").get_json()["rules"])


def test_api_search_and_memory_page(client):
    body = client.get("/api/memory/search?q=questionnaire").get_json()
    assert body["claim_count"] == 2
    assert all(c["source_url"] and c["source_turn"] for c in body["claims"])

    page = client.get("/memory")
    assert page.status_code == 200
    html = page.get_data(as_text=True)
    for needle in ("SAMPLE DATA", "Rule-version history", "100.0%", "sample-t1", "/api/memory/search"):
        assert needle in html, needle
