"""Phase 2 (28 Oct): retries on read-only nodes, one clear fallback per node,
and one retry for the model / search calls on ai_service's shared client."""
import httpx
import pytest

import services.ai_service as ai_service
import services.erp_client as erp_client
import services.hr_graph as hg
from langgraph.graph import StateGraph, START, END
from schema.agent import HRState


class _Writer(list):
    def __call__(self, e):
        self.append(e)


# ── with_fallback ────────────────────────────────────────────────────────────

async def test_a_failing_node_closes_the_turn_with_one_clear_reply():
    async def _boom(state, writer):
        raise ValueError("bug")
    w = _Writer()
    out = await hg.with_fallback("attendance_node", _boom)({"intent": "attendance", "usage_events": []}, w)
    done = [e for e in w if e["type"] == "done"]
    assert len(done) == 1
    assert done[0]["message"] == hg.NODE_FAILURE_MESSAGE
    assert done[0]["failure_stage"] == "attendance_node"
    assert out["error"] == "node_failed"
    assert "Helix AI" in hg.NODE_FAILURE_MESSAGE


async def test_a_transient_error_on_a_read_node_is_raised_for_the_retry():
    async def _drop(state, writer):
        raise httpx.ConnectError("refused")
    with pytest.raises(httpx.ConnectError):
        await hg.with_fallback("attendance_node", _drop)({"usage_events": []}, _Writer())


async def test_a_transient_error_on_a_write_node_is_never_retried():
    async def _drop(state, writer):
        raise erp_client.ErpApiTimeout("slow")
    w = _Writer()
    out = await hg.with_fallback("leave_action_node", _drop)({"usage_events": []}, w)
    assert out["response_text"] == hg.NODE_FAILURE_MESSAGE


async def test_a_node_without_a_writer_parameter_still_works():
    async def _ok(state):
        return {"response_text": "fine"}
    assert (await hg.with_fallback("clarify_node", _ok)({}, _Writer()))["response_text"] == "fine"


@pytest.mark.parametrize("exc, transient", [
    (httpx.ConnectError("x"), True), (httpx.PoolTimeout("x"), True), (erp_client.ErpApiTimeout("x"), True),
    (httpx.ReadTimeout("x"), False), (erp_client.ErpApiUnauthorized("x", status_code=401), False),
    (ValueError("x"), False)])
def test_what_counts_as_transient(exc, transient):
    assert hg._is_transient(exc) is transient


# ── the RetryPolicy inside a real graph ─────────────────────────────────────

def _graph(name, node):
    g = StateGraph(HRState)
    hg._add_node(g, name, node)
    g.add_edge(START, name)
    g.add_edge(name, END)
    return g.compile()


async def test_a_read_node_is_retried_once_and_succeeds():
    calls = []

    async def _flaky(state, writer):
        calls.append(1)
        if len(calls) == 1:
            raise httpx.ConnectError("refused")
        writer({"type": "done", "message": "ok"})
        return {"response_text": "ok"}
    events = [e async for e in _graph("attendance_node", _flaky).astream(
        {"query": "q", "usage_events": []}, stream_mode="custom")]
    assert len(calls) == 2
    assert events[-1]["message"] == "ok"


async def test_a_write_node_runs_once_and_falls_back():
    calls = []

    async def _write(state, writer):
        calls.append(1)
        raise httpx.ConnectError("refused")
    events = [e async for e in _graph("leave_action_node", _write).astream(
        {"query": "q", "usage_events": []}, stream_mode="custom")]
    assert len(calls) == 1
    assert events[-1]["message"] == hg.NODE_FAILURE_MESSAGE


def test_every_write_node_is_on_the_no_retry_list():
    for name in ("leave_action_node", "leave_approval_node", "regularisation_approval_node",
                 "regularisation_cancel_node", "regularisation_eligibility_node", "regularisation_node"):
        assert name in hg._WRITE_NODES


def test_the_compiled_graph_still_has_every_node():
    assert "classify_node" in hg.hr_graph.get_graph().nodes
    assert "leave_action_node" in hg.hr_graph.get_graph().nodes


# ── one retry on the shared model client ────────────────────────────────────

class _Resp:
    def __init__(self, status, headers=None):
        self.status_code = status
        self.headers = headers or {}


@pytest.fixture
def no_sleep(monkeypatch):
    async def _instant(_):
        return None
    monkeypatch.setattr(ai_service.asyncio, "sleep", _instant)


async def test_a_503_is_retried_once(monkeypatch, no_sleep):
    answers = iter([_Resp(503), _Resp(200)])
    calls = []

    async def _post(url, *a, **k):
        calls.append(url)
        return next(answers)
    monkeypatch.setattr(ai_service, "_raw_post", _post)
    resp = await ai_service._post_with_one_retry("https://race/x", json={})
    assert resp.status_code == 200 and len(calls) == 2


