#!/usr/bin/env python3
"""Speech test runner for the current API-based TTS/ASR stack."""

from __future__ import annotations

import argparse
import os
import subprocess
import sys
from pathlib import Path


def run_command(cmd: list[str], cwd: str | None = None) -> int:
    print(f"\n执行: {' '.join(cmd)}")
    print("-" * 70)
    return subprocess.run(cmd, cwd=cwd).returncode


def run_unit_tests(verbose: bool = False) -> int:
    cmd = ["pytest", "backend/tests/test_tts_asr.py"]
    if verbose:
        cmd.append("-v")
    return run_command(cmd)


def run_benchmark(extra_args: list[str] | None = None) -> int:
    cmd = ["python", "backend/tests/benchmark_tts_asr.py"]
    if extra_args:
        cmd.extend(extra_args)
    return run_command(cmd)


def run_all(verbose: bool = False) -> int:
    results = [
        ("单元测试", run_unit_tests(verbose=verbose)),
        ("基准测试", run_benchmark()),
    ]

    print("\n" + "=" * 70)
    print("测试结果汇总")
    print("=" * 70)
    passed = 0
    for name, code in results:
        ok = code == 0
        passed += int(ok)
        print(f"{name}: {'✓ 通过' if ok else '✗ 失败'}")
    print("-" * 70)
    print(f"总计: {passed}/{len(results)} 通过")
    return 0 if passed == len(results) else 1


def main() -> int:
    parser = argparse.ArgumentParser(description="当前 API 化 TTS/ASR 测试运行器")
    subparsers = parser.add_subparsers(dest="command", help="测试类型")

    unit_parser = subparsers.add_parser("unit", help="运行当前 TTS/ASR 单元测试")
    unit_parser.add_argument("-v", "--verbose", action="store_true", help="详细输出")

    benchmark_parser = subparsers.add_parser("benchmark", help="运行当前 TTS/ASR benchmark")
    benchmark_parser.add_argument("benchmark_args", nargs="*", help="透传给 benchmark_tts_asr.py")

    all_parser = subparsers.add_parser("all", help="运行当前 TTS/ASR 单元测试和 benchmark")
    all_parser.add_argument("-v", "--verbose", action="store_true", help="详细输出")

    args = parser.parse_args()
    project_root = Path(__file__).parent.parent.parent
    os.chdir(project_root)

    if args.command == "unit":
        return run_unit_tests(verbose=args.verbose)
    if args.command == "benchmark":
        return run_benchmark(extra_args=args.benchmark_args)
    if args.command == "all":
        return run_all(verbose=args.verbose)

    parser.print_help()
    return 0


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