#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
一键运行所有测试脚本
"""

import sys
import subprocess
from pathlib import Path

def run_command(cmd, description):
    """运行命令并显示结果"""
    print("\n" + "=" * 80)
    print(f"{description}")
    print("=" * 80)
    print(f"命令: {cmd}\n")

    result = subprocess.run(
        cmd,
        shell=True,
        capture_output=True,
        text=True
    )

    # 显示输出
    if result.stdout:
        print(result.stdout)

    if result.returncode != 0 and result.stderr:
        print("错误信息:")
        print(result.stderr)

    return result.returncode

def main():
    print("\n" + "=" * 80)
    print("Questions MCP Server - 整体测试套件")
    print("=" * 80)

    tests = [
        {
            "cmd": "uv run python -m pytest tests/test_search_service.py tests/test_embedding_service.py tests/test_management_service.py -v --tb=short",
            "desc": "核心业务测试（搜索、Embedding、管理服务）",
            "critical": True
        },
        {
            "cmd": "uv run python verify_stage5.py",
            "desc": "阶段5功能验证（检索服务完整测试）",
            "critical": True
        },
        {
            "cmd": "uv run python -m pytest tests/test_database.py::TestSQLiteDAO -v",
            "desc": "SQLite数据库测试",
            "critical": True
        },
        {
            "cmd": "uv run python -m pytest tests/ -v --tb=line --ignore=tests/test_database.py",
            "desc": "所有测试（排除Windows文件锁问题）",
            "critical": False
        }
    ]

    results = []
    for test in tests:
        returncode = run_command(test["cmd"], test["desc"])
        results.append({
            "name": test["desc"],
            "code": returncode,
            "critical": test["critical"]
        })

    # 显示总结
    print("\n" + "=" * 80)
    print("测试结果总结")
    print("=" * 80)

    critical_passed = 0
    critical_total = 0
    all_passed = 0

    for result in results:
        status = "[OK] PASS" if result["code"] == 0 else "[FAIL]"
        criticality = "[关键]" if result["critical"] else "[可选]"

        print(f"{criticality} {status} - {result['name']}")

        if result["critical"]:
            critical_total += 1
            if result["code"] == 0:
                critical_passed += 1

        if result["code"] == 0:
            all_passed += 1

    print("\n" + "=" * 80)
    print(f"关键测试通过率: {critical_passed}/{critical_total}")

    if critical_passed == critical_total:
        print("所有关键测试通过！系统运行正常。")
        return 0
    else:
        print("部分关键测试失败，请检查上述错误信息。")
        return 1

if __name__ == "__main__":
    sys.exit(main())