async def test_a_dropped_connection_is_retried_once(monkeypatch, no_sleep):
    calls = []

    async def _post(url, *a, **k):
        calls.append(url)
        if len(calls) == 1:
            raise httpx.ConnectError("refused")
        return _Resp(200)
    monkeypatch.setattr(ai_service, "_raw_post", _post)
    assert (await ai_service._post_with_one_retry("u")).status_code == 200


@pytest.mark.parametrize("status", [400, 401, 404, 422])
async def test_a_4xx_is_not_retried(monkeypatch, no_sleep, status):
    calls = []

    async def _post(url, *a, **k):
        calls.append(url)
        return _Resp(status)
    monkeypatch.setattr(ai_service, "_raw_post", _post)
    assert (await ai_service._post_with_one_retry("u")).status_code == status
    assert len(calls) == 1


async def test_a_read_timeout_is_not_retried(monkeypatch, no_sleep):
    calls = []

    async def _post(url, *a, **k):
        calls.append(url)
        raise httpx.ReadTimeout("slow")
    monkeypatch.setattr(ai_service, "_raw_post", _post)
    with pytest.raises(httpx.ReadTimeout):
        await ai_service._post_with_one_retry("u")
    assert len(calls) == 1


async def test_a_second_failure_is_returned_not_looped(monkeypatch, no_sleep):
    calls = []

    async def _post(url, *a, **k):
        calls.append(url)
        return _Resp(429)
    monkeypatch.setattr(ai_service, "_raw_post", _post)
    assert (await ai_service._post_with_one_retry("u")).status_code == 429
    assert len(calls) == 2


# ── one retry on the race answer stream, only before anything is sent ───────

import contextlib  # noqa: E402


class _StreamResp:
    def __init__(self, status, lines=(), fail_after=None):
        self.status_code = status
        self._lines, self._fail_after = list(lines), fail_after

    def raise_for_status(self):
        if self.status_code >= 400:
            raise httpx.HTTPStatusError("x", request=httpx.Request("POST", "u"),
                                        response=httpx.Response(self.status_code))

    async def aiter_lines(self):
        for i, line in enumerate(self._lines):
            if self._fail_after is not None and i == self._fail_after:
                raise httpx.RemoteProtocolError("dropped")
            yield line


def _chunk(text):
    return 'data: {"choices": [{"delta": {"content": "%s"}}]}' % text


def _fake_stream(monkeypatch, *responses):
    calls = []
    it = iter(responses)

    @contextlib.asynccontextmanager
    async def _stream(method, url, **kwargs):
        calls.append(url)
        r = next(it)
        if isinstance(r, Exception):
            raise r
        yield r
    monkeypatch.setattr(ai_service._http, "stream", _stream)
    monkeypatch.setattr(ai_service, "RACE_API_KEY", "k")
    return calls


async def _collect(gen):
    return "".join([e["content"] async for e in gen if e["type"] == "chunk"])


async def test_a_429_before_the_answer_is_retried(monkeypatch, no_sleep):
    calls = _fake_stream(monkeypatch, _StreamResp(429), _StreamResp(200, [_chunk("Hi"), "data: [DONE]"]))
    assert await _collect(ai_service._call_race_stream([{"role": "user", "content": "x"}])) == "Hi"
    assert len(calls) == 2


async def test_a_refused_connection_before_the_answer_is_retried(monkeypatch, no_sleep):
    calls = _fake_stream(monkeypatch, httpx.ConnectError("refused"), _StreamResp(200, [_chunk("Hi")]))
    assert await _collect(ai_service._call_race_stream([{"role": "user", "content": "x"}])) == "Hi"
    assert len(calls) == 2


async def test_a_drop_after_text_was_sent_is_not_retried(monkeypatch, no_sleep):
    calls = _fake_stream(monkeypatch, _StreamResp(200, [_chunk("Half"), _chunk("rest")], fail_after=1),
                         _StreamResp(200, [_chunk("Again")]))
    with pytest.raises(httpx.RemoteProtocolError):
        await _collect(ai_service._call_race_stream([{"role": "user", "content": "x"}]))
    assert len(calls) == 1


async def test_a_second_failure_on_the_stream_is_raised(monkeypatch, no_sleep):
    _fake_stream(monkeypatch, _StreamResp(503), _StreamResp(503))
    with pytest.raises(httpx.HTTPStatusError):
        await _collect(ai_service._call_race_stream([{"role": "user", "content": "x"}]))


@pytest.mark.parametrize("status", [400, 401, 422])
async def test_a_4xx_on_the_stream_is_not_retried(monkeypatch, no_sleep, status):
    calls = _fake_stream(monkeypatch, _StreamResp(status), _StreamResp(200, [_chunk("Hi")]))
    with pytest.raises(httpx.HTTPStatusError):
        await _collect(ai_service._call_race_stream([{"role": "user", "content": "x"}]))
    assert len(calls) == 1
