"""Tests for ! shell command runner."""

from __future__ import annotations

from pathlib import Path


from clients.terminal.tui.shell_runner import run_shell_command, MAX_OUTPUT_LINES


def test_run_simple_command() -> None:
    result = run_shell_command("!echo hello")
    assert result.returncode == 0
    assert "hello" in result.stdout
    assert result.stderr == ""


def test_run_with_stderr() -> None:
    result = run_shell_command("!echo error >&2")
    assert result.returncode == 0
    assert "error" in result.stderr


def test_run_failing_command() -> None:
    result = run_shell_command("!false")
    assert result.returncode == 1
    assert "✗" in result.summary()


def test_run_piped_command() -> None:
    result = run_shell_command("!echo hi | tr a-z A-Z")
    assert result.returncode == 0
    assert "HI" in result.stdout


def test_run_timeout() -> None:
    result = run_shell_command("!sleep 5", timeout=0.1)
    assert result.returncode == 124
    assert "timed out" in result.stderr


def test_empty_command() -> None:
    result = run_shell_command("!")
    assert result.returncode == 1


def test_truncate_long_output() -> None:
    result = run_shell_command(f"!seq 1 {MAX_OUTPUT_LINES + 50}")
    assert result.truncated is False
    assert "lines truncated" in result.stdout
    assert len(result.stdout.splitlines()) <= MAX_OUTPUT_LINES + 1


def test_run_in_cwd(tmp_path: Path) -> None:
    sub = tmp_path / "sub"
    sub.mkdir()
    (sub / "file.txt").write_text("data", encoding="utf-8")
    result = run_shell_command("!cat file.txt", cwd=sub)
    assert result.returncode == 0
    assert result.stdout.strip() == "data"
