import app.agents.graph as graph_module
from app.agents.orchestration.result_merge import merge_task_results
from app.agents.schemas.task import AgentTask
from app.agents.state import AgentRole, initial_state


def test_merge_task_results_marks_conflict_for_distinct_completed_summaries():
    report = merge_task_results(
        [
            {
                "task_id": "task-1",
                "status": "completed",
                "summary": "结论 A",
                "evidence": [{"type": "source"}],
                "owner_agent_id": "librarian",
            },
            {
                "task_id": "task-2",
                "status": "completed",
                "summary": "结论 B",
                "evidence": [{"type": "analysis"}, {"type": "analysis"}],
                "owner_agent_id": "analyst",
            },
        ]
    )

    assert report.status == "conflicted"
    assert "multiple_distinct_completed_summaries" in report.conflict_flags
    assert report.resolution_strategy == "rank_by_evidence_count"
    assert report.resolved_summary == "结论 B"


def test_verify_collaboration_results_persists_merge_and_verification_reports():
    state = initial_state("u1", "c1")
    tasks = [
        AgentTask(
            task_id="task-1",
            title="收集证据",
            role=AgentRole.LIBRARIAN.value,
            owner_agent_id=AgentRole.LIBRARIAN.value,
            goal="检索资料",
            expected_evidence=[{"type": "evidence"}],
        ),
        AgentTask(
            task_id="task-2",
            title="给出分析",
            role=AgentRole.ANALYST.value,
            owner_agent_id=AgentRole.ANALYST.value,
            goal="分析风险",
            expected_evidence=[{"type": "analysis"}],
        ),
    ]

    graph_module._verify_collaboration_results(
        state,
        tasks,
        task_results=[
            {
                "task_id": "task-1",
                "status": "completed",
                "summary": "证据显示风险中等",
                "evidence": [{"type": "evidence"}],
                "owner_agent_id": AgentRole.LIBRARIAN.value,
            },
            {
                "task_id": "task-2",
                "status": "completed",
                "summary": "证据显示风险中等",
                "evidence": [{"type": "analysis"}],
                "owner_agent_id": AgentRole.ANALYST.value,
            },
        ],
    )

    assert state["merge_report"] is not None
    assert state["merge_report"]["status"] == "merged"
    assert state["verification_report"] is not None
    assert state["verification_report"]["status"] == "passed"
    event_types = [item["event_type"] for item in state["event_trace"]]
    assert "agent.merge.completed" in event_types
    assert "agent.verify.completed" in event_types


def test_serial_fallback_response_is_used_when_merge_report_requires_fallback():
    state = initial_state("u1", "c1")
    tasks = [
        AgentTask(
            task_id="task-1",
            title="收集证据",
            role=AgentRole.LIBRARIAN.value,
            owner_agent_id=AgentRole.LIBRARIAN.value,
            goal="检索资料",
            expected_evidence=[{"type": "evidence"}],
        ),
        AgentTask(
            task_id="task-2",
            title="给出分析",
            role=AgentRole.ANALYST.value,
            owner_agent_id=AgentRole.ANALYST.value,
            goal="分析风险",
            expected_evidence=[{"type": "analysis"}],
        ),
    ]
    state["task_results"] = [
        {
            "task_id": "task-1",
            "status": "completed",
            "summary": "已确认可用证据",
            "evidence": [{"type": "evidence"}],
            "owner_agent_id": AgentRole.LIBRARIAN.value,
        },
        {
            "task_id": "task-2",
            "status": "failed",
            "summary": "分析失败",
            "evidence": [{"type": "analysis"}],
            "owner_agent_id": AgentRole.ANALYST.value,
        },
    ]
    state["final_response"] = "原始协作汇总"

    graph_module._verify_collaboration_results(state, tasks, state["task_results"])
    if state["verification_status"] == "failed" and state["merge_report"]["fallback_used"]:
        state["final_response"] = graph_module._build_serial_fallback_response(
            "先查资料再分析",
            state["task_results"],
            state["merge_report"],
        )
        graph_module._append_event_trace(
            state,
            "agent.rollback.triggered",
            payload={"layer": "collaboration_runtime", "reason": "merge_fallback_used"},
            severity="warning",
        )

    assert "切回保守收敛路径" in state["final_response"]
    event_types = [item["event_type"] for item in state["event_trace"]]
    assert "agent.rollback.triggered" in event_types
