#!/usr/bin/env python3
"""
run_tests.py

Simple test runner script for the automated testing system.
Provides easy commands to run different types of tests.
"""

import sys
import subprocess
import os
import shutil


def get_python_executable():
    """Get the appropriate Python executable (python3 on Linux, python on Windows)."""
    # First try the same executable that's running this script
    current_python = sys.executable
    if current_python and shutil.which(current_python):
        return current_python
    
    # Try python3 first (common on Linux)
    if shutil.which('python3'):
        return 'python3'
    
    # Fall back to python
    if shutil.which('python'):
        return 'python'
    
    # Last resort - assume python3
    return 'python3'


def check_pytest_available(python_exe):
    """Check if pytest is available and provide helpful error message if not."""
    try:
        result = subprocess.run([python_exe, '-m', 'pytest', '--version'], 
                              capture_output=True, text=True, timeout=10)
        return result.returncode == 0
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return False


def run_command(cmd):
    """Run a command and return the exit code."""
    print(f"Running: {' '.join(cmd)}")
    result = subprocess.run(cmd)
    return result.returncode


def main():
    if len(sys.argv) < 2:
        print("Usage: python3 run_tests.py <command>")
        print("       python run_tests.py <command>  (Windows)")
        print("Commands:")
        print("  all          - Run all tests")
        print("  functional   - Run all functional tests")
        print("  security     - Run all security tests")
        print("  integration  - Run all integration tests")
        print("  auth         - Run authentication tests")
        print("  cameras      - Run camera management tests")
        print("  images       - Run image management tests")
        print("  map          - Run map functionality tests")
        print("  admin        - Run admin panel tests")
        print("  coverage     - Run all tests with coverage report")
        print("  html         - Run all tests with HTML report")
        return 1

    command = sys.argv[1].lower()
    
    # Use the appropriate Python executable for the current system
    python_exe = get_python_executable()
    
    # Check if pytest is available
    if not check_pytest_available(python_exe):
        print("❌ Error: pytest is not installed!")
        print("")
        print("To install test dependencies:")
        print("  Linux/Mac:")
        print("    pip3 install -r config/requirements-test.txt")
        print("    # OR run: ./scripts/setup_test_environment.sh")
        print("")
        print("  Windows:")
        print("    pip install -r config/requirements-test.txt")
        print("")
        print("Required packages: pytest, pytest-html, pytest-cov, pytest-flask, bcrypt")
        return 1
    
    base_cmd = [python_exe, "-m", "pytest", "-v"]
    
    if command == "all":
        cmd = base_cmd + ["tests/"]
    elif command == "functional":
        cmd = base_cmd + ["tests/functional/"]
    elif command == "security":
        cmd = base_cmd + ["tests/security/"]
    elif command == "integration":
        cmd = base_cmd + ["tests/integration/"]
    elif command == "auth":
        cmd = base_cmd + ["tests/functional/test_auth.py", "-m", "auth"]
    elif command == "cameras":
        cmd = base_cmd + ["tests/functional/test_cameras.py", "-m", "cameras"]
    elif command == "images":
        cmd = base_cmd + ["tests/functional/test_images.py", "-m", "images"]
    elif command == "map":
        cmd = base_cmd + ["tests/functional/test_map.py", "-m", "map"]
    elif command == "admin":
        cmd = base_cmd + ["tests/functional/test_admin.py", "-m", "admin"]
    elif command == "coverage":
        cmd = base_cmd + ["tests/", "--cov=app_modules", "--cov-report=html:reports/coverage", "--cov-report=term-missing"]
    elif command == "html":
        cmd = base_cmd + ["tests/", "--html=reports/test_report.html", "--self-contained-html"]
    else:
        print(f"Unknown command: {command}")
        return 1
    
    return run_command(cmd)


if __name__ == "__main__":
    sys.exit(main())