"""Execute commands and capture output."""

from __future__ import annotations

import os
import subprocess
import tempfile


def run_command(command: str, timeout: int = 30) -> dict:
    """Run a bash command and return structured output.

    Redirects to temp files instead of pipes so backgrounded processes
    (commands with &) don't hang the parent.
    """
    out_fd, out_path = tempfile.mkstemp(suffix=".out")
    err_fd, err_path = tempfile.mkstemp(suffix=".err")
    try:
        result = subprocess.run(
            ["bash", "-c", command],
            stdout=out_fd,
            stderr=err_fd,
            timeout=timeout,
        )
        os.close(out_fd)
        os.close(err_fd)
        out_fd = err_fd = -1
        return {
            "command": command,
            "stdout": open(out_path).read(),
            "stderr": open(err_path).read(),
            "exit_code": result.returncode,
        }
    except subprocess.TimeoutExpired:
        if out_fd >= 0:
            os.close(out_fd)
        if err_fd >= 0:
            os.close(err_fd)
        return {
            "command": command,
            "stdout": open(out_path).read(),
            "stderr": open(err_path).read() + f"\nCommand timed out after {timeout}s",
            "exit_code": -1,
        }
    finally:
        os.unlink(out_path)
        os.unlink(err_path)
