from app.agents.orchestration.task_graph import build_bounded_task_graph
from app.agents.schemas.orchestration import RuntimeRequestContext, assess_parallel_worthiness, render_runtime_request_context_summary


def test_build_bounded_task_graph_creates_independent_nodes_and_merge_node():
    worthiness = assess_parallel_worthiness(
        "先查资料、再分析风险、再安排下周计划",
        retrospective_count=2,
        skill_count=1,
    )

    graph = build_bounded_task_graph(
        query_text="先查资料、再分析风险、再安排下周计划",
        parallel_worthiness=worthiness,
    )

    assert graph is not None
    assert len(graph.nodes) >= 2
    assert graph.entry_node_ids
    assert any(node.execution_mode == "parallel" for node in graph.nodes[:-1])
    assert graph.nodes[-1].role == "master"


def test_runtime_request_context_summary_renders_task_graph():
    worthiness = assess_parallel_worthiness(
        "先查资料、再分析风险、再安排下周计划",
        retrospective_count=1,
        skill_count=1,
    )
    task_graph = build_bounded_task_graph(
        query_text="先查资料、再分析风险、再安排下周计划",
        parallel_worthiness=worthiness,
    )
    context = RuntimeRequestContext(
        user_id="u1",
        session_id="c1",
        query_text="先查资料、再分析风险、再安排下周计划",
        parallel_worthiness=worthiness,
        task_graph=task_graph,
        recommended_runtime_mode="collaboration",
    )

    summary = render_runtime_request_context_summary(context)

    assert "任务图" in summary
    assert "max_parallelism" in summary


def test_runtime_request_context_summary_renders_assembly_metrics():
    context = RuntimeRequestContext(
        user_id="u1",
        session_id="c1",
        query_text="帮我分析一下资料",
        assembly_metrics={"total_ms": 12.3},
    )

    summary = render_runtime_request_context_summary(context)

    assert "上下文装配耗时" in summary
