import shlex
import subprocess
from typing import List, Sequence, Optional, Tuple

#
# Construct the smartctl/btrfs/...  commands safely.
#

def build_smartctl_scan(device: str) -> List[str]:
    """
    Get disks available:
    """
    return shlex.split(f"smartctl --scan {shlex.quote(device)}")

def build_sudo_smartctl_a(device: str) -> List[str]:
    """
    Legacy way to retrieve info
    """
    return shlex.split(f"sudo smartctl -a {shlex.quote(device)}")

def build_sudo_smartctl_l_error(device: str) -> List[str]:
    """
    retrieve errors
    """
    return shlex.split(f"sudo smartctl -l error {shlex.quote(device)}")

def build_sudo_smartctl_x(device: str) -> List[str]:
    """
    SMART overall-health self-assessment test result:
    test in progress
    completed test in power_on_hours
    """
    return shlex.split(f"sudo smartctl -x {shlex.quote(device)}")

def build_sudo_smartctl_t_short(device: str) -> List[str]:
    """
    run short test
    """
    return shlex.split(f"sudo smartctl -t short {shlex.quote(device)}")

def build_sudo_smartctl_l_selftest(device: str) -> List[str]:
    """
    show self-test log (subset of -x )
    """
    return shlex.split(f"sudo smartctl -l selftest {shlex.quote(device)}")

def build_sudo_btrfs_filesystem_show() -> List[str]:
    """
     list all partitions with btrfs; last info in every paragraph
     is: "path /dev/nvme0n1p1"
    """
    return shlex.split(f"sudo btrfs filesystem show")

def build_sudo_btrfs_scrub_status(mountpoint: str) -> List[str]:
    """
     Show if scrub is running. Show errors.
    """
    return shlex.split(f"sudo btrfs scrub status {shlex.quote(mountpoint)}")

def build_sudo_btrfs_scrub_start(mountpoint: str) -> List[str]:
    """
     Start scrub if it is not already running.
    """
    return shlex.split(f"sudo btrfs scrub start {shlex.quote(mountpoint)}")

def build_sudo_btrfs_device_stats(device: str) -> List[str]:
    """
     Show if scrub is running. Show errors.
    """
    return shlex.split(f"sudo btrfs device stats {shlex.quote(device)}")

def build_snapper_list_configs() -> List[str]:
    """
    Snapper operated btrfs mountpoints:
    Drop 1st 3 lines, the rest is rows with:  configname | mountpoint
    """
    return shlex.split(f"snapper list-configs")

def build_sudo_snapper_c_list(configname: str) -> List[str]:
    """
    list all snapshots
    """
    return shlex.split(f"sudo snapper -c {shlex.quote(configname)} list")



def run_command(command: Sequence[str], timeout: int = 10) -> Tuple[int, str]:
    """Execute a command and return (returncode, output).

    Args:
        command: List of command arguments
        timeout: Maximum time to wait for command completion (seconds)

    Returns:
        Tuple of (returncode, combined_stdout_stderr)
    """
    try:
        result = subprocess.run(
            list(command),
            capture_output=True,
            text=True,
            timeout=timeout,
            check=False,
        )
        return result.returncode, result.stdout + result.stderr
    except subprocess.TimeoutExpired:
        return 1, f"Command timed out after {timeout} seconds"
    except Exception as e:
        return 1, str(e)
