import subprocess

import pytest


def test_compose_down_volumes_and_remove_orphans(monkeypatch, tmp_path):
    from armorer import docker_runner

    captured = {}

    def fake_run(cmd, **kwargs):
        captured["cmd"] = cmd
        captured["kwargs"] = kwargs
        return subprocess.CompletedProcess(cmd, 0, "ok", "")

    monkeypatch.setattr(docker_runner.subprocess, "run", fake_run)

    res = docker_runner.compose_down(cwd=tmp_path, volumes=True, remove_orphans=True, timeout=5)
    assert res.returncode == 0
    assert res.args[:3] == ["docker", "compose", "down"]
    assert "-v" in res.args
    assert "--remove-orphans" in res.args
    assert captured["kwargs"]["timeout"] == 5


def test_compose_up_timeout_returns_124(monkeypatch, tmp_path):
    from armorer import docker_runner

    def fake_run(cmd, **kwargs):
        raise subprocess.TimeoutExpired(cmd, timeout=kwargs.get("timeout"))

    monkeypatch.setattr(docker_runner.subprocess, "run", fake_run)

    res = docker_runner.compose_up(cwd=tmp_path, services=["svc"], timeout=7)
    assert res.returncode == 124
    assert "timeout" in (res.stderr or "").lower()


def test_compose_config_quiet(monkeypatch, tmp_path):
    from armorer import docker_runner

    captured = {}

    def fake_run(cmd, **kwargs):
        captured["cmd"] = cmd
        return subprocess.CompletedProcess(cmd, 0, "", "")

    monkeypatch.setattr(docker_runner.subprocess, "run", fake_run)

    docker_runner.compose_config(cwd=tmp_path, quiet=True)
    assert captured["cmd"] == ["docker", "compose", "config", "-q"]


def test_compose_exec_adds_T(monkeypatch, tmp_path):
    from armorer import docker_runner

    captured = {}

    def fake_run(cmd, **kwargs):
        captured["cmd"] = cmd
        return subprocess.CompletedProcess(cmd, 0, "", "")

    monkeypatch.setattr(docker_runner.subprocess, "run", fake_run)

    docker_runner.compose_exec(cwd=tmp_path, service="svc", exec_args=["echo", "hi"])
    assert captured["cmd"][:5] == ["docker", "compose", "exec", "-T", "svc"]

