#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：create_and_run_semantic_verify.py
模块描述：创建「新建会议-语义化验证版」用例（去掉 finally 步骤）并触发真实执行

阶段 6 真实执行验证用：正式示范用例的 finally 清理端点（POST /api/meeting/query）
是 PRD 占位，5.44 走 MQTT 无 HTTP 端点，直接跑必失败并把主流程翻 failed。
本脚本复制 build_steps() 但弹出 finally 步骤，先验证 16 步主流程 UI 链路。

用法：python scripts/create_and_run_semantic_verify.py
输出：case_id + execution_id（随后轮询 /api/executions/{id}）

作者：czj
创建日期：2026-08-18
"""

import asyncio
import sys
import io
import os

import httpx

# 确保可从 scripts 目录 import 到 create_semantic_meeting_case
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from create_semantic_meeting_case import (  # noqa: E402
    BASE_URL,
    MEETING_MODULE_ID,
    CASE_PARAMETERS,
    DEFAULT_CONFIG,
    build_steps,
)

# 验证版用例名（与正式版区分，幂等先删后建）
VERIFY_CASE_NAME = "新建会议-语义化验证版（临时-无finally）"


def build_verify_steps() -> list:
    """复制正式版步骤，弹出 finally 清理步骤（order 17）"""
    steps = build_steps()
    assert steps[-1].get("run_on") == "finally", "最后一步应为 finally 清理步骤"
    verify_steps = steps[:-1]
    print(f"  验证版步骤数: {len(verify_steps)}（已剔除 finally 清理步骤）")
    return verify_steps


async def delete_existing(client: httpx.AsyncClient) -> None:
    r = await client.get(f"{BASE_URL}/api/cases", params={"limit": 100})
    if r.status_code == 200:
        items = r.json().get("items", [])
        for item in items:
            if item.get("name") == VERIFY_CASE_NAME:
                await client.delete(f"{BASE_URL}/api/cases/{item['id']}")
                print(f"  已删除旧验证版用例: {item['id']}")


async def main() -> None:
    async with httpx.AsyncClient(timeout=30) as client:
        await delete_existing(client)

        # 1. 创建验证版用例
        payload = {
            "module_id": MEETING_MODULE_ID,
            "name": VERIFY_CASE_NAME,
            "description": "阶段6真实执行验证版：与正式示范用例一致，剔除 finally 清理步骤，先验证16步主流程。",
            "priority": "high",
            "tags": ["语义化", "新建会议", "阶段6验证"],
            "steps": build_verify_steps(),
            "parameters": CASE_PARAMETERS,
            "config": DEFAULT_CONFIG,
        }
        r = await client.post(f"{BASE_URL}/api/cases", json=payload)
        if r.status_code != 201:
            print(f"用例创建失败: HTTP {r.status_code}\n{r.text[:800]}")
            return
        case = r.json()
        print(f"用例创建成功: {case['id']}")

        # 2. 触发执行
        r = await client.post(
            f"{BASE_URL}/api/executions",
            json={
                "case_ids": [case["id"]],
                "name": "语义化验证版-真实执行",
                "trigger_type": "manual",
                "trigger_by": "claude",
            },
        )
        if r.status_code != 201:
            print(f"执行创建失败: HTTP {r.status_code}\n{r.text[:800]}")
            return
        exec_data = r.json()
        print(f"执行创建成功: {exec_data['id']}")


if __name__ == "__main__":
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    asyncio.run(main())
