"""Progress bar widget for time-based visualization."""

from __future__ import annotations

from rich.text import Text

from hil_testbench.display.widgets.base import RenderOutput, WidgetContext
from hil_testbench.display.widgets.theme import get_theme


class ProgressBarWidget:
    """Progress bar for elapsed/remaining time."""

    def __init__(
        self,
        current: float,
        total: float,
        width: int = 8,
        show_text: bool = True,
        countdown: bool = True,
    ):
        """
        Args:
            current: Current value (elapsed seconds)
            total: Total value (duration seconds)
            width: Bar width in characters
            show_text: Show "45s / 60s" text
            countdown: Show remaining (True) vs elapsed (False)
        """
        self.current = current
        self.total = total
        self.width = width
        self.show_text = show_text
        self.countdown = countdown

    def render(self, context: WidgetContext) -> RenderOutput:
        """Render progress bar with optional time text."""
        if context.is_minimal():
            # Minimal mode: just show time text
            if self.show_text:
                if self.countdown:
                    remaining = max(0, self.total - self.current)
                    text = Text(f"{remaining:.0f}s", style="dim")
                else:
                    text = Text(f"{self.current:.0f}s", style="dim")
                return RenderOutput.from_text(text)
            return RenderOutput.from_text(Text(""))

        theme = get_theme()

        # Calculate fill ratio
        ratio = min(1.0, self.current / self.total) if self.total > 0 else 0
        filled_width = int(ratio * self.width)
        empty_width = self.width - filled_width

        # Color based on progress
        if ratio < 0.33:
            color = "red"
        elif ratio < 0.66:
            color = "yellow"
        else:
            color = "green"

        # Build bar
        bar = theme.progress_filled * filled_width + theme.progress_empty * empty_width
        text = Text(f"[{bar}]", style=color)

        # Add time text
        if self.show_text:
            if self.countdown:
                # Show elapsed/total format instead of just remaining
                text.append(f" {self.current:.0f}/{self.total:.0f}s", style="dim")
            else:
                text.append(f" {self.current:.0f}s / {self.total:.0f}s", style="dim")

        return RenderOutput.from_text(text)
