"""
Test command - Run automation tests.

This module provides functionality to run the test suite for an automation
using pytest with optional coverage reporting.
"""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

from rich.console import Console
from rich.panel import Panel

console = Console()


def run_tests(
    watch: bool = False,
    verbose: bool = False,
    coverage: bool = False,
    path: str | None = None,
) -> bool:
    """
    Run automation tests.

    Args:
        watch: Watch for file changes and re-run tests
        verbose: Show verbose output
        coverage: Generate coverage report
        path: Specific test path to run

    Returns:
        True if tests pass, False otherwise
    """
    # Check we're in an automation project
    if not _is_automation_project():
        console.print("[red]Error:[/red] Not in an automation project directory")
        return False

    # Check pytest is installed
    if not _check_pytest():
        console.print("[red]Error:[/red] pytest is not installed")
        console.print("[dim]Run: pip install pytest pytest-asyncio[/dim]")
        return False

    console.print(
        Panel.fit(
            "[bold]Running Automation Tests[/bold]",
            subtitle="Press Ctrl+C to cancel",
        )
    )
    console.print()

    # Build pytest command
    cmd = [sys.executable, "-m", "pytest"]

    # Add test path
    if path:
        cmd.append(path)
    else:
        # Look for tests directory
        tests_dir = Path.cwd() / "tests"
        if tests_dir.exists():
            cmd.append(str(tests_dir))

    # Add options
    if verbose:
        cmd.append("-v")
    else:
        cmd.append("-v")  # Always show some output

    if coverage:
        # Check pytest-cov is installed
        if not _check_pytest_cov():
            console.print("[yellow]Warning:[/yellow] pytest-cov not installed")
            console.print("[dim]Run: pip install pytest-cov[/dim]")
        else:
            cmd.extend(["--cov=.", "--cov-report=term-missing"])

    # Add asyncio mode
    cmd.append("--asyncio-mode=auto")

    # Add color output
    cmd.append("--color=yes")

    if watch:
        # Use pytest-watch if available
        if _check_pytest_watch():
            cmd = [sys.executable, "-m", "pytest_watch", "--"] + cmd[3:]
        else:
            console.print(
                "[yellow]Warning:[/yellow] pytest-watch not installed, "
                "running tests once"
            )
            console.print("[dim]Run: pip install pytest-watch[/dim]")

    try:
        # Run pytest
        result = subprocess.run(cmd, cwd=Path.cwd())
        return result.returncode == 0

    except KeyboardInterrupt:
        console.print("\n[yellow]Tests cancelled[/yellow]")
        return False
    except Exception as e:
        console.print(f"\n[red]Error running tests:[/red] {e}")
        return False


def _is_automation_project() -> bool:
    """Check if the current directory is an automation project."""
    cwd = Path.cwd()

    if (cwd / "automation.yaml").exists():
        return True
    if (cwd / "main.py").exists():
        return True

    return False


def _check_pytest() -> bool:
    """Check if pytest is installed."""
    try:
        import pytest  # noqa: F401

        return True
    except ImportError:
        return False


def _check_pytest_cov() -> bool:
    """Check if pytest-cov is installed."""
    try:
        import pytest_cov  # noqa: F401

        return True
    except ImportError:
        return False


def _check_pytest_watch() -> bool:
    """Check if pytest-watch is installed."""
    try:
        import pytest_watch  # noqa: F401

        return True
    except ImportError:
        return False
