"""Bottom status bar — shows progress bar, step counts, and key hints."""

from textual.widgets import Static


class StatusBar(Static):
    """Three-line docked status bar spanning the full terminal width."""

    DEFAULT_CSS = """
    StatusBar {
        dock: bottom;
        height: 3;
        background: #1e1e2e;
        color: #e0e0e0;
        text-style: bold;
        content-align: left middle;
        padding: 0 2;
    }
    """

    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)
        self.can_focus = False  # Input is the only focusable widget
        self._completed = 0
        self._failed = 0
        self._current_index = 0
        self._current_name = ""
        self._total = 0
        self._status = "Preparing"

    def on_mount(self) -> None:
        self._refresh_display()

    def _render_progress_bar(self) -> str:
        """Build an ASCII progress bar from current step progress."""
        bar_width = 30
        if self._total == 0:
            filled = 0
        else:
            filled = int((self._current_index / self._total) * bar_width)
        empty = bar_width - filled
        bar = "=" * filled
        if filled < bar_width and self._current_index > 0:
            bar = bar[:-1] + ">" if filled > 0 else ">"
            empty = bar_width - len(bar)
        return f"[{bar}{'.' * empty}] {self._current_index}/{self._total}"

    def _refresh_display(self) -> None:
        """Refresh the full 3-line status bar content."""
        progress = self._render_progress_bar()
        step_label = f" {self._current_name}" if self._current_name else ""
        line1 = f" {progress}{step_label}"
        line2 = (
            f" Completed: {self._completed}  |  "
            f"Failed: {self._failed}  |  "
            f"Status: {self._status}"
        )
        line3 = " Ctrl+C: Quit  |  Type below to chat with Johnny 5"
        self.update(f"{line1}\n{line2}\n{line3}")

    def update_step(self, index: int, name: str, total: int) -> None:
        """Update the bar to show current step progress."""
        self._current_index = index
        self._current_name = name
        self._total = total
        self._status = "Running"
        self._refresh_display()

    def record_step_result(self, success: bool) -> None:
        """Record a step completion and update counts."""
        if success:
            self._completed += 1
        else:
            self._failed += 1
        self._refresh_display()

    def show_final(self, success: bool) -> None:
        """Show the final installation result."""
        self._status = "Complete" if success else "FAILED"
        if success:
            self._current_name = "All steps completed!"
        else:
            self._current_name = "Check logs or ask Johnny 5"
        self._refresh_display()
