"""Chống tự khóa mình: phát hiện lệnh có thể làm mất kết nối quản trị của chính ứng dụng tới thiết bị."""
from __future__ import annotations

import re

from drivers.vendors import VENDORS, get_vendor
from .config_facts import Facts, norm_if, svi_name

_IOS_LIKE = ("ios", "nxos", "cisco_ap", "aruba_os", "tplink", "generic", "comware", "huawei")


def mgmt_interfaces(device: dict, facts: Facts, family: str) -> tuple[list[str], list[str]]:
    """Các giao diện đang giữ IP mà ứng dụng dùng để kết nối, và các VLAN tương ứng. Trả về (tên_giao_diện, vlan_ids)."""
    ip, names, vlans = device["ip"], [], []
    for n, a in facts.ports.items():
        if a.get("ip", "").split("/")[0] == ip:
            names.append(n)
    for n, cidr in facts.l3.items():
        if str(cidr).split("/")[0] == ip and n not in names:
            names.append(n)
    for vid, cidr in facts.svis.items():
        if str(cidr).split("/")[0] == ip:
            names.append(svi_name(family, vid))
            vlans.append(vid)
    return names, vlans


def _ssh_off(c: str) -> bool:
    low = c.lower()
    return bool(re.match(r"^(no ip ssh|no feature ssh|undo stelnet server enable|undo ssh server enable|delete system services ssh)\b", low)
                or re.search(r"transport input (telnet|none)\b", low) or re.search(r"/ip service (disable ssh|set ssh .*disabled=yes)", low))


def _telnet_off(c: str) -> bool:
    low = c.lower()
    return bool(re.match(r"^(no feature telnet|telnet server disable|undo telnet server enable|delete system services telnet)\b", low)
                or re.search(r"transport input ssh\b", low) or re.search(r"/ip service disable telnet", low))


def check(device: dict, facts: Facts, commands: list[str]) -> list[str]:
    """Trả về danh sách cảnh báo (rỗng = không thấy nguy cơ)."""
    if device["vendor"] not in VENDORS:
        return []
    fam = get_vendor(device["vendor"]).family
    names, vlans = mgmt_interfaces(device, facts, fam)
    norm = {norm_if(n) for n in names}
    warns: list[str] = []
    where = f"giao diện quản trị {', '.join(names)} (giữ IP {device['ip']} mà ứng dụng dùng để kết nối)" if names else ""

    def flag(cmd: str, why: str) -> None:
        w = f"⛔ '{cmd}': {why}"
        if w not in warns:
            warns.append(w)

    if fam in _IOS_LIKE:
        neg = "undo " if fam in ("comware", "huawei") else "no "
        cur = ""
        for raw in commands:
            c, low = raw.strip(), raw.strip().lower()
            m = re.match(r"^interface (\S+)$", c, re.I)
            if m:
                cur = norm_if(m.group(1))
                continue
            if low in ("exit", "quit", "end", "return"):
                cur = ""
                continue
            if cur and cur in norm:
                if low == "shutdown" or low.startswith((neg + "ip address", "ip address ", neg + "switchport", "no switchport", "switchport mode",
                                                       "switchport access vlan", "switchport trunk", "ip access-group", "channel-group",
                                                       "port link-type", "port default vlan", "port access vlan", "port trunk")):
                    flag(c, f"thay đổi {where}")
                continue
            m = re.match(rf"^(?:{neg}interface|default interface) (\S+)$", c, re.I)
            if m and norm_if(m.group(1)) in norm:
                flag(c, f"xóa/đặt lại {where}")
            m = re.match(rf"^{neg}vlan (\d+)$", c, re.I)
            if m and m.group(1) in vlans:
                flag(c, f"xóa VLAN {m.group(1)} đang chứa {where}")
    elif fam in ("junos", "junos_srx"):
        for raw in commands:
            c = raw.strip()
            m = re.match(r"^(?:set|delete) interfaces (\S+)(?: unit (\d+))?(.*)$", c)
            if m:
                port = m.group(1) if m.group(1) != "irb" else f"irb.{m.group(2)}"
                hit = port in names or m.group(1) in names or (m.group(1) == "irb" and f"irb.{m.group(2)}" in names)
                rest = m.group(3).strip()
                if hit and (c.startswith("delete") or rest == "disable" or "family inet address" in rest or "vlan members" in rest
                            or "interface-mode" in rest):
                    flag(c, f"thay đổi {where}")
            m = re.match(r"^delete vlans (\S+)$", c)
            if m and any(facts.vlans.get(v) == m.group(1) for v in vlans):
                flag(c, f"xóa VLAN đang chứa {where}")
            m = re.match(r"^delete security zones security-zone (\S+)(?: (interfaces (\S+)|host-inbound-traffic.*))?$", c)
            if m:
                zone_if = {i.split(".")[0] for i in facts.zones.get(m.group(1), [])} | set(facts.zones.get(m.group(1), []))
                if (m.group(3) and (m.group(3) in names or m.group(3).split(".")[0] in names)) or \
                        (not m.group(2) and any(n in zone_if for n in names)) or (m.group(2) and m.group(2).startswith("host-inbound")):
                    flag(c, f"zone chứa {where} - bỏ zone/dịch vụ quản trị sẽ chặn kết nối")
    elif fam == "mikrotik":
        for raw in commands:
            c = raw.strip()
            if re.search(r"^/interface (disable|remove)\b", c) or re.search(r"^/ip address (remove|disable)\b", c):
                flag(c, "có thể tắt/xóa giao diện hoặc địa chỉ đang dùng để quản trị")
            m = re.search(r"interface=(\S+)\]?.*\bpvid=", c)
            if m and norm_if(m.group(1)) in norm:
                flag(c, f"đổi VLAN của {where}")
    proto = (device.get("protocol") or "ssh").lower()
    for raw in commands:
        c = raw.strip()
        if proto == "ssh" and _ssh_off(c):
            flag(c, "tắt SSH trong khi ứng dụng đang kết nối bằng SSH")
        if proto == "telnet" and _telnet_off(c):
            flag(c, "tắt Telnet trong khi ứng dụng đang kết nối bằng Telnet")
    return warns
