# standard
import json

# third party
import pytest

# custom
from sunwaee.core import output as out


def test_success_machine_caller_prints_json(monkeypatch, capsys):
    monkeypatch.setenv("SUNWAEE_CALLER", "api")
    out.success({"key": "value"})
    captured = capsys.readouterr()
    payload = json.loads(captured.out)
    assert payload == {"ok": True, "data": {"key": "value"}}


def test_success_machine_caller_list(monkeypatch, capsys):
    monkeypatch.setenv("SUNWAEE_CALLER", "api")
    out.success([1, 2, 3])
    captured = capsys.readouterr()
    assert json.loads(captured.out) == {"ok": True, "data": [1, 2, 3]}


def test_success_human_caller_calls_human_fn(monkeypatch):
    monkeypatch.setenv("SUNWAEE_CALLER", "human")
    called = []
    out.success({"x": 1}, human_fn=lambda: called.append(True))
    assert called == [True]


def test_success_human_caller_no_human_fn(monkeypatch, capsys):
    monkeypatch.setenv("SUNWAEE_CALLER", "human")
    out.success({"x": 1})
    captured = capsys.readouterr()
    assert captured.out == ""


def test_error_machine_caller_prints_json_and_exits(monkeypatch, capsys):
    monkeypatch.setenv("SUNWAEE_CALLER", "api")
    with pytest.raises(SystemExit) as exc:
        out.error("Not found", "NOT_FOUND")
    assert exc.value.code == 1
    captured = capsys.readouterr()
    payload = json.loads(captured.out)
    assert payload == {"ok": False, "error": "Not found", "code": "NOT_FOUND"}


def test_error_custom_exit_code(monkeypatch, capsys):
    monkeypatch.setenv("SUNWAEE_CALLER", "api")
    with pytest.raises(SystemExit) as exc:
        out.error("Bad input", "VALIDATION_ERROR", exit_code=2)
    assert exc.value.code == 2


def test_error_human_caller_exits(monkeypatch, capsys):
    monkeypatch.setenv("SUNWAEE_CALLER", "human")
    with pytest.raises(SystemExit) as exc:
        out.error("Something failed", "IO_ERROR")
    assert exc.value.code == 1


def test_info_human_caller_prints(monkeypatch, capsys):
    monkeypatch.setenv("SUNWAEE_CALLER", "human")
    out.info("Hello")
    captured = capsys.readouterr()
    assert "Hello" in captured.out


def test_info_machine_caller_silent(monkeypatch, capsys):
    monkeypatch.setenv("SUNWAEE_CALLER", "api")
    out.info("Hello")
    captured = capsys.readouterr()
    assert captured.out == ""
