"""Đọc 'sự thật' từ cấu hình thiết bị (VLAN, cổng, zone, address, policy, ACL, bridge...) để các ô nhập liên kết với nhau.

Nguồn dữ liệu: bản sao lưu mới nhất của thiết bị (tự cập nhật sau mỗi lần chạy cấu hình). Nhờ vậy sau khi tạo VLAN,
ô 'VLAN' ở tác vụ gán cổng sẽ liệt kê VLAN đó để chọn; sau khi tạo zone, ô 'Từ zone' của security policy sẽ hiện zone đó...
"""
from __future__ import annotations

import ipaddress
import re
from dataclasses import dataclass, field
from typing import Iterable, Optional

from drivers.vendors import VENDORS, get_vendor
from .config_tools import parse_tree

PREDEFINED_APPS = ["junos-http", "junos-https", "junos-ssh", "junos-telnet", "junos-ftp", "junos-smtp", "junos-pop3",
                   "junos-imap", "junos-dns-udp", "junos-dns-tcp", "junos-icmp-ping", "junos-ntp", "junos-syslog",
                   "junos-mysql", "junos-ms-sql", "junos-radius", "junos-tftp", "junos-snmp-agent"]
IOS_LIKE = ("ios", "nxos", "cisco_ap", "aruba_os", "tplink", "generic")


@dataclass
class Facts:
    loaded: bool = False
    backup_time: str = ""
    ports_complete: bool = False          # danh sách cổng có đủ mọi cổng vật lý không (Cisco: có; Junos/MikroTik: chỉ cổng đã cấu hình)
    hostname: str = ""
    vlans: dict = field(default_factory=dict)         # id -> tên
    ports: dict = field(default_factory=dict)         # tên cổng -> {desc, mode, vlan, ip, shut}
    svis: dict = field(default_factory=dict)          # vlan id -> ip/prefix (giao diện lớp 3 của VLAN)
    l3: dict = field(default_factory=dict)            # giao diện lớp 3 khác (loopback, cổng routed) -> ip
    portchannels: dict = field(default_factory=dict)  # số nhóm -> mô tả
    zones: dict = field(default_factory=dict)         # zone -> [giao diện]
    addresses: dict = field(default_factory=dict)     # tên đối tượng -> giá trị
    addrsets: list = field(default_factory=list)
    applications: dict = field(default_factory=dict)
    policies: list = field(default_factory=list)      # (from_zone, to_zone, tên)
    acls: list = field(default_factory=list)
    bridges: list = field(default_factory=list)
    src_rulesets: list = field(default_factory=list)
    dst_rulesets: list = field(default_factory=list)
    src_pools: list = field(default_factory=list)
    dst_pools: list = field(default_factory=list)
    dhcp_pools: list = field(default_factory=list)
    routes: list = field(default_factory=list)
    ssids: list = field(default_factory=list)


def _expand_ids(spec: str) -> list[str]:
    out: list[str] = []
    for tok in re.split(r"[,\s]+", spec.strip()):
        if re.fullmatch(r"\d+-\d+", tok):
            a, b = map(int, tok.split("-"))
            if 0 < a <= b <= 4094 and b - a <= 4094:
                out += [str(i) for i in range(a, b + 1)]
        elif tok.isdigit():
            out.append(tok)
    return out


def _expand_huawei_batch(tokens: list[str]) -> list[str]:
    out, i = [], 0
    while i < len(tokens):
        if i + 2 < len(tokens) and tokens[i + 1] == "to" and tokens[i].isdigit() and tokens[i + 2].isdigit():
            out += [str(n) for n in range(int(tokens[i]), int(tokens[i + 2]) + 1)]
            i += 3
        else:
            if tokens[i].isdigit():
                out.append(tokens[i])
            i += 1
    return out


def _cidr(addr: str, mask: Optional[str] = None) -> str:
    try:
        return str(ipaddress.ip_interface(f"{addr}/{mask}" if mask else addr))
    except ValueError:
        return addr


