from __future__ import annotations


def _create_chat(client, agent_id: str, node_id: str, ref: str) -> str:
    r = client.post(
        "/api/chats",
        json={
            "agent_id": agent_id,
            "node_id": node_id,
            "source": "web",
            "external_chat_ref": ref,
        },
    )
    assert r.status_code == 200, r.text
    return r.json()["chat"]["chat_id"]


def test_send_routes_to_noda1(sofiia_client, sofiia_module, monkeypatch):
    calls = []

    def _router_url(node_id: str) -> str:
        return {"NODA1": "http://noda1-router.test", "NODA2": "http://noda2-router.test"}.get(node_id, "")

    async def _fake_infer(base_url, agent_id, text, **kwargs):
        calls.append({"base_url": base_url, "agent_id": agent_id, "text": text})
        return {"response": "ok-n1", "backend": "fake", "model": "fake-model"}

    monkeypatch.setattr(sofiia_module, "get_router_url", _router_url)
    monkeypatch.setattr(sofiia_module, "infer", _fake_infer)

    cid = _create_chat(sofiia_client, "monitor", "NODA1", "route-n1")
    r = sofiia_client.post(f"/api/chats/{cid}/send", json={"text": "ping-n1"})
    assert r.status_code == 200, r.text
    body = r.json()
    assert body["accepted"] is True
    assert body["node_id"] == "NODA1"
    assert calls and calls[-1]["base_url"] == "http://noda1-router.test"


def test_send_routes_to_noda2(sofiia_client, sofiia_module, monkeypatch):
    calls = []

    def _router_url(node_id: str) -> str:
        return {"NODA1": "http://noda1-router.test", "NODA2": "http://noda2-router.test"}.get(node_id, "")

    async def _fake_infer(base_url, agent_id, text, **kwargs):
        calls.append({"base_url": base_url, "agent_id": agent_id, "text": text})
        return {"response": "ok-n2", "backend": "fake", "model": "fake-model"}

    monkeypatch.setattr(sofiia_module, "get_router_url", _router_url)
    monkeypatch.setattr(sofiia_module, "infer", _fake_infer)

    cid = _create_chat(sofiia_client, "sofiia", "NODA2", "route-n2")
    r = sofiia_client.post(f"/api/chats/{cid}/send", json={"text": "ping-n2"})
    assert r.status_code == 200, r.text
    body = r.json()
    assert body["accepted"] is True
    assert body["node_id"] == "NODA2"
    assert calls and calls[-1]["base_url"] == "http://noda2-router.test"

