"""Tests for the REAL ingestion layer (the senses).

Covers the four required areas:
  1. normalisation into the one common signal shape
  2. dedupe by stable id (re-running never duplicates)
  3. graceful handling of a source that errors (run completes + failure logged)
  4. the component is registered as the INGESTED handler

No test touches the network: every HTTP call is mocked.
"""

from __future__ import annotations

import os
import tempfile

import pytest

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

from orchestrator import ingestion  # noqa: E402
from orchestrator import service  # noqa: E402
from orchestrator import state_machine as sm  # noqa: E402
from orchestrator.components import register_default_components  # noqa: E402
from orchestrator.db import connect, init_db  # noqa: E402
from orchestrator.events import verify_chain  # noqa: E402
from orchestrator.registry import REGISTRY  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_db():
    db = os.environ["JARVIS_DB"]
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(db + suffix)
        except FileNotFoundError:
            pass
    init_db()
    REGISTRY.clear()
    register_default_components(REGISTRY)
    yield
    REGISTRY.clear()
    register_default_components(REGISTRY)


def fake_source(name="fake/feed", items=None, boom=None):
    def _fetch(limit):
        if boom is not None:
            raise boom
        return list(items or [])

    return {"name": name, "kind": "test", "url": f"https://example.invalid/{name}", "fetch": _fetch}


def sample_items(n=2, source="fake/feed"):
    return [
        ingestion.normalize_item(
            source,
            title=f"Real headline {i}",
            url=f"https://example.invalid/story/{i}",
            summary=f"snippet {i}",
            score=100 - i,
            rank=i,
            raw={"i": i},
        )
        for i in range(1, n + 1)
    ]


# ------------------------------------------------------- 1. normalisation

def test_normalize_item_has_the_common_shape():
    sig = ingestion.normalize_item(
        "hackernews",
        title="  <b>Big  news</b> &amp; stuff ",
        url="https://example.com/a",
        summary="<p>hello <i>world</i></p>",
        score="42",
        rank=3,
        raw={"id": 1},
    )
    assert set(sig) == set(ingestion.SIGNAL_KEYS)
    assert sig["source"] == "hackernews"
    assert sig["title"] == "Big news & stuff"          # html stripped + unescaped
    assert sig["summary"] == "hello world"
    assert sig["score"] == 42 and sig["rank"] == 3
    assert sig["url"] == "https://example.com/a"
    assert sig["raw"] == {"id": 1}
    # fetched_at is a real ISO-8601 UTC timestamp
    assert sig["fetched_at"].endswith("Z") and "T" in sig["fetched_at"]
    # id is a stable 16-char hex hash of source|url|title
    assert len(sig["id"]) == 16 and int(sig["id"], 16) >= 0


def test_stable_id_is_deterministic_and_source_sensitive():
    a = ingestion.normalize_item("s1", title="T", url="https://x/y")
    b = ingestion.normalize_item("s1", title="T", url="https://x/y")
    c = ingestion.normalize_item("s2", title="T", url="https://x/y")
    d = ingestion.normalize_item("s1", title="T2", url="https://x/y")
    assert a["id"] == b["id"]
    assert a["id"] != c["id"] and a["id"] != d["id"]


def test_coerce_signal_accepts_loose_dicts():
    sig = ingestion.coerce_signal("rss/x", {"title": "Loose", "link": "https://e/1"})
    assert set(sig) == set(ingestion.SIGNAL_KEYS)
    assert sig["source"] == "rss/x" and sig["title"] == "Loose"


def test_rss_parser_normalises_real_feed_xml(monkeypatch):
    xml = b"""<?xml version="1.0"?><rss version="2.0"><channel>
      <item><title>Feed story one</title><link>https://feed.example/1</link>
            <description>&lt;p&gt;body one&lt;/p&gt;</description></item>
      <item><title>Feed story two</title><link>https://feed.example/2</link>
            <description>body two</description></item>
    </channel></rss>"""
    monkeypatch.setattr(ingestion, "http_get", lambda url, **kw: xml)
    items = ingestion.fetch_rss("rss/test", "https://feed.example/rss", 10)
    assert len(items) == 2
    assert items[0]["title"] == "Feed story one"
    assert items[0]["url"] == "https://feed.example/1"
    assert items[0]["summary"] == "body one"
    assert items[0]["rank"] == 1 and items[1]["rank"] == 2
    assert all(set(i) == set(ingestion.SIGNAL_KEYS) for i in items)


def test_atom_parser_works(monkeypatch):
    xml = b"""<?xml version="1.0"?><feed xmlns="http://www.w3.org/2005/Atom">
      <entry><title>Atom one</title><link href="https://atom.example/1"/>
             <summary>atom body</summary></entry>
    </feed>"""
    monkeypatch.setattr(ingestion, "http_get", lambda url, **kw: xml)
    items = ingestion.fetch_rss("rss/atom", "https://atom.example/feed", 5)
    assert len(items) == 1
    assert items[0]["title"] == "Atom one"
    assert items[0]["url"] == "https://atom.example/1"