def norm_if(name: str) -> str:
    """Chuẩn hóa tên cổng để so sánh (Gi1/0/1 == GigabitEthernet1/0/1)."""
    n = re.sub(r"\s+", "", name.lower())
    for long, short in (("tengigabitethernet", "te"), ("gigabitethernet", "gi"), ("fastethernet", "fa"),
                        ("port-channel", "po"), ("ethernet", "eth")):
        if n.startswith(long):
            return short + n[len(long):]
    return n


def nat_key(s: str):
    return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]


# ---------------------------------------------------------------------------
def _ios_attrs(kids: list[str]) -> dict:
    a = {"desc": "", "mode": "", "vlan": "", "ip": "", "shut": False, "allowed": ""}
    for t in kids:
        m = re.match(r"(?:ip address|ip) (\d+\.\d+\.\d+\.\d+) (\d+\.\d+\.\d+\.\d+)", t) or re.match(r"ip address (\d+\.\d+\.\d+\.\d+/\d+)", t)
        if m and t.startswith("ip address"):
            a["ip"] = _cidr(m.group(1), m.group(2)) if m.lastindex == 2 else _cidr(m.group(1))
        elif t.startswith("description "):
            a["desc"] = t[12:].strip('" ')
        elif t.startswith("switchport mode "):
            a["mode"] = t[16:]
        elif t.startswith("port link-type "):
            a["mode"] = t[15:]
        elif re.match(r"(?:switchport trunk allowed vlan|port trunk allow-pass vlan|port trunk permit vlan) ", t):
            a["allowed"] = (a["allowed"] + " " + re.sub(r"^.*?vlan (?:add )?", "", t)).strip()
        else:
            m = re.match(r"(?:switchport access vlan|port default vlan|port access vlan) (\d+)$", t)
            if m:
                a["vlan"] = m.group(1)
        if t == "shutdown":
            a["shut"] = True
    return a


def parse_ios_like(text: str, family: str) -> Facts:
    f = Facts(ports_complete=True)
    items = parse_tree(text)
    kids: dict[tuple, list[str]] = {}
    for path, line in items:
        kids.setdefault(path, []).append(line)
    for path, line in items:
        if path:
            continue
        m = re.match(r"^vlan (\d[\d,\-]*)$", line)
        if m:
            ids = _expand_ids(m.group(1))
            name = next((c[5:].strip().strip('"') for c in kids.get((line,), []) if c.startswith("name ")), "")
            for i in ids:
                f.vlans[i] = name if len(ids) == 1 else f.vlans.get(i, "")
            continue
        if line.startswith("hostname "):
            f.hostname = line.split(None, 1)[1].strip('"')
        elif line.startswith("interface "):
            name = line.split(None, 1)[1]
            a = _ios_attrs(kids.get((line,), []))
            low = name.lower()
            if low.startswith("vlan"):
                f.svis[re.sub(r"\D", "", name)] = a["ip"]
            elif low.startswith(("port-channel", "trk")):
                f.portchannels[re.sub(r"\D", "", name)] = a["desc"]
            elif low.startswith(("loopback", "mgmt", "tunnel", "null", "bvi")):
                f.l3[name] = a["ip"]
            else:
                f.ports[name] = a
                if a["ip"]:
                    f.l3[name] = a["ip"]
        else:
            m = re.match(r"^(?:ip|ipv4) access-list (?:extended |standard |resequence )?(\S+)$", line)
            if m:
                f.acls.append(m.group(1))
            m = re.match(r"^ip route (\S+) (\S+) (\S+)", line)
            if m:
                f.routes.append(_cidr(m.group(1), m.group(2)) if "." in m.group(2) else m.group(1))
            m = re.match(r"^dot11 ssid (\S+)$", line)
            if m:
                f.ssids.append(m.group(1))
            m = re.match(r"^ip dhcp pool (\S+)$", line)
            if m:
                f.dhcp_pools.append(m.group(1))
            m = re.match(r"^radius server (\S+)$", line)
    return f


