"""LiveFeedWidget - Real-time Claude output display.

Contract: CNT-TUI-WDG-005
Traceability: UX-001, UI-002
"""

from textual.widgets import RichLog


class LiveFeedWidget(RichLog):
    """Widget displaying Claude Code output in real-time.

    Features:
    - Auto-scrolling to latest output
    - Syntax highlighting for different output types
    - Limited buffer to prevent memory issues
    - Supports streaming callback pattern
    """

    DEFAULT_CSS = """
    LiveFeedWidget {
        border: round #8b5cf6;
        padding: 0 1;
        margin: 0 1 1 1;
        height: 1fr;
        min-height: 10;
        background: #0f0a1a;
    }
    """

    # Output type indicators
    THOUGHT_MARKERS = ["[THOUGHT]", "thinking", "considering", "analyzing"]
    ACTION_MARKERS = [">", "Reading", "Writing", "Executing", "Created", "Modified"]
    ERROR_MARKERS = ["Error", "Failed", "error:", "ERROR"]
    SUCCESS_MARKERS = ["Success", "Completed", "✔", "Done"]

    def __init__(self, max_lines: int = 500) -> None:
        """Initialize the live feed.

        Args:
            max_lines: Maximum lines to keep in buffer
        """
        super().__init__(
            highlight=True,
            markup=True,
            max_lines=max_lines,
            auto_scroll=True,
        )
        self._is_active = False

    def append_line(self, line: str) -> None:
        """Append a line to the feed with syntax highlighting.

        This method is designed to be used as a callback for
        ExecutePhaseService.execute_streaming().

        Args:
            line: Output line from Claude Code
        """
        styled_line = self._style_line(line)
        self.write(styled_line)

    def _style_line(self, line: str) -> str:
        """Apply styling based on line content.

        Args:
            line: Raw output line

        Returns:
            Styled line with Rich markup
        """
        stripped = line.strip()

        # Check for thought/reasoning lines
        for marker in self.THOUGHT_MARKERS:
            if marker.lower() in stripped.lower():
                return f"[italic #c084fc]{line}[/]"

        # Check for action lines
        for marker in self.ACTION_MARKERS:
            if stripped.startswith(marker):
                return f"[#5eead4]{line}[/]"

        # Check for error lines
        for marker in self.ERROR_MARKERS:
            if marker in stripped:
                return f"[bold #f87171]{line}[/]"

        # Check for success lines
        for marker in self.SUCCESS_MARKERS:
            if marker in stripped:
                return f"[bold #10b981]{line}[/]"

        # Default styling
        return f"[#e2e8f0]{line}[/]"

    def start_execution(self, phase: int, step: int) -> None:
        """Mark the start of an execution.

        Args:
            phase: Phase number
            step: Step number
        """
        self._is_active = True
        self.clear()
        self.write(f"[bold #a78bfa]▶ Starting Phase {phase} Step {step}...[/]\n")

    def end_execution(self, success: bool) -> None:
        """Mark the end of an execution.

        Args:
            success: Whether execution succeeded
        """
        self._is_active = False
        if success:
            self.write("\n[bold #10b981]✔ Execution completed successfully[/]")
        else:
            self.write("\n[bold #f87171]✘ Execution failed[/]")

    def show_idle_message(self) -> None:
        """Show idle state message."""
        self.clear()
        self.write(
            "[#64748b]Waiting for execution...[/]\n\n"
            "[#94a3b8]Press [bold]Ctrl+R[/] to run the next step[/]\n"
            "[#94a3b8]Press [bold]Ctrl+L[/] to login to Claude Code[/]\n\n"
            "[#64748b]Tip: Hold [bold]Shift[/] + drag mouse to select text[/]"
        )

    @property
    def is_active(self) -> bool:
        """Check if execution is in progress."""
        return self._is_active
