"""Flux connectivity widget - pure display, receives data from daemon events."""

from __future__ import annotations

from typing import Any

from textual.app import ComposeResult
from textual.dom import NoMatches
from textual.widget import Widget
from textual.widgets import DataTable


class FluxConnectivity(Widget, can_focus=True):
    BORDER_TITLE = "Flux Connectivity"

    def compose(self) -> ComposeResult:
        yield DataTable(show_cursor=False)

    def handle_flux_connectivity_event(self, data: dict[str, Any]) -> None:
        """Handle FLUX_CONNECTIVITY_UPDATE event data from the daemon.

        Args:
            data: Event data with "nodes" list of node check results
        """
        nodes = data.get("nodes", [])

        rows: list[tuple[str, str, str, bool, int | str | None]] = []
        for node in nodes:
            elapsed = str.rjust(f"{node['elapsed_ms']:.2f} ms", 10)
            rows.append((
                node["node"],
                node["path"],
                elapsed,
                node["connected"],
                node["response"],
            ))

        self._update_table(rows)

    def _update_table(self, rows: list[tuple[str, str, str, bool, int | str | None]]) -> None:
        try:
            table = self.query_one(DataTable)
        except NoMatches:
            return

        table.clear(columns=True)

        columns = ["Fluxnode", "Path", "   Elapsed", "Connected", "Response"]
        table.add_columns(*columns)

        table.add_rows(rows)

    def stop_and_clear(self) -> None:
        try:
            table = self.query_one(DataTable)
        except NoMatches:
            return

        table.clear()

    def watch_has_focus(self, event: bool) -> None:
        super().watch_has_focus(event)
        self.set_class(event, "--highlight")