def parse_comware(text: str, family: str) -> Facts:
    f = Facts(ports_complete=True)
    items = parse_tree(text)
    kids: dict[tuple, list[str]] = {}
    for path, line in items:
        kids.setdefault(path, []).append(line)
    for path, line in items:
        if path:
            continue
        m = re.match(r"^vlan batch (.+)$", line)
        if m:
            for i in _expand_huawei_batch(m.group(1).split()):
                f.vlans.setdefault(i, "")
            continue
        m = re.match(r"^vlan (\d[\d,\-]*)$", line)
        if m:
            ids = _expand_ids(m.group(1))
            name = next((c.split(None, 1)[1].strip() for c in kids.get((line,), []) if c.startswith(("name ", "description "))), "")
            for i in ids:
                f.vlans[i] = name if len(ids) == 1 else f.vlans.get(i, "")
        elif line.startswith("sysname "):
            f.hostname = line.split(None, 1)[1]
        elif line.startswith("interface "):
            name = line.split(None, 1)[1]
            a = _ios_attrs(kids.get((line,), []))
            low = name.lower()
            if low.startswith(("vlan-interface", "vlanif")):
                f.svis[re.sub(r"\D", "", name)] = a["ip"]
            elif low.startswith(("bridge-aggregation", "eth-trunk")):
                f.portchannels[re.sub(r"\D", "", name)] = a["desc"]
            elif low.startswith(("loopback", "null", "nve", "tunnel")):
                f.l3[name] = a["ip"]
            else:
                f.ports[name] = a
        else:
            m = re.match(r"^acl (?:number |name |advanced |basic |ipv6 )*(\S+)", line)
            if m:
                f.acls.append(m.group(1))
    return f


def parse_junos(text: str, family: str) -> Facts:
    f = Facts(ports_complete=False)
    for ln in text.split("\n"):
        ln = ln.strip()
        if not ln.startswith("set "):
            continue
        t = ln[4:]
        m = re.match(r"vlans (\S+) vlan-id (\d+)$", t)
        if m:
            f.vlans[m.group(2)] = m.group(1)
            continue
        m = re.match(r"system host-name (\S+)", t)
        if m:
            f.hostname = m.group(1)
            continue
        m = re.match(r"interfaces (\S+) (.*)$", t) or re.match(r"interfaces (\S+)$", t)
        if m:
            name, rest = m.group(1), (m.group(2) if m.lastindex == 2 else "")
            if name == "irb":
                u = re.match(r"unit (\d+)(?: family inet address (\S+))?", rest)
                if u:
                    f.svis[u.group(1)] = u.group(2) or f.svis.get(u.group(1), "")
            elif name.startswith("ae"):
                f.portchannels[name[2:]] = ""
            elif re.match(r"(lo|fxp|em|me|vme|st|gr|ip|lt|vlan)\d", name):
                f.l3[name] = ""
            else:
                a = f.ports.setdefault(name, {"desc": "", "mode": "", "vlan": "", "ip": "", "shut": False, "allowed": ""})
                d = re.match(r'description "?([^"]*)"?$', rest)
                if d:
                    a["desc"] = d.group(1)
                if rest == "disable":
                    a["shut"] = True
                im = re.search(r"interface-mode (\S+)", rest)
                if im:
                    a["mode"] = im.group(1)
                vm = re.search(r"vlan members (?:\[ )?(\S+)", rest)
                if vm:
                    a["vlan"] = vm.group(1)
                vm2 = re.search(r"vlan members (.+)$", rest)
                if vm2:
                    a["allowed"] = (a.get("allowed", "") + " " + vm2.group(1).replace("[", " ").replace("]", " ")).strip()
                ad = re.search(r"family inet address (\S+)", rest)
                if ad:
                    a["ip"] = ad.group(1)
                    f.l3[name] = ad.group(1)
            continue
        m = re.match(r"security zones security-zone (\S+)(?: (.*))?$", t)
        if m:
            z = f.zones.setdefault(m.group(1), [])
            i = re.match(r"interfaces (\S+)$", m.group(2) or "")
            if i and i.group(1) not in z:
                z.append(i.group(1))
            continue
        m = re.match(r"security address-book \S+ address (\S+) (\S+)$", t)
        if m:
            f.addresses[m.group(1)] = m.group(2)
            continue
        m = re.match(r"security address-book \S+ address-set (\S+)", t)
        if m:
            if m.group(1) not in f.addrsets:
                f.addrsets.append(m.group(1))
            continue
        m = re.match(r"applications application (\S+)", t)
        if m:
            f.applications.setdefault(m.group(1), "")
            continue
        m = re.match(r"security policies from-zone (\S+) to-zone (\S+) policy (\S+)", t)
        if m:
            p = (m.group(1), m.group(2), m.group(3))
            if p not in f.policies:
                f.policies.append(p)
            continue
        for key, attr in (("security nat source rule-set", "src_rulesets"), ("security nat destination rule-set", "dst_rulesets"),
                          ("security nat source pool", "src_pools"), ("security nat destination pool", "dst_pools"),
                          ("firewall family inet filter", "acls")):
            m = re.match(re.escape(key) + r" (\S+)", t)
            if m:
                lst = getattr(f, attr)
                if m.group(1) not in lst:
                    lst.append(m.group(1))
        m = re.match(r"routing-options static route (\S+)", t)
        if m and m.group(1) not in f.routes:
            f.routes.append(m.group(1))
    return f


