#!/usr/bin/env python3
"""
Run script for the sim-search API tests.

This script runs the API tests and provides a clear output of the test results.
"""

import os
import sys
import argparse
import subprocess
import time

def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(description="Run the sim-search API tests")
    parser.add_argument(
        "--test-file",
        type=str,
        default="tests/test_api.py",
        help="Test file to run",
    )
    parser.add_argument(
        "--verbose",
        action="store_true",
        help="Enable verbose output",
    )
    parser.add_argument(
        "--xvs",
        action="store_true",
        help="Run tests with -xvs flag (exit on first failure, verbose, show output)",
    )
    parser.add_argument(
        "--coverage",
        action="store_true",
        help="Run tests with coverage",
    )
    return parser.parse_args()

def run_tests(args):
    """Run the tests."""
    print(f"Running tests from {args.test_file}...")
    
    # Build the command
    command = ["pytest"]
    
    if args.xvs:
        command.append("-xvs")
    elif args.verbose:
        command.append("-v")
    
    if args.coverage:
        command.extend(["--cov=app", "--cov-report=term", "--cov-report=html"])
    
    command.append(args.test_file)
    
    # Run the tests
    start_time = time.time()
    result = subprocess.run(command)
    end_time = time.time()
    
    # Print the results
    if result.returncode == 0:
        print(f"\n✅ Tests passed in {end_time - start_time:.2f} seconds")
    else:
        print(f"\n❌ Tests failed in {end_time - start_time:.2f} seconds")
    
    return result.returncode

def main():
    """Main function."""
    args = parse_args()
    
    # Check if the test file exists
    if not os.path.exists(args.test_file):
        print(f"Error: Test file {args.test_file} does not exist")
        return 1
    
    # Run the tests
    return run_tests(args)

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