"""Tests for pyos/exception_utils.py — try_make_lines, try_print_line."""

import pytest

from pyos.exception_utils import try_make_lines, try_print_line


# ===========================================================================
# try_make_lines
# ===========================================================================

class TestTryMakeLines:
    def test_normal_generator(self):
        def gen(ctx, h):
            return ["line1", "line2"]

        ctx = {"line_generator": gen}
        result = try_make_lines(ctx, 10)
        assert result == ["line1", "line2"]

    def test_generator_that_raises(self):
        def bad_gen(ctx, h):
            raise ValueError("inner error")

        ctx = {"line_generator": bad_gen}
        with pytest.raises(Exception, match="Problem with line generator") as exc_info:
            try_make_lines(ctx, 10)
        assert exc_info.value.__cause__ is not None
        assert isinstance(exc_info.value.__cause__, ValueError)

    def test_missing_line_generator_key(self):
        """Missing line_generator key → KeyError wrapped in Exception."""
        with pytest.raises(Exception, match="Problem with line generator"):
            try_make_lines({}, 10)


# ===========================================================================
# try_print_line
# ===========================================================================

class TestTryPrintLine:
    def test_normal_printer(self):
        called_with = []

        def printer(screen, y):
            called_with.append((screen, y))

        try_print_line(printer, "mock_screen", 5)
        assert called_with == [("mock_screen", 5)]

    def test_printer_that_raises(self):
        def bad_printer(screen, y):
            raise RuntimeError("render error")

        with pytest.raises(Exception, match="problem with line printer") as exc_info:
            try_print_line(bad_printer, "mock_screen", 3)
        assert exc_info.value.__cause__ is not None
        assert isinstance(exc_info.value.__cause__, RuntimeError)
