"""Kiểm tra sức khỏe trước/sau khi thay đổi: đếm số giao diện up, số route... rồi so sánh để phát hiện thay đổi làm hỏng mạng."""
from __future__ import annotations

import re
from typing import Optional

from drivers.vendors import Vendor

_UPUP = r"\bup\s+up\s*$|protocol-up/link-up"
_ROUTE_IOS = r"^[A-Z*]\w?\s+\d|^\d+\.\d+\.\d+\.\d+/\d+,"

# họ thiết bị -> [(nhãn, lệnh xem, biểu thức đếm số dòng)]
CHECKS: dict[str, list[tuple[str, str, str]]] = {
    "ios": [("Số giao diện đang up", "show ip interface brief", _UPUP), ("Số route", "show ip route", _ROUTE_IOS)],
    "nxos": [("Số giao diện đang up", "show ip interface brief", _UPUP), ("Số route", "show ip route", _ROUTE_IOS)],
    "comware": [("Số giao diện đang up", "display ip interface brief", r"\bup\s+up\b")],
    "huawei": [("Số giao diện đang up", "display ip interface brief", r"\bup\s+up\b")],
    "junos": [("Số giao diện đang up", "show interfaces terse", r"\bup\s+up\b"), ("Số route", "show route", r"\*\[")],
    "junos_srx": [("Số giao diện đang up", "show interfaces terse", r"\bup\s+up\b"), ("Số route", "show route", r"\*\[")],
    "mikrotik": [("Số route", "/ip route print", r"^\s*\d+")],
}


def snapshot(drv, vendor: Vendor) -> dict[str, Optional[int]]:
    """Chạy các lệnh kiểm tra, trả về {nhãn: số lượng}. Lệnh lỗi/không hỗ trợ -> None (bỏ qua khi so sánh)."""
    out: dict[str, Optional[int]] = {}
    for label, cmd, rx in CHECKS.get(vendor.family, []):
        try:
            text = drv.run_show(cmd)
            if "chưa được mô phỏng" in text or "Invalid" in text[:80]:
                out[label] = None
                continue
            out[label] = sum(1 for ln in text.split("\n") if re.search(rx, ln))
        except Exception:
            out[label] = None
    return out


def compare(before: dict, after: dict) -> list[str]:
    """Cảnh báo khi số lượng GIẢM sau thay đổi (mất cổng up / mất route)."""
    warns = []
    for label, b in before.items():
        a = after.get(label)
        if b is None or a is None or b == 0:
            continue
        if a < b:
            warns.append(f"{label}: {b} → {a} (giảm {b - a})" + (" - MẤT HẾT" if a == 0 else ""))
    return warns


def describe(before: dict, after: dict) -> str:
    rows = []
    for label in before:
        b, a = before[label], after.get(label)
        if b is None and a is None:
            continue
        mark = "" if b == a else ("  ▲" if (a or 0) > (b or 0) else "  ▼")
        rows.append(f"  {label}: {b if b is not None else '?'} → {a if a is not None else '?'}{mark}")
    return "\n".join(rows) if rows else "  (hãng này chưa có kiểm tra tự động)"
