"""Tests para docker_container_running."""

from __future__ import annotations

import os
import shutil
import subprocess
import sys
from unittest.mock import patch

import pytest

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", ".."))

from python.functions.infra.docker_container_running import docker_container_running


def _make_completed(stdout: str, returncode: int = 0) -> subprocess.CompletedProcess:
    return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr="")


def test_running_true():
    with patch("subprocess.run", return_value=_make_completed("true\n", 0)):
        assert docker_container_running("anything") is True


def test_running_false_when_state_false():
    with patch("subprocess.run", return_value=_make_completed("false\n", 0)):
        assert docker_container_running("stopped_container") is False


def test_running_false_when_inspect_fails():
    # docker inspect retorna != 0 cuando el contenedor no existe
    with patch("subprocess.run", return_value=_make_completed("", 1)):
        assert docker_container_running("nope") is False


def test_running_false_when_docker_missing():
    with patch("subprocess.run", side_effect=FileNotFoundError):
        assert docker_container_running("any") is False


def test_running_false_on_timeout():
    with patch("subprocess.run", side_effect=subprocess.TimeoutExpired(cmd="docker", timeout=5.0)):
        assert docker_container_running("any") is False


def test_running_strips_and_lowercases():
    # docker a veces emite con trailing whitespace; aceptamos "True\n" y "TRUE"
    for stdout in ("True\n", "TRUE", " true "):
        with patch("subprocess.run", return_value=_make_completed(stdout, 0)):
            assert docker_container_running("c") is True


def test_running_integration_real_docker():
    """Si docker está disponible, comprueba con un contenedor inexistente y devuelve False."""
    if not shutil.which("docker"):
        pytest.skip("docker no disponible en el PATH")
    assert docker_container_running("__definitely_does_not_exist_xyz__") is False
