#!/usr/bin/env python3
"""E2E: 证据附件 — 上传/列表/下载/删除"""
from helper import *
import tempfile
import os

header("Evidence")

pid = create_project(unique_name("E2E-证据"))
nid = create_node(pid, "目标节点", "host")["id"]

# ── Upload ──
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
    f.write("Hello from E2E test!\n")
    tmp_path = f.name

with open(tmp_path, "rb") as fh:
    r = post(f"/api/v1/projects/{pid}/nodes/{nid}/evidence",
             files={"file": ("test-evidence.txt", fh, "text/plain")})
ev = assert_ok(r)
stored = ev["stored_name"]
assert ev["original_name"] == "test-evidence.txt"
assert ev["file_size"] > 0
ok("upload evidence")

# ── List ──
files = assert_ok(get(f"/api/v1/projects/{pid}/nodes/{nid}/evidence"))
assert len(files) == 1
ok("list evidence (1 file)")

# ── Download ──
r = get(f"/api/v1/projects/{pid}/nodes/{nid}/evidence/{stored}")
assert r.status_code == 200
assert b"Hello from E2E test" in r.content
ok("download evidence content matches")

# ── Upload second file ──
with open(tmp_path, "rb") as fh:
    r2 = post(f"/api/v1/projects/{pid}/nodes/{nid}/evidence",
              files={"file": ("second.txt", fh, "text/plain")})
assert_ok(r2)
assert len(assert_ok(get(f"/api/v1/projects/{pid}/nodes/{nid}/evidence"))) == 2
ok("upload second evidence file")

# ── Delete ──
assert_ok(delete(f"/api/v1/projects/{pid}/nodes/{nid}/evidence/{stored}"))
assert len(assert_ok(get(f"/api/v1/projects/{pid}/nodes/{nid}/evidence"))) == 1
ok("delete evidence")

# ── Path traversal → 400 ──
assert_err(get(f"/api/v1/projects/{pid}/nodes/{nid}/evidence/..bad"), 400)
ok("reject path traversal")

# Cleanup
os.unlink(tmp_path)
delete_project(pid)

summary()
