import asyncio
from types import SimpleNamespace

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


class DummyCtx:
    messages = []
    usage = None


def test_handoff_to_jira_returns_chanakya_answer(monkeypatch):
    async def fake_run(*args, **kwargs):
        return SimpleNamespace(output=JiraAnswer(summary="jira", key_items=[], risks=[], blockers=[]))

    monkeypatch.setattr("chanakya.jira.agent.run", fake_run)
    out = asyncio.run(handoffs.handoff_to_jira(DummyCtx(), "query"))
    assert out.mode == "jira"
    assert out.jira is not None


def test_handoff_to_salesforce_returns_chanakya_answer(monkeypatch):
    async def fake_run(*args, **kwargs):
        return SimpleNamespace(output=SalesforceAnswer(summary="sf", pipeline_signals=[], risks=[], revenue_notes=[]))

    monkeypatch.setattr("chanakya.salesforce.agent.run", fake_run)
    out = asyncio.run(handoffs.handoff_to_salesforce(DummyCtx(), "query"))
    assert out.mode == "salesforce"
    assert out.salesforce is not None


def test_handoff_to_both_merges_sections(monkeypatch):
    a1 = ChanakyaAnswer(mode="jira", jira=JiraAnswer(summary="j", key_items=[], risks=[], blockers=[]), final_text="j")
    a2 = ChanakyaAnswer(mode="salesforce", salesforce=SalesforceAnswer(summary="s", pipeline_signals=[], risks=[], revenue_notes=[]), final_text="s")
    monkeypatch.setattr(handoffs, "handoff_to_jira", lambda *_: asyncio.sleep(0, result=a1))
    monkeypatch.setattr(handoffs, "handoff_to_salesforce", lambda *_: asyncio.sleep(0, result=a2))
    out = asyncio.run(handoffs.handoff_to_both(DummyCtx(), "query"))
    assert out.mode == "both"
    assert "## Jira Findings" in out.final_text and "## Salesforce Findings" in out.final_text
