import logging
import subprocess
from collections.abc import Sequence
from dataclasses import dataclass

logger = logging.getLogger(__name__)


@dataclass
class RunCmdResult:
    stdout: str
    stderr: str
    status: int

    @property
    def success(self) -> bool:
        return self.status == 0


def run_cmd_t(cmd: str) -> tuple[str, str]:
    result = run_cmd(cmd)
    return result.stdout, result.stderr


def run_cmd(cmd: str | Sequence[str]) -> RunCmdResult:
    logger.debug("running command: %s", cmd)
    run = subprocess.run(
        cmd, shell=isinstance(cmd, str), capture_output=True, text=True, check=False
    )
    logger.debug(
        "result of command:\n%s and errors:\n%s and return code: %s",
        run.stdout,
        run.stderr,
        run.returncode,
    )
    return RunCmdResult(run.stdout, run.stderr, run.returncode)


def stress_cpu(time: int) -> subprocess.Popen[bytes]:
    logger.info("stressing CPU for %s seconds", str(time))
    return subprocess.Popen(["bash", "-c", "stress-ng -c $(nproc) -t " + str(time) + "s"])


def execute_cmds(commands: list[str]) -> bool:
    return all(run_cmd(cmd).success for cmd in commands)
