#!/usr/bin/env python
"""
BaoLife Test Runner

Wrapper around pytest with project-specific configuration for running
the BaoLife test suite.
"""
import sys
import os
import argparse
import subprocess
from pathlib import Path


def setup_test_environment():
    """Set up environment variables for testing."""
    os.environ['BAOLIFE_TEST_MODE'] = 'true'
    os.environ['USE_MOCK_OPENAI'] = 'true'
    print("✓ Test environment configured")


def check_dependencies():
    """Check if required test dependencies are installed."""
    try:
        import pytest
        import pytest_asyncio
        import pytest_mock
        import pytest_cov
        print("✓ All test dependencies found")
        return True
    except ImportError as e:
        print(f"✗ Missing test dependency: {e}")
        print("\nInstall test dependencies with:")
        print("  pip install -r ws/requirements-dev.txt")
        return False


def run_pytest(args: list) -> int:
    """
    Run pytest with the given arguments.

    Args:
        args: List of arguments to pass to pytest

    Returns:
        Exit code from pytest
    """
    cmd = ['python', '-m', 'pytest'] + args
    print(f"\nRunning: {' '.join(cmd)}\n")
    result = subprocess.run(cmd, cwd=Path(__file__).parent)
    return result.returncode


def main():
    """Main entry point for test runner."""
    parser = argparse.ArgumentParser(
        description='Run BaoLife test suite',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python run_tests.py                    # Run all tests
  python run_tests.py --unit             # Run unit tests only
  python run_tests.py --integration      # Run integration tests only
  python run_tests.py --coverage         # Run with coverage report
  python run_tests.py --verbose          # Run with verbose output
  python run_tests.py --fast             # Run without coverage (faster)
  python run_tests.py -k test_events     # Run tests matching pattern
        """
    )

    parser.add_argument(
        '--unit',
        action='store_true',
        help='Run unit tests only'
    )
    parser.add_argument(
        '--integration',
        action='store_true',
        help='Run integration tests only'
    )
    parser.add_argument(
        '--coverage',
        action='store_true',
        help='Generate coverage report'
    )
    parser.add_argument(
        '--verbose', '-v',
        action='store_true',
        help='Verbose output'
    )
    parser.add_argument(
        '--fast',
        action='store_true',
        help='Run without coverage (faster)'
    )
    parser.add_argument(
        '-k',
        metavar='PATTERN',
        help='Run tests matching pattern'
    )
    parser.add_argument(
        '--pdb',
        action='store_true',
        help='Drop into debugger on failures'
    )
    parser.add_argument(
        '--markers',
        action='store_true',
        help='Show available test markers'
    )
    parser.add_argument(
        'pytest_args',
        nargs='*',
        help='Additional arguments to pass to pytest'
    )

    args = parser.parse_args()

    # Setup environment
    setup_test_environment()

    # Check dependencies
    if not check_dependencies():
        return 1

    # Build pytest arguments
    pytest_args = []

    # Test selection
    if args.unit:
        pytest_args.append('tests/unit')
    elif args.integration:
        pytest_args.append('tests/integration')
    else:
        pytest_args.append('tests')

    # Coverage
    if args.coverage or (not args.fast and not args.unit):
        pytest_args.extend([
            '--cov=.',
            '--cov-report=term-missing',
            '--cov-report=html:coverage_html',
            '--cov-config=.coveragerc'
        ])

    # Verbosity
    if args.verbose:
        pytest_args.append('-v')
    else:
        pytest_args.append('-q')

    # Pattern matching
    if args.k:
        pytest_args.extend(['-k', args.k])

    # Debugger
    if args.pdb:
        pytest_args.append('--pdb')

    # Show markers
    if args.markers:
        pytest_args.append('--markers')

    # Additional arguments
    pytest_args.extend(args.pytest_args)

    # Run pytest
    exit_code = run_pytest(pytest_args)

    # Summary
    if exit_code == 0:
        print("\n✓ All tests passed!")
        if args.coverage or (not args.fast and not args.unit):
            print("\nCoverage report generated in coverage_html/index.html")
    else:
        print(f"\n✗ Tests failed with exit code {exit_code}")

    return exit_code


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