import json

from sunwaee.modules.shell.tools import shell, TOOLS as SHELL_TOOLS


def test_shell_run_success(ws):
    data = json.loads(shell(command="echo hello", comment="Print hello"))
    assert data["ok"] is True
    assert data["data"]["exit_code"] == 0
    assert "hello" in data["data"]["stdout"]
    assert data["data"]["comment"] == "Print hello"
    assert data["data"]["command"] == "echo hello"


def test_shell_run_stderr(ws):
    data = json.loads(shell(command="echo error >&2", comment="Write to stderr"))
    assert data["ok"] is True
    assert "error" in data["data"]["stderr"]


def test_shell_run_nonzero_exit(ws):
    data = json.loads(shell(command="exit 1", comment="Exit with error"))
    assert data["ok"] is True
    assert data["data"]["exit_code"] == 1


def test_shell_run_multiline_output(ws):
    data = json.loads(shell(command="printf 'a\\nb\\nc\\n'", comment="Multi-line output"))
    assert data["ok"] is True
    lines = data["data"]["stdout"].strip().splitlines()
    assert lines == ["a", "b", "c"]


def test_shell_run_invalid_command(ws):
    data = json.loads(shell(command="nonexistent_command_xyz", comment="Invalid command"))
    assert data["ok"] is True
    assert data["data"]["exit_code"] != 0
    assert data["data"]["stderr"] != ""


def test_shell_run_git_snapshot_fields(ws):
    data = json.loads(shell(command="echo x", comment="Check git fields"))
    assert data["ok"] is True
    assert "git_diff" in data["data"]
    assert "git_status" in data["data"]


def test_shell_tools_registry():
    assert len(SHELL_TOOLS) == 1
    assert SHELL_TOOLS[0].name == "shell"
    assert SHELL_TOOLS[0].fn is not None
    props = SHELL_TOOLS[0].parameters["properties"]
    assert "command" in props
    assert "comment" in props
