"""Offline tests for the added public senses sources."""
import gzip
import json

from orchestrator import ingestion
from orchestrator import senses_sources as senses


def _json_bytes(value):
    return json.dumps(value).encode("utf-8")


def test_source_registry_has_public_sources():
    """The keyless public sources the senses layer must expose.

    Superset check, not equality — adding a source must not fail this test,
    but removing one of these must.
    """
    from orchestrator import senses_sources as _ss

    names = {s["name"] for s in _ss.SENSES_SOURCES}
    expected = {"mastodon", "gdelt", "github", "stackexchange", "arxiv"}
    missing = expected - names
    assert not missing, "missing public sources: %s" % sorted(missing)
    for source in _ss.SENSES_SOURCES:
        assert callable(source.get("fetch")), source.get("name")


def test_youtube_sources_require_configured_channel_ids(monkeypatch):
    monkeypatch.setenv("JARVIS_YOUTUBE_CHANNELS", "UCabc, UCdef")
    names = {source["name"] for source in senses.senses_sources()}
    assert "youtube/UCabc" in names
    assert "youtube/UCdef" in names


def test_json_reader_rejects_html(monkeypatch):
    monkeypatch.setattr(ingestion, "http_get", lambda *args, **kwargs: b"<html>blocked</html>")
    try:
        senses._get_json("https://example.invalid")
    except ValueError as exc:
        assert "HTML" in str(exc)
    else:
        raise AssertionError("HTML response was accepted")


def test_json_reader_handles_gzip(monkeypatch):
    body = gzip.compress(_json_bytes({"items": []}))
    monkeypatch.setattr(ingestion, "http_get", lambda *args, **kwargs: body)
    assert senses._get_json("https://example.invalid") == {"items": []}


def test_bluesky_fetch_normalizes_posts(monkeypatch):
    payload = {
        "posts": [
            {
                "uri": "at://did:plc:abc/app.bsky.feed.post/post1",
                "record": {"text": "A useful post", "createdAt": "2026-11-24T12:00:00Z"},
                "author": {"handle": "example.bsky.social"},
                "likeCount": 3,
            }
        ]
    }
    monkeypatch.setattr(ingestion, "http_get", lambda *args, **kwargs: _json_bytes(payload))
    items = senses.fetch_bluesky(5)
    assert len(items) == 1
    assert "A useful post" in str(items[0])
    assert "bsky.app" in str(items[0])


def test_gdelt_fetch_normalizes_articles(monkeypatch):
    payload = {"articles": [{"title": "Local business news", "url": "https://news.example/story"}]}
    monkeypatch.setattr(ingestion, "http_get", lambda *args, **kwargs: _json_bytes(payload))
    items = senses.fetch_gdelt(5)
    assert len(items) == 1
    assert "Local business news" in str(items[0])


def test_github_fetch_normalizes_repositories(monkeypatch):
    payload = {
        "items": [
            {
                "full_name": "owner/project",
                "html_url": "https://github.com/owner/project",
                "description": "Automation project",
                "stargazers_count": 7,
                "owner": {"login": "owner"},
            }
        ]
    }
    monkeypatch.setattr(ingestion, "http_get", lambda *args, **kwargs: _json_bytes(payload))
    items = senses.fetch_github(5)
    assert len(items) == 1
    assert "owner/project" in str(items[0])


def test_stackexchange_fetch_normalizes_questions(monkeypatch):
    payload = {
        "items": [
            {
                "title": "How do I automate this?",
                "link": "https://stackoverflow.com/questions/1",
                "score": 2,
                "answer_count": 1,
                "owner": {"display_name": "Example"},
            }
        ]
    }
    monkeypatch.setattr(ingestion, "http_get", lambda *args, **kwargs: _json_bytes(payload))
    items = senses.fetch_stackexchange(5)
    assert len(items) == 1
    assert "How do I automate this?" in str(items[0])


def test_mastodon_tries_the_next_instance_on_failure(monkeypatch):
    calls = []

    def fake_get(url, **kwargs):
        calls.append(url)
        if len(calls) == 1:
            raise OSError("first instance unavailable")
        return _json_bytes([])

    monkeypatch.setattr(ingestion, "http_get", fake_get)
    assert senses.fetch_mastodon(5) == []
    assert len(calls) == 2
    assert "fosstodon.org" in calls[1]


def test_youtube_uses_existing_rss_fetcher(monkeypatch):
    called = []
    monkeypatch.setattr(
        ingestion,
        "fetch_rss",
        lambda source, url, limit: called.append((source, url, limit)) or [],
    )
    assert senses.fetch_youtube("UCexample", 4) == []
    assert called[0][0] == "youtube/UCexample"
    assert "channel_id=UCexample" in called[0][1]
    assert called[0][2] == 4
