"""Human participant implementation."""

from typing import Any, Callable, Optional

from ..participant import Participant
from .input_reader import InputReader


class HumanParticipant(Participant):
    """Human participant in the meeting."""

    def __init__(
        self,
        config,
        input_callback: Optional[Callable[[str], str]] = None,
    ):
        """Initialize human participant.

        Args:
            config: Participant configuration
            input_callback: Optional callback for getting user input
                           If None, uses built-in input()
        """
        super().__init__(config)
        self._input_callback = input_callback or self._default_input
        self._input_reader: Optional[InputReader] = None
        self._use_async_input = False

    def _default_input(self, prompt: str) -> str:
        """Default input method using built-in input().

        Args:
            prompt: Prompt to display

        Returns:
            User input
        """
        return input(prompt)

    def speak(self, context: dict[str, Any]) -> str:
        """Get human input.

        Args:
            context: Context (can include suggestions or prompts)

        Returns:
            Human's response
        """
        # Build prompt from context
        prompt_parts = [f"\n[{self.name}]"]

        if "phase" in context:
            prompt_parts.append(f"(Phase: {context['phase']})")

        if "question" in context:
            prompt_parts.append(f"\n{context['question']}")

        prompt_parts.append("> ")
        prompt = " ".join(prompt_parts)

        # Get input
        response = self._input_callback(prompt)

        # Store in history
        self._message_history.append({"sender": self.name, "message": response})

        return response

    def can_speak_now(self, context: dict[str, Any]) -> bool:
        """Human can always speak.

        Args:
            context: Current context

        Returns:
            Always True
        """
        return True

    def set_input_callback(self, callback: Callable[[str], str]) -> None:
        """Set custom input callback.

        Args:
            callback: Function to get user input
        """
        self._input_callback = callback

    def start_input_reader(self) -> None:
        """Start asynchronous input reader.

        This enables non-blocking input handling in the background.
        """
        if self._input_reader is None:
            self._input_reader = InputReader()

        self._input_reader.start()
        self._use_async_input = True

    def stop_input_reader(self) -> None:
        """Stop asynchronous input reader."""
        if self._input_reader is not None:
            self._input_reader.stop()
            self._use_async_input = False

    def check_pending_input(self) -> Optional[str]:
        """Check for pending user input without blocking.

        Returns:
            Pending input string if available, None otherwise
        """
        if self._input_reader is None or not self._use_async_input:
            return None

        return self._input_reader.get_input(timeout=None)
