"""Terminal output handler with formatting."""

import sys
from datetime import datetime
from typing import Optional

from .callback_types import OutputCallbacks


class TerminalOutput:
    """Terminal output handler with nice formatting."""

    # Color codes
    RESET = "\033[0m"
    BOLD = "\033[1m"
    DIM = "\033[2m"

    # Role colors
    COLORS = {
        "host": "\033[95m",  # Magenta
        "pm": "\033[94m",  # Blue
        "tech_lead": "\033[96m",  # Cyan
        "backend": "\033[92m",  # Green
        "frontend": "\033[93m",  # Yellow
        "qa": "\033[91m",  # Red
        "devops": "\033[35m",  # Purple
        "security": "\033[31m",  # Dark red
        "member": "\033[37m",  # White
        "system": "\033[90m",  # Gray
    }

    def __init__(self, show_timestamp: bool = True, use_colors: bool = True):
        """Initialize terminal output.

        Args:
            show_timestamp: Show timestamps in output
            use_colors: Use ANSI colors
        """
        self.show_timestamp = show_timestamp
        self.use_colors = use_colors
        self.callbacks = self._create_callbacks()

    def _create_callbacks(self) -> OutputCallbacks:
        """Create output callbacks.

        Returns:
            OutputCallbacks instance
        """
        return OutputCallbacks(
            output=self._output,
            typing=self._typing,
            system=self._system,
            error=self._error,
        )

    def _get_color(self, role: str) -> str:
        """Get color code for role.

        Args:
            role: Role name

        Returns:
            ANSI color code or empty string
        """
        if not self.use_colors:
            return ""
        return self.COLORS.get(role.lower(), "")

    def _get_timestamp(self) -> str:
        """Get formatted timestamp.

        Returns:
            Timestamp string or empty string
        """
        if not self.show_timestamp:
            return ""
        return f"[{datetime.now().strftime('%H:%M:%S')}] "

    def _output(self, speaker: str, role: str, message: str) -> None:
        """Output a message.

        Args:
            speaker: Speaker name
            role: Speaker role
            message: The message
        """
        timestamp = self._get_timestamp()
        color = self._get_color(role)
        reset = self.RESET if self.use_colors else ""
        bold = self.BOLD if self.use_colors else ""

        print(
            f"{timestamp}{color}{bold}[{speaker}]{reset} {message}",
            flush=True,
        )

    def _typing(self, speaker: str, partial: str) -> None:
        """Show typing indicator.

        Args:
            speaker: Speaker name
            partial: Partial message (chunk only, not accumulated)
        """
        # Print chunk only (speaker name handled separately)
        print(partial, end="", flush=True)

    def _system(self, message: str) -> None:
        """Output system message.

        Args:
            message: System message
        """
        timestamp = self._get_timestamp()
        color = self._get_color("system")
        reset = self.RESET if self.use_colors else ""
        dim = self.DIM if self.use_colors else ""

        print(
            f"{timestamp}{color}{dim}[SYSTEM] {message}{reset}",
            flush=True,
        )

    def _error(self, message: str) -> None:
        """Output error message.

        Args:
            message: Error message
        """
        timestamp = self._get_timestamp()
        bold = self.BOLD if self.use_colors else ""
        reset = self.RESET if self.use_colors else ""

        print(
            f"{timestamp}\033[91m{bold}[ERROR] {message}{reset}",
            file=sys.stderr,
            flush=True,
        )

    def print_separator(self, char: str = "=", length: int = 60) -> None:
        """Print a separator line.

        Args:
            char: Character to use
            length: Length of line
        """
        print(char * length)

    def print_header(self, text: str) -> None:
        """Print a header.

        Args:
            text: Header text
        """
        self.print_separator()
        print(f"  {text}")
        self.print_separator()
        print()
