"""Application & command execution — cross-platform."""

import subprocess
import platform
import shutil


def open_app(app, args=None):
    """Open an application by name. Cross-platform."""
    try:
        system = platform.system().lower()
        cmd_args = args or []

        if system == "darwin":
            # macOS: use 'open -a'
            subprocess.Popen(["open", "-a", app] + cmd_args)
        elif system == "windows":
            # Windows: use 'start'
            subprocess.Popen(["start", "", app] + cmd_args, shell=True)
        else:
            # Linux: try direct, then xdg-open
            app_path = shutil.which(app)
            if app_path:
                subprocess.Popen([app_path] + cmd_args)
            else:
                subprocess.Popen(["xdg-open", app] + cmd_args)

        return {"success": True, "app": app, "args": cmd_args}
    except Exception as e:
        return {"success": False, "error": str(e)}


def run_command(command, timeout=30):
    """Run a shell command and capture output."""
    try:
        result = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            timeout=timeout,
        )
        output = result.stdout[-5000:] if len(result.stdout) > 5000 else result.stdout
        stderr = result.stderr[-2000:] if len(result.stderr) > 2000 else result.stderr
        return {
            "success": result.returncode == 0,
            "exit_code": result.returncode,
            "stdout": output,
            "stderr": stderr,
        }
    except subprocess.TimeoutExpired:
        return {"success": False, "error": f"Command timed out after {timeout}s"}
    except Exception as e:
        return {"success": False, "error": str(e)}
