import asyncio
from types import SimpleNamespace

import pytest
from pydantic_ai import ModelRetry

from chanakya import handoffs
from chanakya.schemas import ChanakyaFailure, ChanakyaAnswer, SalesforceAnswer


class DummyCtx:
    messages = []
    usage = None


def test_recoverable_failure_raises_modelretry(monkeypatch):
    async def fake_run(*args, **kwargs):
        return SimpleNamespace(output=ChanakyaFailure(reason="retry me", recoverable=True))

    monkeypatch.setattr("chanakya.jira.agent.run", fake_run)
    with pytest.raises(ModelRetry):
        asyncio.run(handoffs.handoff_to_jira(DummyCtx(), "query"))


def test_partial_failure_keeps_other_connector(monkeypatch):
    async def fail_jira(*args, **kwargs):
        raise RuntimeError("jira down")

    a2 = ChanakyaAnswer(mode="salesforce", salesforce=SalesforceAnswer(summary="s", pipeline_signals=[], risks=[], revenue_notes=[]), final_text="s")
    monkeypatch.setattr(handoffs, "handoff_to_jira", fail_jira)
    monkeypatch.setattr(handoffs, "handoff_to_salesforce", lambda *_: asyncio.sleep(0, result=a2))
    out = asyncio.run(handoffs.handoff_to_both(DummyCtx(), "query"))
    assert out.salesforce is not None
    assert "Partial failure" in out.final_text
