"""Parameter value widget with unit formatting."""

from __future__ import annotations

from rich.text import Text

from hil_testbench.data_structs.parameters import ParameterField
from hil_testbench.display.widgets.base import RenderOutput, WidgetContext
from hil_testbench.display.widgets.theme import get_theme
from hil_testbench.units.registry import PintValueFormatter


class ParameterValueWidget:
    """Formatted parameter value with units and threshold color."""

    def __init__(self, value: float, schema_field: ParameterField):
        """
        Args:
            value: Parameter value
            schema_field: Schema definition for formatting
        """
        self.value = value
        self.field = schema_field

    def _get_threshold_color(self) -> str:
        """Determine color based on threshold zones."""
        theme = get_theme()

        # Evaluate thresholds
        for name, threshold in self.field.thresholds.items():
            if threshold.min <= self.value <= threshold.max:
                return threshold.color or theme.threshold_colors.get(name, "cyan")

        return theme.threshold_colors["neutral"]

    def render(self, context: WidgetContext) -> RenderOutput:
        """Render formatted parameter value."""
        # Create formatter
        formatter = PintValueFormatter(
            unit=self.field.unit,
            precision=self.field.precision,
            strategy=self.field.scale_strategy,
        )

        # Format value
        formatted = formatter.format(self.value)

        # Apply threshold color
        color = self._get_threshold_color()

        text = Text(formatted, style=color)
        return RenderOutput.from_text(text)
