#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
清空测试数据脚本
"""

import sys
import asyncio
from pathlib import Path

# 添加项目路径
backend_dir = Path(__file__).parent.parent
sys.path.insert(0, str(backend_dir))

from sqlalchemy import text
from app.database import engine


async def clean_data():
    """清空所有测试数据"""
    print("开始清空测试数据...")

    async with engine.begin() as conn:
        # 按外键依赖顺序删除
        print("1. 删除依赖关系...")
        result = await conn.execute(text("DELETE FROM case_dependencies"))
        print(f"   删除了 {result.rowcount} 条依赖关系")

        print("2. 删除执行结果...")
        result = await conn.execute(text("DELETE FROM case_results"))
        print(f"   删除了 {result.rowcount} 条执行结果")

        print("3. 删除执行记录...")
        result = await conn.execute(text("DELETE FROM executions"))
        print(f"   删除了 {result.rowcount} 条执行记录")

        print("4. 删除测试用例...")
        result = await conn.execute(text("DELETE FROM test_cases"))
        print(f"   删除了 {result.rowcount} 条测试用例")

        print("5. 删除模块...")
        result = await conn.execute(text("DELETE FROM modules"))
        print(f"   删除了 {result.rowcount} 条模块")

    print("")
    print("验证清空结果...")

    # 验证清空结果
    async with engine.begin() as conn:
        result = await conn.execute(text("SELECT COUNT(*) FROM test_cases"))
        case_count = result.scalar()

        result = await conn.execute(text("SELECT COUNT(*) FROM modules"))
        module_count = result.scalar()

        result = await conn.execute(text("SELECT COUNT(*) FROM executions"))
        exec_count = result.scalar()

        result = await conn.execute(text("SELECT COUNT(*) FROM case_dependencies"))
        dep_count = result.scalar()

        print(f"  模块数: {module_count}")
        print(f"  用例数: {case_count}")
        print(f"  执行记录: {exec_count}")
        print(f"  依赖关系: {dep_count}")

    print("")
    print("✅ 数据清空完成!")


if __name__ == "__main__":
    asyncio.run(clean_data())