_MT_KV = re.compile(r'([\w\-]+)=("[^"]*"|\S+)')


def parse_mikrotik(text: str, family: str) -> Facts:
    f = Facts(ports_complete=False)
    sec = ""
    for raw in text.split("\n"):
        ln = raw.strip()
        if not ln or ln.startswith("#"):
            continue
        if ln.startswith("/"):
            sec = ln
            continue
        kv = {k: v.strip('"') for k, v in _MT_KV.findall(ln)}
        if sec == "/interface bridge" and ln.startswith("add") and kv.get("name"):
            f.bridges.append(kv["name"])
        elif sec == "/interface bridge port" and kv.get("interface"):
            f.ports[kv["interface"]] = {"desc": "", "mode": "bridge " + kv.get("bridge", ""), "vlan": kv.get("pvid", ""), "ip": "", "shut": False}
        elif sec == "/interface bridge vlan" and kv.get("vlan-ids"):
            for i in _expand_ids(kv["vlan-ids"]):
                f.vlans[i] = kv.get("comment", f.vlans.get(i, ""))
        elif sec == "/interface vlan" and kv.get("vlan-id"):
            f.vlans[kv["vlan-id"]] = kv.get("name", "")
        elif sec == "/system identity" and kv.get("name"):
            f.hostname = kv["name"]
        elif sec == "/ip address" and kv.get("address"):
            f.l3[kv.get("interface", "?")] = kv["address"]
        elif sec == "/interface wireless" and kv.get("ssid"):
            f.ssids.append(kv["ssid"])
        elif sec == "/ip route" and kv.get("dst-address"):
            f.routes.append(kv["dst-address"])
    return f


def parse_openwrt(text: str, family: str) -> Facts:
    f = Facts(ports_complete=False)
    for ln in text.split("\n"):
        m = re.match(r"^system\.@system\[0\]\.hostname='(.*)'", ln)
        if m:
            f.hostname = m.group(1)
        m = re.match(r"^wireless\.(radio\d+)\.", ln)
        if m:
            f.ports.setdefault(m.group(1), {"desc": "radio", "mode": "", "vlan": "", "ip": "", "shut": False})
        m = re.match(r"^wireless\.\w+\.ssid='(.*)'", ln)
        if m:
            f.ssids.append(m.group(1))
    return f


def parse_fortinet(text: str, family: str) -> Facts:
    f = Facts(ports_complete=False)
    cur = ""
    for ln in text.split("\n"):
        s = ln.strip()
        m = re.match(r"^config (.+)$", s)
        if m:
            cur = m.group(1)
        m = re.match(r'^edit "?([^"]+)"?$', s)
        if m:
            if cur == "switch vlan":
                f.vlans[m.group(1)] = ""
            elif cur == "system interface":
                f.ports[m.group(1)] = {"desc": "", "mode": "", "vlan": "", "ip": "", "shut": False}
        m = re.match(r'^set hostname "?([^"]+)"?$', s)
        if m:
            f.hostname = m.group(1)
    return f


