#!/usr/bin/env python3
"""E2E: 攻击路径分析 (Analysis)"""
from helper import *

def run():
    header("攻击路径分析")
    pid = create_project(unique_name("分析测试"))

    # 构建一条简单攻击路径
    n1 = create_node(pid, "入口点: 外网 Web", "entry_point")
    n2 = create_node(pid, "漏洞: SQL注入", "vulnerability", after=n1["id"], edge_label="扫描发现")
    n3 = create_node(pid, "利用: 获取数据", "attack_step", after=n2["id"], edge_label="利用漏洞")
    create_node(pid, "目标: 数据库服务器", "objective", after=n3["id"], edge_label="横向移动")

    # 1. 分析（不带 AI）
    resp = get(f"/api/v1/projects/{pid}/analysis")
    j = assert_ok(resp)
    assert "attack_paths" in j, f"分析应有 attack_paths, got keys: {list(j.keys())}"
    assert len(j["attack_paths"]) > 0, "应有至少一条攻击路径"
    ok("分析返回攻击路径")

    # 2. 检查路径结构
    path = j["attack_paths"][0]
    assert "nodes" in path, f"路径应有 nodes 字段, got keys: {list(path.keys())}"
    nodes_in_path = [p["label"] for p in path["nodes"]]
    assert "入口点: 外网 Web" in nodes_in_path, f"路径应含入口点, got {nodes_in_path}"
    ok("路径包含入口点和目标")

    # 3. 未利用漏洞
    assert "unexploited_vulns" in j, f"分析应有 unexploited_vulns"
    ok(f"未利用漏洞: {len(j['unexploited_vulns'])} 个")

    # 4. 下一步建议
    assert "next_steps" in j, f"分析应有 next_steps"
    ok(f"下一步建议: {len(j['next_steps'])} 条")

    # 5. 跨分支连接
    assert "cross_connections" in j, f"分析应有 cross_connections"
    ok(f"跨分支连接: {len(j['cross_connections'])} 条")

    # 6. 死路
    assert "dead_ends" in j, f"分析应有 dead_ends"

    # 7. 空项目分析
    pid2 = create_project(unique_name("空项目分析"))
    resp = get(f"/api/v1/projects/{pid2}/analysis")
    j = assert_ok(resp)
    assert len(j["attack_paths"]) == 0, "空项目应无攻击路径"
    ok("空项目分析返回空路径")

    delete_project(pid)
    delete_project(pid2)
    summary()

if __name__ == "__main__":
    run()
