"""TelemetryBar - Status bar widget with real-time metrics.

Contract: CNT-TUI-WDG-001
Traceability: UX-001
"""

from typing import Any

from textual.reactive import reactive
from textual.widgets import Static

from laida_cli.tui.services.telemetry_service import TelemetryService


class TelemetryBar(Static):
    """Bottom status bar showing session metrics in real-time.

    Displays:
    - Last execution result (✔ P0-S0 or ✘ P1-S2)
    - Session duration (00:14:32)
    - Current task duration (00:00:45 or --:--)
    - Memory usage (24MB)

    Uses Textual reactive attributes for automatic UI updates.
    """

    # Reactive attributes - UI updates automatically when these change
    last_result: reactive[str] = reactive("--")
    session_time: reactive[str] = reactive("00:00:00")
    task_time: reactive[str] = reactive("--:--")
    memory_mb: reactive[int] = reactive(0)

    DEFAULT_CSS = """
    TelemetryBar {
        dock: bottom;
        height: 1;
        background: #1e1b4b;
        color: #e2e8f0;
        padding: 0 1;
    }
    """

    def __init__(
        self,
        telemetry_service: TelemetryService | None = None,
        **kwargs: Any,
    ) -> None:
        """Initialize with optional telemetry service.

        Args:
            telemetry_service: Service for metrics (creates default if None)
            **kwargs: Additional arguments for Static
        """
        super().__init__(**kwargs)
        self._telemetry = telemetry_service or TelemetryService()

    def on_mount(self) -> None:
        """Start periodic updates when widget is mounted."""
        # Update every second
        self.set_interval(1.0, self._refresh_metrics)
        # Initial update
        self._refresh_metrics()

    def _refresh_metrics(self) -> None:
        """Fetch latest metrics and update reactive attributes."""
        data = self._telemetry.get_data()

        self.last_result = data.last_result
        self.session_time = TelemetryService.format_duration(data.session_elapsed_seconds)
        self.task_time = TelemetryService.format_task_time(data.task_elapsed_seconds)
        self.memory_mb = data.memory_mb

    def render(self) -> str:
        """Render the telemetry bar content."""
        # Build status segments
        segments = [
            f"Last: {self.last_result}",
            f"Session: {self.session_time}",
            f"Task: {self.task_time}",
            f"RAM: {self.memory_mb}MB",
        ]
        return " │ ".join(segments)

    @property
    def telemetry_service(self) -> TelemetryService:
        """Get the underlying telemetry service."""
        return self._telemetry
