"""Tests for output.py JSON envelope helpers."""

import json
import sys
from io import StringIO

import pytest

from corpo.output import error, success


def test_success_envelope(capsys):
    success({"foo": "bar"})
    out = capsys.readouterr().out
    parsed = json.loads(out)
    assert parsed == {"ok": True, "data": {"foo": "bar"}}


def test_success_nested(capsys):
    success({"items": [1, 2, 3], "count": 3})
    out = capsys.readouterr().out
    parsed = json.loads(out)
    assert parsed["ok"] is True
    assert parsed["data"]["count"] == 3


def test_error_envelope():
    with pytest.raises(SystemExit) as exc_info:
        error("something broke")
    assert exc_info.value.code == 1


def test_error_with_hint(capsys):
    with pytest.raises(SystemExit):
        error("bad input", hint="try --help")
    out = capsys.readouterr().out
    parsed = json.loads(out)
    assert parsed["ok"] is False
    assert parsed["error"] == "bad input"
    assert parsed["hint"] == "try --help"


def test_error_without_hint(capsys):
    with pytest.raises(SystemExit):
        error("fail")
    out = capsys.readouterr().out
    parsed = json.loads(out)
    assert "hint" not in parsed