def extract(vendor_key: str, text: str) -> Facts:
    fam = get_vendor(vendor_key).family if vendor_key in VENDORS else "generic"
    if fam in ("junos", "junos_srx"):
        f = parse_junos(text, fam)
    elif fam == "mikrotik":
        f = parse_mikrotik(text, fam)
    elif fam in ("comware", "huawei"):
        f = parse_comware(text, fam)
    elif fam == "openwrt":
        f = parse_openwrt(text, fam)
    elif fam == "fortinet":
        f = parse_fortinet(text, fam)
    else:
        f = parse_ios_like(text, fam)
    f.loaded = bool(text.strip())
    if "1" not in f.vlans and f.loaded and fam not in ("openwrt",):
        f.vlans["1"] = f.vlans.get("1", "default")
    return f


# ---------------------------------------------------------------------------
class FactsStore:
    """Lấy 'sự thật cấu hình' của thiết bị từ bản sao lưu mới nhất (có bộ nhớ đệm theo id bản sao lưu)."""

    def __init__(self, db):
        self.db = db
        self._cache: dict[tuple, Facts] = {}

    def get(self, device: dict) -> Facts:
        b = self.db.last_backup(device["id"])
        if not b:
            return Facts()
        key = (device["id"], b["id"], device["vendor"])
        if key not in self._cache:
            f = extract(device["vendor"], b["config"])
            f.backup_time = b["created"]
            self._cache = {k: v for k, v in self._cache.items() if k[0] != device["id"]}
            self._cache[key] = f
        return self._cache[key]


@dataclass(frozen=True)
class Option:
    value: str
    label: str
    extra: tuple = ()          # ((tên_trường, giá_trị), ...) tự điền vào các ô khác khi chọn


def svi_name(family: str, vid: str) -> str:
    return {"junos": f"irb.{vid}", "junos_srx": f"irb.{vid}", "huawei": f"Vlanif{vid}", "comware": f"Vlan-interface{vid}"}.get(family, f"Vlan{vid}")


def _candidates(ref: str, f: Facts, family: str) -> dict[str, tuple[str, tuple]]:
    """{giá_trị: (nhãn, extra)} của một thiết bị."""
    out: dict[str, tuple[str, tuple]] = {}
    if ref in ("vlan", "vlans"):
        for i, n in f.vlans.items():
            out[i] = (f"{i} — {n}" if n else i, ())
    elif ref == "svi_vlan":
        for i, ip in f.svis.items():
            out[i] = (f"{i} — SVI {ip}" if ip else f"{i} — SVI", ())
    elif ref == "port":
        for n, a in f.ports.items():
            bits = [x for x in (a.get("desc"), a.get("mode"), f"vlan {a['vlan']}" if a.get("vlan") else "", a.get("ip"),
                                "shutdown" if a.get("shut") else "") if x]
            out[n] = (f"{n}  — {', '.join(bits)}" if bits else n, ())
    elif ref == "iface":
        for n, a in f.ports.items():
            out[n] = (n + (f"  — {a['desc']}" if a.get("desc") else ""), ())
        for n, ip in f.l3.items():
            out.setdefault(n, (f"{n}  — {ip}" if ip else n, ()))
        for v, ip in f.svis.items():
            nm = svi_name(family, v)
            out[nm] = (f"{nm}  — {ip}" if ip else nm, ())
    elif ref == "zone":
        for z, ifs in f.zones.items():
            out[z] = (f"{z}  — {', '.join(ifs)}" if ifs else z, ())
    elif ref == "address":
        out["any"] = ("any — mọi địa chỉ", ())
        for n, v in f.addresses.items():
            out[n] = (f"{n}  — {v}", ())
        for n in f.addrsets:
            out[n] = (f"{n}  — address-set", ())
    elif ref == "address_obj":
        for n, v in f.addresses.items():
            out[n] = (f"{n}  — {v}", ())
    elif ref == "addrset":
        for n in f.addrsets:
            out[n] = (n, ())
    elif ref == "application":
        out["any"] = ("any — mọi dịch vụ", ())
        if family == "junos_srx":
            for a in PREDEFINED_APPS:
                out[a] = (a + "  — có sẵn", ())
        for a in f.applications:
            out[a] = (a + "  — tùy chỉnh", ())
    elif ref == "application_new":
        for a in f.applications:
            out[a] = (a, ())
    elif ref == "policy":
        for fz, tz, n in f.policies:
            out[n] = (f"{fz} → {tz}:  {n}", (("from_zone", fz), ("to_zone", tz)))
    elif ref == "portchannel":
        for g, d in f.portchannels.items():
            out[g] = (f"{g}" + (f" — {d}" if d else ""), ())
    elif ref in ("acl", "bridge", "src_ruleset", "dst_ruleset", "src_pool", "dst_pool", "dhcp_pool"):
        attr = {"acl": "acls", "bridge": "bridges", "src_ruleset": "src_rulesets", "dst_ruleset": "dst_rulesets",
                "src_pool": "src_pools", "dst_pool": "dst_pools", "dhcp_pool": "dhcp_pools"}[ref]
        for n in getattr(f, attr):
            out[n] = (n, ())
    return out


