#!/usr/bin/env python3
"""E2E: 工具辅助导入 (Import)"""
from helper import *

def run():
    header("工具辅助导入")
    pid = create_project(unique_name("导入测试"))

    # 1. 导入新节点
    resp = post(f"/api/v1/projects/{pid}/import", {
        "nodes": [
            {"label": "10.0.0.1", "node_type": "host", "content": "## 主机发现\n网关机器"},
            {"label": "10.0.0.2", "node_type": "service", "content": "## 内网机器\nWeb 服务器"}
        ],
        "edges": [
            {"source_label": "10.0.0.1", "target_label": "10.0.0.2", "label": "HTTP 访问"}
        ]
    })
    j = assert_ok(resp)
    assert j["nodes_created"] == 2, f"nodes_created should be 2, got {j['nodes_created']}"
    assert j["nodes_skipped"] == 0, f"nodes_skipped should be 0, got {j['nodes_skipped']}"
    assert j["edges_created"] == 1, f"edges_created should be 1, got {j['edges_created']}"
    assert j["edges_skipped"] == 0, f"edges_skipped should be 0, got {j['edges_skipped']}"
    ok("新节点导入成功")

    # 2. 去重测试 —— 同样内容再导入
    resp = post(f"/api/v1/projects/{pid}/import", {
        "nodes": [{"label": "10.0.0.1", "node_type": "host", "content": "## 重复导入"}],
        "edges": []
    })
    j = assert_ok(resp)
    assert j["nodes_created"] == 0, f"重复导入应 created=0, got {j['nodes_created']}"
    assert j["nodes_skipped"] == 1, f"重复导入应 skipped=1, got {j['nodes_skipped']}"
    ok("去重跳过已有节点")

    # 3. 混合导入 —— 部分新部分旧
    resp = post(f"/api/v1/projects/{pid}/import", {
        "nodes": [
            {"label": "10.0.0.1", "node_type": "host", "content": "旧"},
            {"label": "10.0.0.3", "node_type": "service", "content": "新"}
        ],
        "edges": []
    })
    j = assert_ok(resp)
    assert j["nodes_created"] == 1, f"新节点应 created=1, got {j['nodes_created']}"
    assert j["nodes_skipped"] == 1, f"旧节点应 skipped=1, got {j['nodes_skipped']}"
    ok("混合导入正确区分新旧")

    # 4. 导入带默认类型
    resp = post(f"/api/v1/projects/{pid}/import", {
        "nodes": [{"label": "无类型节点", "content": "## 无类型"}],
        "edges": []
    })
    j = assert_ok(resp)
    assert j["nodes_created"] == 1, f"无类型节点应创建, got {j['nodes_created']}"
    ok("无 node_type 也能导入（默认类型）")

    # 5. 空导入
    resp = post(f"/api/v1/projects/{pid}/import", {"nodes": [], "edges": []})
    j = assert_ok(resp)
    assert j["nodes_created"] == 0
    assert j["nodes_skipped"] == 0
    ok("空导入返回全0")

    # 6. 非法 JSON
    resp = requests.post(f"{BASE}/api/v1/projects/{pid}/import", data="not json", headers={"Content-Type": "application/json"}, timeout=10)
    assert resp.status_code == 400, f"非法 JSON 应 400, got {resp.status_code}"
    ok("非法 JSON 返回 400")

    delete_project(pid)
    summary()

if __name__ == "__main__":
    run()
