#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""端到端测试安全测试执行（模拟前端从 Cases.vue 执行）"""
import sys
import os
import time
import requests

BASE = "http://127.0.0.1:8001"

# 1. 创建执行（模拟前端 executionApi.create）
print("=== 1. 创建执行 ===")
resp = requests.post(f"{BASE}/api/executions", json={
    "case_ids": ["sec_2_8_1", "sec_2_8_2", "sec_2_8_3"],
    "name": "安全测试端到端验证",
})
print(f"创建状态码: {resp.status_code}")
exec_data = resp.json()
exec_id = exec_data.get("id")
print(f"执行ID: {exec_id}")
print(f"case_type: {exec_data.get('case_type')}")

if not exec_id:
    print("❌ 创建失败:", exec_data)
    sys.exit(1)

# 2. 触发执行（模拟前端 executionApi.run）
print("\n=== 2. 触发执行 ===")
resp = requests.post(f"{BASE}/api/executions/{exec_id}/run")
print(f"触发状态码: {resp.status_code}")
print(f"触发响应: {resp.text[:200]}")

# 3. 轮询等待完成
print("\n=== 3. 等待执行完成 ===")
for i in range(30):
    time.sleep(2)
    resp = requests.get(f"{BASE}/api/executions/{exec_id}/results")
    if resp.status_code == 200:
        data = resp.json()
        results = data.get("items", [])
        done = [r for r in results if r.get("status") in ("passed", "failed", "error", "skipped")]
        print(f"  轮询 {i+1}: {len(done)}/{len(results)} 完成")
        if len(done) == len(results) and results:
            print("\n=== 4. 执行结果 ===")
            for r in results:
                status = r.get("status")
                err = r.get("error_message") or ""
                print(f"  {r.get('case_name')}: {status} | {err[:80]}")
            break
    # 检查执行记录状态
    resp2 = requests.get(f"{BASE}/api/executions?skip=0&limit=1&case_type=security")
    if resp2.status_code == 200:
        items = resp2.json().get("items", [])
        if items:
            e = items[0]
            if e.get("status") in ("completed", "failed"):
                print(f"\n执行状态: {e.get('status')}, 通过: {e.get('passed')}, 失败: {e.get('failed')}")
else:
    print("⚠️ 30秒内未完成，检查后端日志")
