"""Unit tests for InputReader class."""

import queue
import time

import pytest

from thetable_poc.core.human.input_reader import InputReader


class TestInputReader:
    """Test InputReader core functionality."""

    def test_initialization(self):
        """Test InputReader initializes correctly."""
        reader = InputReader()

        assert not reader.is_running
        assert not reader.has_pending_input()

    def test_start_stop(self):
        """Test start and stop methods."""
        reader = InputReader()

        # Start the reader
        reader.start()
        assert reader.is_running

        # Stop the reader
        reader.stop()
        time.sleep(0.1)  # Give thread time to stop
        assert not reader.is_running

    def test_start_idempotent(self):
        """Test that calling start multiple times is safe."""
        reader = InputReader()

        reader.start()
        assert reader.is_running

        # Should not cause issues
        reader.start()
        assert reader.is_running

        reader.stop()

    def test_stop_idempotent(self):
        """Test that calling stop multiple times is safe."""
        reader = InputReader()

        reader.start()
        reader.stop()
        time.sleep(0.1)

        # Should not cause issues
        reader.stop()
        assert not reader.is_running

    def test_has_pending_input_empty(self):
        """Test has_pending_input returns False when queue is empty."""
        reader = InputReader()
        assert not reader.has_pending_input()

    def test_get_input_empty_nonblocking(self):
        """Test get_input returns None when no input is available."""
        reader = InputReader()
        result = reader.get_input(timeout=None)
        assert result is None

    def test_clear(self):
        """Test clear method empties the queue."""
        reader = InputReader()

        # Manually add items to queue for testing
        reader._input_queue.put("test1")
        reader._input_queue.put("test2")

        assert reader.has_pending_input()

        # Clear the queue
        reader.clear()

        assert not reader.has_pending_input()

    def test_get_input_from_queue(self):
        """Test get_input retrieves from queue when available."""
        reader = InputReader()

        # Manually add item to queue for testing
        test_input = "test input"
        reader._input_queue.put(test_input)

        assert reader.has_pending_input()
        result = reader.get_input(timeout=None)
        assert result == test_input
        assert not reader.has_pending_input()
