"""Tests for orchestrator.runner — handlers, checks, and the run loop."""

import pytest

from orchestrator import runner


SPEC = {
    "bot_name": "test-bot",
    "steps": [
        {"action": "read_feeds", "reads": ["feed:x"], "writes": ["store:articles"]},
        {"action": "extract_claims", "reads": ["store:articles"], "writes": ["store:claims"]},
        {"action": "drop_uncited", "reads": ["store:claims"], "writes": ["store:claims_cited"]},
        {"action": "draft_brief", "reads": ["store:claims_cited"], "writes": ["store:drafts"]},
        {"action": "notify_owner", "reads": ["store:drafts"], "writes": ["store:approval_queue"]},
    ],
    "outputs": {"fields": {
        "brief_markdown": "string",
        "claims": "array",
        "dropped_uncited": "integer",
        "send_requires_human": "boolean",
    }},
    "verifier": {"checks": [
        {"id": "outputs_present"},
        {"id": "no_silent_green"},
        {"id": "citations_resolve"},
    ]},
}


def test_handlers_registered():
    for action in ("read_feeds", "extract_claims", "drop_uncited",
                   "draft_brief", "notify_owner"):
        assert action in runner.HANDLERS


def test_extract_claims_is_structural():
    store = {"articles": [{"title": "Headline", "url": "https://x.test/a"}]}
    runner._extract_claims({}, store, {})
    assert store["claims"] == [{
        "claim": "Headline",
        "source_url": "https://x.test/a",
        "published_at": "",
    }]


def test_drop_uncited_removes_bad_urls():
    store = {"claims": [
        {"claim": "good", "source_url": "https://x.test/a"},
        {"claim": "bad", "source_url": "not-a-url"},
    ]}
    runner._drop_uncited({}, store, {})
    assert len(store["claims_cited"]) == 1
    assert store["dropped_uncited"] == 1


def test_draft_brief_renders():
    store = {"claims_cited": [{"claim": "c", "source_url": "https://x.test/a"}],
             "dropped_uncited": 2}
    runner._draft_brief({}, store, {"bot_name": "b"})
    assert "https://x.test/a" in store["brief_markdown"]
    assert "Dropped uncited: 2" in store["brief_markdown"]


def test_notify_owner_never_sends():
    store = {"brief_markdown": "x"}
    runner._notify_owner({}, store, {"bot_name": "b"})
    assert store["send_requires_human"] is True
    assert store["approval_queue"][0]["requires_human"] is True


def test_check_outputs_present_fails_on_missing():
    ok, note = runner._check_outputs_present(SPEC, {"brief_markdown": "x"})
    assert ok is False
    assert "missing outputs" in note


def test_check_no_silent_green_fails_on_empty_brief():
    store = {"_steps_ran": ["a"] * 5}
    ok, note = runner._check_no_silent_green(SPEC, store)
    assert ok is False
    assert "no brief" in note


def test_check_citations_resolve_fails_on_bad_url():
    store = {"claims_cited": [{"claim": "c", "source_url": "ftp://x"}]}
    ok, note = runner._check_citations_resolve(SPEC, store)
    assert ok is False
    assert "resolvable" in note


def test_unimplemented_check_fails():
    spec = {"steps": [{"action": "read_feeds"}],
            "verifier": {"checks": [{"id": "does_not_exist"}]}}
    assert "does_not_exist" not in runner.CHECKS


def test_run_spec_unknown_bot_raises():
    with pytest.raises(runner.RunBlocked):
        runner.run_spec(999999)