def test_hackernews_fetch_normalises_items(monkeypatch):
    payloads = {
        "https://hacker-news.firebaseio.com/v0/topstories.json": b"[1, 2]",
        "https://hacker-news.firebaseio.com/v0/item/1.json": (
            b'{"id":1,"type":"story","title":"HN one","url":"https://hn.example/1",'
            b'"score":10,"by":"a","descendants":3}'
        ),
        "https://hacker-news.firebaseio.com/v0/item/2.json": (
            b'{"id":2,"type":"story","title":"HN two","score":5,"by":"b","descendants":1}'
        ),
    }
    monkeypatch.setattr(ingestion, "http_get", lambda url, **kw: payloads[url])
    items = ingestion.fetch_hackernews(2)
    assert [i["title"] for i in items] == ["HN one", "HN two"]
    assert items[0]["source"] == "hackernews" and items[0]["score"] == 10
    # a story with no url falls back to its HN discussion permalink
    assert items[1]["url"] == "https://news.ycombinator.com/item?id=2"


# --------------------------------------------------------------- 2. dedupe

def test_run_ingest_dedupes_by_stable_id_across_runs():
    src = fake_source(items=sample_items(3))
    first = ingestion.run_ingest([src], limit_per_source=10, trigger="test")
    assert first["fetched_total"] == 3 and first["new_total"] == 3
    assert first["counts"]["total"] == 3

    second = ingestion.run_ingest([src], limit_per_source=10, trigger="test")
    assert second["fetched_total"] == 3
    assert second["new_total"] == 0, "re-running must not create duplicates"
    assert second["counts"]["total"] == 3

    # and the DB really holds 3 rows, not 6
    conn = connect()
    try:
        assert conn.execute("SELECT COUNT(*) AS n FROM signals").fetchone()["n"] == 3
    finally:
        conn.close()


def test_duplicate_ids_inside_one_run_are_collapsed():
    dupes = sample_items(2) + sample_items(2)  # same two signals twice
    run = ingestion.run_ingest([fake_source(items=dupes)], trigger="test")
    assert run["fetched_total"] == 2
    assert run["new_total"] == 2


# ------------------------------------------------- 3. graceful source failure

def test_failing_source_does_not_abort_the_run_and_is_logged(monkeypatch):
    good = fake_source("fake/good", items=sample_items(2, "fake/good"))
    bad = fake_source("fake/bad", boom=OSError("connection refused"))

    run = ingestion.run_ingest([good, bad], trigger="test")

    # the run completed and kept the good source's signals
    assert run["fetched_total"] == 2
    assert run["new_total"] == 2
    assert run["counts"]["total"] == 2
    assert [s["source"] for s in run["sources"]] == ["fake/good", "fake/bad"]
    assert run["sources"][0]["ok"] is True
    assert run["sources"][1]["ok"] is False
    assert run["errors"] and run["errors"][0]["source"] == "fake/bad"
    assert "connection refused" in run["errors"][0]["error"]

    # the failure is in the audit note, honestly
    assert "failed" in run["note"] and "fake/bad" in run["note"]
    assert "REAL FETCH" in run["note"] and "STUB" not in run["note"]

    # ... and in the hash chain
    events = service.list_events(limit=50, kind="ingest_run")
    assert events, "the run must append an audit event"
    ev = events[0]
    assert ev["actor"] == "IngestionLayer"
    assert ev["data"]["errors"][0]["source"] == "fake/bad"
    assert ev["data"]["real_fetch"] is True
    assert service.chain_status()["ok"] is True


def test_http_error_is_reported_with_status(monkeypatch):
    import urllib.error

    def boom(url, **kw):
        raise urllib.error.HTTPError(url, 403, "Blocked", None, None)

    monkeypatch.setattr(ingestion, "http_get", boom)
    run = ingestion.run_ingest([{"name": "reddit/test", "kind": "json",
                                 "fetch": lambda limit: ingestion.fetch_reddit("test", limit)}],
                               trigger="test")
    assert run["new_total"] == 0
    assert "HTTP 403 Blocked" in run["errors"][0]["error"]
    assert "No signals were stored" in run["note"]


def test_all_sources_failing_stores_nothing_and_says_so():
    run = ingestion.run_ingest(
        [fake_source("a", boom=RuntimeError("nope")), fake_source("b", boom=RuntimeError("nope"))],
        trigger="test",
    )
    assert run["fetched_total"] == 0 and run["new_total"] == 0
    assert run["counts"]["total"] == 0
    assert "nothing was fabricated" in run["note"]
    assert ingestion.grouped_signals() == {}
    assert ingestion.list_signals() == []


