"""Find executable path for commands."""

from __future__ import annotations

import argparse
import logging
import os
import platform
import subprocess

is_windows = platform.system() == "Windows"
ext = ".exe" if is_windows else ""

logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)


def find_executable(name: str, *, fuzzy: bool) -> tuple[str, str | None]:
    """Find executable path for commands cross-platform.

    Returns:
        Tuple[str, Optional[str]]: Command name and path.
    """
    try:
        # Select command based on system
        match_name = name if not fuzzy else f"*{name}*{ext}"
        cmd = ["where" if is_windows else "which", match_name]

        # Run command and capture output
        result = subprocess.run(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL,
            text=True,
            check=True,
        )

        # Handle Windows multiple results case
        paths = result.stdout.strip().split("\n")
    except (subprocess.CalledProcessError, FileNotFoundError):
        # Check direct executable path on UNIX systems
        if not is_windows and os.access(f"/usr/bin/{name}", os.X_OK):
            return name, f"/usr/bin/{name}"
        return name, None
    else:
        return (name, paths[0]) if is_windows else (name, result.stdout.strip())


def main() -> None:
    parser = argparse.ArgumentParser(description="Find executable path for commands.")
    parser.add_argument("commands", type=str, nargs="+", help="Commands to query")
    parser.add_argument("-f", "--fuzzy", action="store_true", help="Enable fuzzy matching")
    parser.add_argument("-q", "--quiet", action="store_true", help="Only print paths, no status symbols")

    args = parser.parse_args()

    found_count = 0
    fuzzy = args.fuzzy
    quiet = args.quiet

    for command in args.commands:
        name, path = find_executable(command, fuzzy=fuzzy)
        if path:
            found_count += 1
            if quiet:
                logger.info(path)
            else:
                logger.info(f"✓ {name} -> {path}")
        else:
            if not quiet:
                logger.info(f"✗ {name} -> not found")

    if not quiet and len(args.commands) > 1:
        logger.info(f"\nFound {found_count}/{len(args.commands)} commands")
