"""
Module: test_command
Description: Test runner command

Implements:
    - docs/cli/reference.md#huitzo-test
"""

import subprocess
from typing import Optional

import typer
from rich.console import Console

console = Console()


def test(
    coverage: bool = typer.Option(False, "--coverage", help="Generate coverage report"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
    parallel: bool = typer.Option(False, "--parallel", "-p", help="Run tests in parallel"),
    filter_pattern: Optional[str] = typer.Option(
        None, "--filter", "-k", help="Filter tests by pattern"
    ),
) -> None:
    """Run pack tests using pytest.

    Options:
    - --coverage: Generate coverage report (requires pytest-cov)
    - --verbose: Verbose test output
    - --parallel: Run tests in parallel (requires pytest-xdist)
    - --filter: Filter tests by pattern (pytest -k syntax)
    """
    cmd = ["pytest", "tests/"]

    if verbose:
        cmd.append("-v")

    if coverage:
        cmd.extend(["--cov=src", "--cov-report=term-missing"])

    if parallel:
        cmd.extend(["-n", "auto"])

    if filter_pattern:
        cmd.extend(["-k", filter_pattern])

    try:
        result = subprocess.run(cmd, check=False)
        if result.returncode != 0:
            raise typer.Exit(result.returncode)
    except FileNotFoundError:
        console.print("[red]❌ pytest not found. Install with: pip install pytest[/red]")
        raise typer.Exit(1)