def options_for(ref: str, devices: list[dict], store: FactsStore) -> list[Option]:
    """Danh sách lựa chọn cho ô có `ref`, gộp từ cấu hình của các thiết bị đang chọn."""
    merged: dict[str, tuple[str, tuple, int]] = {}
    for d in devices:
        if d["vendor"] not in VENDORS:
            continue
        fam = get_vendor(d["vendor"]).family
        for val, (label, extra) in _candidates(ref, store.get(d), fam).items():
            old = merged.get(val)
            merged[val] = (old[0] if old else label, old[1] if old else extra, (old[2] if old else 0) + 1)
    total = len(devices)
    opts = []
    for val in sorted(merged, key=nat_key):
        label, extra, n = merged[val]
        if total > 1 and n < total:
            label += f"   [{n}/{total} thiết bị]"
        opts.append(Option(val, label, extra))
    return opts


# ---------------------------------------------------------------------------
def vlan_users(f: Facts, vid: str) -> list[str]:
    """Những thứ đang dùng một VLAN: cổng access, trunk cho phép VLAN, SVI."""
    name = f.vlans.get(vid, "")
    users = []
    for n, a in f.ports.items():
        if a.get("vlan") in (vid, name) and a.get("vlan"):
            users.append(f"cổng {n} (access)")
        allowed = a.get("allowed", "")
        ids = set()
        for tok in re.split(r"[,\s]+", allowed):
            ids.update(_expand_ids(tok) if "-" in tok else ([tok] if tok else []))
        if (vid in ids or (name and name in allowed.split())) and a.get("vlan") not in (vid, name):
            users.append(f"cổng {n} (trunk)")
    if vid in f.svis:
        users.append(f"giao diện lớp 3 (SVI/irb) VLAN {vid}")
    return users


_SPLIT = re.compile(r"[,\s;]+")
_IPISH = re.compile(r"^\d{1,3}(\.\d{1,3}){3}(/\d{1,2})?$")


def _tokens(val: str) -> list[str]:
    return [t for t in _SPLIT.split(val.strip()) if t]