def test_ingest_does_not_touch_jobs_or_break_the_chain():
    job = service.create_job("keep me", "pytest", {"k": "v"}, registry=REGISTRY)
    ingestion.run_ingest([fake_source(items=sample_items(2))], trigger="test")
    assert service.get_job(job["id"])["title"] == "keep me"
    assert service.chain_status()["ok"] is True


# ------------------------------------- 4. registered as the INGESTED handler

def test_component_is_registered_as_ingested_handler():
    intake = REGISTRY.get_intake(sm.INGESTED)
    assert intake is not None
    assert intake.name == "IngestionLayer"
    assert intake.handles_state == sm.INGESTED
    assert intake.intake is True
    assert callable(intake.handler)
    # the stub is gone
    assert REGISTRY.get("IngestionStub") is None
    # and it is described as real work, not a stub
    desc = next(c for c in REGISTRY.describe() if c["name"] == "IngestionLayer")
    assert "REAL" in desc["description"] and "STUB" not in desc["description"]


def test_handler_without_fetch_flag_does_not_hit_the_network(monkeypatch):
    def explode(*a, **kw):
        raise AssertionError("no network call expected for a plain job")

    monkeypatch.setattr(ingestion, "http_get", explode)
    job = service.create_job("plain job", "pytest", {"k": "v"}, registry=REGISTRY)
    assert job["state"] == sm.INGESTED
    events = service.list_events(limit=50, job_id=job["id"])
    invoked = [e for e in events if e["kind"] == "component_invoked"]
    assert invoked and invoked[0]["actor"] == "IngestionLayer"
    assert "no fetch requested" in invoked[0]["note"]
    assert not invoked[0]["note"].startswith("STUB")


def test_handler_with_fetch_flag_runs_a_real_fetch(monkeypatch):
    monkeypatch.setattr(ingestion, "SOURCES", [fake_source(items=sample_items(2))])
    job = service.create_job("fetch job", "pytest", {"fetch": True}, registry=REGISTRY)
    assert job["state"] == sm.INGESTED
    assert job["payload"]["_ingestion"]["fetch_performed"] is True
    assert job["payload"]["_ingestion"]["new_total"] == 2
    invoked = [e for e in service.list_events(limit=50, job_id=job["id"])
               if e["kind"] == "component_invoked"]
    assert invoked[0]["note"].startswith("REAL INGESTION")
    assert ingestion.signal_counts()["total"] == 2


# --------------------------------------------------------------- 5. HTTP UI

@pytest.fixture
def client():
    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_senses_route_shows_honest_empty_state(client):
    r = client.get("/senses")
    assert r.status_code == 200
    html = r.get_data(as_text=True)
    assert "Senses" in html and "Fetch now" in html
    assert "No signals stored yet" in html
    assert "Cache-Control" in r.headers


def test_senses_route_lists_real_signals_grouped_by_source(client):
    ingestion.run_ingest(
        [fake_source("fake/one", items=sample_items(2, "fake/one")),
         fake_source("fake/two", items=sample_items(1, "fake/two"))],
        trigger="test",
    )
    r = client.get("/senses")
    assert r.status_code == 200
    html = r.get_data(as_text=True)
    assert "fake/one" in html and "fake/two" in html
    assert "Real headline 1" in html
    assert "https://example.invalid/story/1" in html
    assert "REAL FETCH" in html


def test_post_ingest_endpoint_runs_a_fetch(client, monkeypatch):
    monkeypatch.setattr(ingestion, "SOURCES", [fake_source(items=sample_items(2))])
    r = client.post("/ingest", json={"limit": 5})
    assert r.status_code == 200
    body = r.get_json()
    assert body["new_total"] == 2 and body["fetched_total"] == 2
    assert body["event_id"] is not None
    assert client.get("/signals").get_json()["count"] == 2


def test_ui_fetch_button_redirects_to_senses(client, monkeypatch):
    monkeypatch.setattr(ingestion, "SOURCES", [fake_source(items=sample_items(1))])
    r = client.post("/ui/senses/fetch")
    assert r.status_code == 302
    assert "/senses" in r.headers["Location"]
    assert ingestion.signal_counts()["total"] == 1


def test_dashboard_still_renders_and_links_senses(client):
    r = client.get("/")
    assert r.status_code == 200
    html = r.get_data(as_text=True)
    assert "JARVIS Orchestrator" in html
    assert 'href="/senses"' in html


def test_chain_still_verifies_after_ingest_runs(client):
    ingestion.run_ingest([fake_source(items=sample_items(2))], trigger="test")
    ingestion.run_ingest([fake_source("bad", boom=RuntimeError("x"))], trigger="test")
    conn = connect()
    try:
        assert verify_chain(conn)["ok"] is True
    finally:
        conn.close()
