"""Left pane (60%) — fast-scrolling subprocess output via RichLog."""

from rich.text import Text
from textual.app import ComposeResult
from textual.widget import Widget
from textual.widgets import RichLog


class LogPane(Widget):
    """Wraps a RichLog optimised for high-throughput line appending.

    RichLog is Textual's fastest text-output widget — it bypasses the
    layout engine and appends directly to an internal ring buffer.
    max_lines caps memory while keeping generous scrollback.
    """

    DEFAULT_CSS = """
    LogPane {
        height: 100%;
    }

    LogPane RichLog {
        height: 100%;
        scrollbar-size-vertical: 1;
        scrollbar-background: $surface;
        scrollbar-color: $accent;
    }
    """

    def compose(self) -> ComposeResult:
        log = RichLog(
            highlight=False,
            markup=True,
            wrap=True,
            auto_scroll=True,
            max_lines=5000,
            id="install-log",
        )
        log.can_focus = False  # Input is the only focusable widget
        yield log

    def append_line(self, text: str, is_stderr: bool = False) -> None:
        """Append a single line to the install log.

        stderr lines are rendered in yellow for readability on dark backgrounds.
        """
        log = self.query_one("#install-log", RichLog)
        if is_stderr:
            log.write(Text(text, style="bold #ffcc00"))
        else:
            log.write(Text(text))

    def append_step_result(
        self,
        index: int,
        name: str,
        total: int,
        success: bool,
        error: str = "",
    ) -> None:
        """Write a color-coded step result line to the log."""
        log = self.query_one("#install-log", RichLog)
        styled = Text()
        if success:
            styled.append(
                f"  \u2713 Step {index}/{total}: {name} \u2014 OK",
                style="bold green",
            )
        else:
            detail = f" \u2014 FAILED: {error}" if error else " \u2014 FAILED"
            styled.append("  \u2717 ", style="bold red")
            styled.append(
                f"Step {index}/{total}: {name}{detail}",
                style="bold white",
            )
        log.write(styled)
