"""DNS tab widget - combines DNS summary with name resolution."""

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 ResolvedDnsServer
from flux_networking_shared.tui.widgets.dns_summary import DnsSummary
from flux_networking_shared.tui.widgets.name_resolution import NameResolution


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

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

    async def test_dns(self, hostnames: list[str] | None = None) -> dict[str, Any]: ...


class Dns(Widget):
    """Combined widget showing DNS servers and name resolution status.

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

    BORDER_TITLE = "Domain Name System"

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

        Args:
            client: RPC client for network operations
        """
        super().__init__()
        self.client = client
        self.dns_summary = DnsSummary()
        self.name_resolution = NameResolution(client)

    def compose(self) -> ComposeResult:
        yield self.dns_summary
        yield self.name_resolution

    def update_servers(
        self, links: dict[int, str], servers: list[ResolvedDnsServer]
    ) -> None:
        """Update DNS server list.

        Args:
            links: Interface index to name mapping
            servers: List of DNS server objects
        """
        self.dns_summary.update_servers(links, servers)

    def update_resolutions(self, results: list[dict[str, Any]]) -> None:
        """Update name resolution results.

        Args:
            results: List of resolution result dicts
        """
        self.name_resolution.update_from_results(results)

    @on(NameResolution.ResolutionStateChanged)
    def on_resolution_changed(
        self, event: NameResolution.ResolutionStateChanged
    ) -> None:
        """Forward resolution state changes."""
        # Parent widgets can handle this event
        pass
