"""Routing tab widget - combines route summary with connectivity."""

from __future__ import annotations

from typing import Any, Protocol

from textual import on
from textual.app import ComposeResult
from textual.widget import Widget

from flux_networking_shared.tui.models.network import Route
from flux_networking_shared.tui.widgets.connectivity import Connectivity
from flux_networking_shared.tui.widgets.route_summary import RouteSummary


class NetworkClient(Protocol):
    """Protocol for network RPC client."""

    async def get_routes(self) -> dict[str, Any]: ...


class Routing(Widget):
    """Combined widget showing routing table and connectivity status.

    This widget is used in the Routes tab of the network screen.
    """

    BORDER_TITLE = "Routing"

    def __init__(self, client: NetworkClient | None = None) -> None:
        """Initialize the routing widget.

        Args:
            client: RPC client for network operations
        """
        super().__init__()
        self.client = client
        self.route_summary = RouteSummary()
        self.connectivity = Connectivity(client)

    def compose(self) -> ComposeResult:
        yield self.route_summary
        yield self.connectivity

    def update_routes(self, routes: list[Route]) -> None:
        """Update route summary with new routes.

        Args:
            routes: List of Route objects
        """
        self.route_summary.update_routes(routes)

        # Start monitoring gateways from routes
        gateways = [r.gateway for r in routes if r.gateway and r.is_default]
        if gateways:
            self.connectivity.start_monitoring(gateways)

    @on(Connectivity.ConnectivityStateChanged)
    def on_connectivity_changed(
        self, event: Connectivity.ConnectivityStateChanged
    ) -> None:
        """Forward connectivity state changes."""
        # Parent widgets can handle this event
        pass
