import io
import sys

from colored.cprint import cprint, resolve_background, resolve_foreground
from colored.library import Library


def _capture(func: object, *args: object, **kwargs: object) -> str:
    old_stdout = sys.stdout
    sys.stdout = io.StringIO()
    func(*args, **kwargs)  # type: ignore[operator]
    output = sys.stdout.getvalue()
    sys.stdout = old_stdout
    return output


def test_cprint_fore_256() -> None:
    output = _capture(cprint, 'Hello', fore_256='red')
    assert 'Hello' in output


def test_cprint_back_256() -> None:
    output = _capture(cprint, 'Hello', back_256='blue')
    assert 'Hello' in output


def test_cprint_fore_rgb() -> None:
    output = _capture(cprint, 'Hello', fore_rgb=(255, 0, 0))
    assert 'Hello' in output


def test_cprint_back_rgb() -> None:
    output = _capture(cprint, 'Hello', back_rgb=(0, 255, 0))
    assert 'Hello' in output


def test_cprint_no_reset() -> None:
    output = _capture(cprint, 'Hello', fore_256='red', reset=False)
    assert 'Hello' in output


def test_cprint_formatting() -> None:
    output = _capture(cprint, 'Hello', formatting='bold')
    assert 'Hello' in output


def test_resolve_foreground_256() -> None:
    result = resolve_foreground('red', None)
    assert result != ''


def test_resolve_foreground_rgb() -> None:
    result = resolve_foreground(None, (255, 0, 0))
    assert result != ''


def test_resolve_foreground_empty() -> None:
    assert resolve_foreground(None, None) == ''


def test_resolve_background_256() -> None:
    result = resolve_background('red', None)
    assert result != ''


def test_resolve_background_rgb() -> None:
    result = resolve_background(None, (0, 255, 0))
    assert result != ''


def test_resolve_background_empty() -> None:
    assert resolve_background(None, None) == ''


def test_cprint_all_colors() -> None:
    for color in list(Library.COLORS.values())[:10]:
        output = _capture(cprint, 'Test', fore_256=color)
        assert 'Test' in output
