from __future__ import annotations

import threading
from dataclasses import dataclass
from typing import Literal

from hytop.core.history import SlidingHistory

NetKind = Literal["eth", "ib"]


@dataclass(frozen=True)
class NetCounter:
    """One network interface counter snapshot."""

    kind: NetKind
    name: str
    rx_bytes: int
    tx_bytes: int
    link_state: str | None = None
    device_name: str | None = None

    @property
    def key(self) -> str:
        return f"{self.kind}:{self.name}"


@dataclass
class NodeCounterSnapshot:
    """Collection result for one host."""

    host: str
    counters: dict[str, NetCounter]
    sample_ts: float = 0.0
    error: str | None = None


@dataclass
class RateSample:
    """Rate sample for one host+iface key."""

    ts: float
    rx_bps: float
    tx_bps: float


@dataclass
class HostSnapshot:
    seq: int = 0
    result: NodeCounterSnapshot | None = None


@dataclass
class MonitorState:
    max_window: float
    histories: dict[tuple[str, str], SlidingHistory]
    monitored_keys: set[tuple[str, str]]
    latest_counter_by_key: dict[tuple[str, str], NetCounter]
    previous_counter_by_key: dict[tuple[str, str], NetCounter]
    previous_sample_ts_by_key: dict[tuple[str, str], float]
    errors: dict[str, str]
    host_state: dict[str, HostSnapshot]
    processed_seq: dict[str, int]
    state_lock: threading.Lock
    stop_event: threading.Event