def validate_links(fields: Iterable[dict], values: dict, device: dict, facts: Facts) -> list[str]:
    """Cảnh báo khi giá trị nhập không khớp cấu hình hiện có của thiết bị (VLAN chưa tạo, zone chưa có...)."""
    if not facts.loaded or device["vendor"] not in VENDORS:
        return []
    fam = get_vendor(device["vendor"]).family
    warns: list[str] = []
    for fld in fields:
        ref, check = fld.get("ref"), fld.get("check", "exist")
        val = str(values.get(fld["name"], "") or "").strip()
        if not ref or not val or check == "none":
            continue
        label = fld["label"].split("(")[0].strip()
        toks = _tokens(val)
        if ref in ("vlan", "vlans"):
            ids: list[str] = []
            for t in toks:
                ids += _expand_ids(t) if "-" in t else [t]
            missing = [i for i in ids if i not in facts.vlans]
            if check == "unused":
                if missing:
                    warns.append(f"{label}: VLAN {', '.join(missing)} không có trong cấu hình thiết bị.")
                for i in ids:
                    u = vlan_users(facts, i)
                    if u and i in facts.vlans:
                        warns.append(f"VLAN {i} ĐANG ĐƯỢC DÙNG bởi: {', '.join(u[:8])}{'...' if len(u) > 8 else ''} - xóa VLAN sẽ ảnh hưởng các mục này.")
            elif check == "new":
                dup = [i for i in ids if i in facts.vlans and i != "1"]
                if dup:
                    warns.append(f"VLAN {', '.join(dup)} ĐÃ tồn tại trên thiết bị (tên: {facts.vlans[dup[0]] or '-'}) - lệnh sẽ ghi đè/trùng.")
            elif missing:
                warns.append(f"{label}: VLAN {', '.join(missing[:8])} CHƯA có trong cấu hình thiết bị - hãy tạo bằng tác vụ 'Tạo VLAN' trước"
                             + (" (Cisco có thể tự tạo; Junos sẽ báo lỗi khi commit)." if fam in ("ios", "nxos", "junos", "junos_srx") else "."))
        elif ref == "svi_vlan":
            missing = [t for t in toks if t not in facts.svis]
            if missing:
                warns.append(f"{label}: VLAN {', '.join(missing)} chưa có giao diện lớp 3 (SVI/irb) - tạo bằng 'Giao diện VLAN (SVI / IRB)' trước.")
        elif ref == "port" and facts.ports_complete:
            known = {norm_if(n) for n in list(facts.ports) + [f"port-channel{g}" for g in facts.portchannels]}
            missing = [t for t in toks if norm_if(t) not in known]
            if missing:
                warns.append(f"{label}: không thấy cổng {', '.join(missing[:6])} trong cấu hình (kiểm tra lại tên cổng).")
        elif ref == "zone":
            missing = [t for t in toks if t not in facts.zones]
            if missing:
                warns.append(f"{label}: zone '{', '.join(missing)}' chưa có - tạo bằng 'Security zone' trước (policy/NAT tham chiếu zone chưa có sẽ lỗi khi commit).")
        elif ref == "address":
            missing = [t for t in toks if t.lower() != "any" and not _IPISH.match(t) and t not in facts.addresses and t not in facts.addrsets]
            if missing:
                warns.append(f"{label}: đối tượng địa chỉ '{', '.join(missing)}' chưa có trong address-book - tạo bằng 'Address book' hoặc gõ IP/prefix.")
        elif ref == "application":
            missing = [t for t in toks if t.lower() != "any" and not t.startswith("junos-") and t not in facts.applications]
            if missing:
                warns.append(f"{label}: application '{', '.join(missing)}' chưa có - tạo bằng 'Application' trước.")
        elif ref == "policy":
            fz, tz = str(values.get("from_zone", "")).strip(), str(values.get("to_zone", "")).strip()
            if check == "new":
                if any(p[2] == val and (not fz or p[0] == fz) and (not tz or p[1] == tz) for p in facts.policies):
                    warns.append(f"Policy '{val}' ĐÃ tồn tại giữa hai zone này - lệnh sẽ thay đổi policy hiện có.")
            elif not any(p[2] == val and (not fz or p[0] == fz) and (not tz or p[1] == tz) for p in facts.policies):
                warns.append(f"Không tìm thấy policy '{val}' (zone {fz or '?'} → {tz or '?'}) trên thiết bị.")
        elif ref == "address_obj" and check == "new" and val in facts.addresses:
            warns.append(f"Đối tượng địa chỉ '{val}' ĐÃ tồn tại ({facts.addresses[val]}) - lệnh sẽ ghi đè.")
        elif ref == "application_new" and val in facts.applications:
            warns.append(f"Application '{val}' ĐÃ tồn tại - lệnh sẽ ghi đè.")
        elif ref == "bridge" and facts.bridges:
            missing = [t for t in toks if t not in facts.bridges]
            if missing:
                warns.append(f"{label}: bridge '{', '.join(missing)}' không có trên thiết bị (có: {', '.join(facts.bridges)}).")
    return warns
