"""
Shell utilities for running external commands
"""

import subprocess
import tempfile
from pathlib import Path
from typing import List, Optional, Tuple

def run_command(cmd: List[str], input_data: Optional[str] = None, 
                timeout: int = 300) -> Tuple[bool, str, str]:
    """
    Run a shell command and return success, stdout, stderr
    
    Args:
        cmd: Command and arguments as list
        input_data: Optional stdin data
        timeout: Command timeout in seconds
        
    Returns:
        Tuple of (success, stdout, stderr)
    """
    try:
        result = subprocess.run(
            cmd,
            input=input_data,
            capture_output=True,
            text=True,
            timeout=timeout
        )
        
        return (
            result.returncode == 0,
            result.stdout.strip(),
            result.stderr.strip()
        )
        
    except subprocess.TimeoutExpired:
        return False, "", f"Command timed out after {timeout} seconds"
    except Exception as e:
        return False, "", str(e)

def run_with_input_file(cmd: List[str], input_data: str, 
                       timeout: int = 300) -> Tuple[bool, str, str]:
    """
    Run command with input data written to temporary file
    
    Args:
        cmd: Command and arguments as list  
        input_data: Data to write to temp file
        timeout: Command timeout in seconds
        
    Returns:
        Tuple of (success, stdout, stderr)
    """
    with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
        f.write(input_data)
        temp_file = f.name
    
    try:
        # Replace placeholder with actual temp file path
        cmd_with_file = [arg.replace('INPUT_FILE', temp_file) for arg in cmd]
        
        result = subprocess.run(
            cmd_with_file,
            capture_output=True,
            text=True,
            timeout=timeout
        )
        
        return (
            result.returncode == 0,
            result.stdout.strip(),
            result.stderr.strip()
        )
        
    except subprocess.TimeoutExpired:
        return False, "", f"Command timed out after {timeout} seconds"
    except Exception as e:
        return False, "", str(e)
    finally:
        # Clean up temp file
        Path(temp_file).unlink(missing_ok=True)