"""Composite task status widget combining all components."""

from __future__ import annotations

from typing import Any

from rich.text import Text

from hil_testbench.data_structs.parameters import ParametersSchema
from hil_testbench.display.widgets.base import RenderOutput, WidgetContext
from hil_testbench.display.widgets.parameter import ParameterValueWidget
from hil_testbench.display.widgets.progress import ProgressBarWidget
from hil_testbench.display.widgets.status import StatusWidget
from hil_testbench.display.widgets.trendline import TrendlineWidget


class TaskStatusWidget:
    """Composite widget for complete task status display."""

    def __init__(
        self,
        task_name: str,
        status: str,
        primary_param: tuple[str, float] | None = None,
        trendline_data: Any | None = None,
        elapsed: float = 0,
        duration: float = 60,
        error_count: int = 0,
        schema: ParametersSchema | None = None,
    ):
        """
        Args:
            task_name: Task name
            status: Task status (running, completed, failed)
            primary_param: (param_name, value) tuple for primary parameter
            trendline_data: TrendlineData for primary parameter
            elapsed: Elapsed time in seconds
            duration: Total duration in seconds
            error_count: Number of errors
            schema: Parameter schema for formatting
        """
        self.task_name = task_name
        self.status = status
        self.primary_param = primary_param
        self.trendline_data = trendline_data
        self.elapsed = elapsed
        self.duration = duration
        self.error_count = error_count
        self.schema = schema

    def render(self, context: WidgetContext) -> RenderOutput:
        """
        Renders: "task_name 🟢 2.4 Gbps [▃▄▅▆▇ ↗] [▓▓▓░░░░░] 30s"
        """
        parts = [Text(self.task_name, style="bold"), Text(" ")]

        # Status icon
        status_widget = StatusWidget(self.status)
        parts.append(status_widget.render(context).rich_text)
        parts.append(Text(" "))

        # Stale warning annotation
        if self.status == "stale":
            parts.append(Text("NO DATA ", style="yellow bold"))

        # Primary parameter value
        if self.primary_param and self.schema:
            param_name, param_value = self.primary_param
            field = next((f for f in self.schema.fields if f.name == param_name), None)
            if field:
                value_widget = ParameterValueWidget(param_value, field)
                parts.append(value_widget.render(context).rich_text)
                parts.append(Text(" "))

                # Trendline (normal/full mode only)
                if not context.is_minimal() and self.trendline_data:
                    trendline_widget = TrendlineWidget(self.trendline_data)
                    parts.append(trendline_widget.render(context).rich_text)
                    parts.append(Text(" "))

        # Progress bar (normal/full mode only)
        if not context.is_minimal() and self.duration > 0:
            progress_widget = ProgressBarWidget(
                current=self.elapsed,
                total=self.duration,
                countdown=True,
            )
            parts.append(progress_widget.render(context).rich_text)

        # Error count annotation
        if self.error_count > 0:
            parts.append(Text(f" ⚠️ {self.error_count} errors", style="yellow"))

        # Assemble
        result = Text()
        for part in parts:
            result.append(part)

        return RenderOutput.from_text(result)
