"""Bộ mô phỏng thiết bị theo từng hãng (dùng cho 'thiết bị giả lập').

Mỗi bộ mô phỏng hiểu cú pháp lệnh và định dạng cấu hình của một họ thiết bị:
  - IosSim (Cisco IOS/XE/AP, NX-OS, Aruba, Comware, Huawei, TP-Link...): cấu hình thụt lề, khối interface/vlan..., no/undo
  - JunosSim: lệnh `set`/`delete`, chỉ áp dụng khi không lỗi (giống commit)
  - MikroTikSim: lệnh `/đường dẫn add|set|remove ...`, xuất cấu hình theo từng nhánh
  - OpenWrtSim: lệnh `uci set/commit`
  - FortinetSim: khối config/edit/set/next/end
Trạng thái của thiết bị là danh sách dòng văn bản (state) -> lưu được ra file JSON.
"""
from __future__ import annotations

import ipaddress
import re
from abc import ABC, abstractmethod
from typing import Optional

from .vendors import Vendor


def norm_cmd(cmd: str) -> str:
    n = " ".join(cmd.strip().split()).lower()
    if n.startswith("sh "):
        n = "show " + n[3:]
    return "show running-config" if n in ("show run", "show running") else n


def apply_pipes(text: str, pipes: list[str]) -> str:
    """Mô phỏng các bộ lọc sau dấu | : include/match/grep, exclude/except, section, begin, count (display/no-more bỏ qua)."""
    lines = text.split("\n")
    for pipe in pipes:
        kw, _, arg = pipe.strip().partition(" ")
        kw, arg = kw.lower(), arg.strip()
        try:
            rx = re.compile(arg, re.I) if arg else None
        except re.error:
            rx = re.compile(re.escape(arg), re.I)
        if kw in ("include", "inc", "grep", "match") and rx:
            lines = [ln for ln in lines if rx.search(ln)]
        elif kw in ("exclude", "except", "ex", "e") and rx:
            lines = [ln for ln in lines if not rx.search(ln)]
        elif kw in ("begin", "bg") and rx:
            idx = next((i for i, ln in enumerate(lines) if rx.search(ln)), None)
            lines = lines[idx:] if idx is not None else []
        elif kw in ("section", "sec") and rx:
            blocks, cur = [], []
            for ln in lines:
                if ln and not ln.startswith(" ") and cur:
                    blocks.append(cur)
                    cur = []
                cur.append(ln)
            blocks.append(cur)
            lines = [ln for b in blocks if b and rx.search(b[0]) for ln in b]
        elif kw == "count":
            lines = [f"Count: {len(lines)} lines"]
    return "\n".join(lines)


class Simulator(ABC):
    def __init__(self, vendor: Vendor, name: str, model: str = ""):
        self.vendor, self.name, self.model = vendor, name, model

    @abstractmethod
    def baseline(self) -> list[str]: ...

    @abstractmethod
    def apply(self, state: list[str], commands: list[str]) -> tuple[list[str], str]:
        """Áp dụng lệnh. Trả về (trạng thái mới, output của thiết bị)."""

    def show_config(self, state: list[str]) -> str:
        return "\n".join(state)

    def version_text(self) -> str:
        return f"{self.vendor.label} (giả lập)"

    def show(self, command: str, state: list[str]) -> str:
        return (f"(giả lập) Lệnh '{command}' chưa được mô phỏng. Thử: lệnh xem cấu hình của hãng này, hoặc các lệnh trong "
                "danh sách 'Lệnh gợi ý' của tab Công cụ.")

    def is_config_cmd(self, base: str) -> bool:
        return norm_cmd(base) == norm_cmd(self.vendor.backup_cmd.split("|")[0])

    def bad_trigger(self, cmd: str) -> bool:
        """Tên thiết bị chứa 'badcmd' -> mô phỏng lỗi với các lệnh SNMP."""
        return "badcmd" in self.name.lower() and bool(re.match(r"^(set snmp|/snmp|snmp|uci set snmp)", cmd))


# =====================================================================
#                        Họ IOS (thụt lề, khối, no/undo)
# =====================================================================
class Node:
    __slots__ = ("text", "children")

    def __init__(self, text: str):
        self.text, self.children = text, []


def parse_nodes(lines: list[str]) -> list[Node]:
    root: list[Node] = []
    stack: list[tuple[int, Node]] = []
    for raw in lines:
        s = raw.rstrip()
        t = s.strip()
        if not t or t[0] in "!#" or t == "end":
            continue
        indent = len(s) - len(s.lstrip(" "))
        node = Node(t)
        while stack and stack[-1][0] >= indent:
            stack.pop()
        (stack[-1][1].children if stack else root).append(node)
        stack.append((indent, node))
    return root


def render_nodes(nodes: list[Node], sep: str) -> list[str]:
    out: list[str] = []

    def walk(n: Node, depth: int) -> None:
        out.append(" " * depth + n.text)
        for c in n.children:
            walk(c, depth + 1)

    for n in nodes:
        walk(n, 0)
        if n.children and sep:
            out.append(sep)
    return out


def _find(nodes: list[Node], text: str) -> Optional[Node]:
    return next((n for n in nodes if n.text == text), None)


class IosSim(Simulator):
    NEG, SEP = "no", "!"
    EXITS, ENDS = ("exit", "quit"), ("end", "return")
    ERR = "% Invalid input detected at '^' marker."
    INVALID_FIRST: tuple = ("set", "delete", "undo", "sysname", "display", "uci")
    BLOCK = re.compile(r"^(interface \S+|vlan \d+|line \S+.*|dot11 ssid \S+|router \S+.*|ip access-list \S+ \S+|"
                       r"radius server \S+|ip dhcp pool \S+)$")
    NESTED: Optional[re.Pattern] = None
    REPLACE = ("hostname ", "description ", "switchport access vlan", "switchport mode", "switchport trunk allowed vlan",
               "switchport trunk native vlan", "name ", "ip domain-name", "ip address ", "spanning-tree mode",
               "banner motd", "clock timezone", "channel-group ")
    NEG_STORED = ("switchport", "lldp run", "cdp run", "ip http server", "ip http secure-server")
    VERSION = "Cisco IOS Software, Catalyst L3 Switch Software, Version 15.2(7)E8, RELEASE SOFTWARE (fc2)"

    def baseline(self) -> list[str]:
        return self._render(parse_nodes([
            f"hostname {self.name}", "vlan 1", " name default",
            "interface GigabitEthernet0/1", " description uplink", " switchport mode trunk", " switchport trunk allowed vlan 1",
            "interface GigabitEthernet0/2", " switchport mode access", " switchport access vlan 1",
            "interface GigabitEthernet0/3", " switchport mode access", " switchport access vlan 1",
            "ntp server 10.0.0.1"]))

    def _render(self, nodes: list[Node]) -> list[str]:
        return render_nodes(nodes, self.SEP)

    def show_config(self, state: list[str]) -> str:
        return "Building configuration...\n" + "\n".join(state) + "\nend"

    def version_text(self) -> str:
        return self.VERSION

    def _err(self, cmd: str) -> str:
        return f"{self.ERR} <- '{cmd}'"

    def is_config_cmd(self, base: str) -> bool:
        return norm_cmd(base) in ("show startup-config", "display saved-configuration") or super().is_config_cmd(base)

    def show(self, command: str, state: list[str]) -> str:
        out = _ios_show(self, norm_cmd(command), state)
        return out if out is not None else super().show(command, state)

    def apply(self, state: list[str], commands: list[str]) -> tuple[list[str], str]:
        root = parse_nodes(state)
        path: list[Node] = []
        out: list[str] = []
        for raw in commands:
            cmd = raw.strip()
            if not cmd:
                continue
            first = cmd.split()[0].lower()
            if first in self.INVALID_FIRST or cmd.startswith("/") or (self.NEG == "undo" and first == "no") \
                    or self.bad_trigger(cmd):
                out.append(self._err(cmd))
                continue
            if cmd in self.ENDS:
                path.clear()
                continue
            if cmd in self.EXITS:
                if path:
                    path.pop()
                continue
            container = path[-1].children if path else root
            if cmd.startswith(self.NEG + " "):
                target = cmd[len(self.NEG) + 1:].strip()
                container[:] = [n for n in container if not (n.text == target or n.text.startswith(target + " "))]
                if target in self.NEG_STORED and not any(n.text == cmd for n in container):
                    container.append(Node(cmd))
                continue
            if self.BLOCK.match(cmd):
                path.clear()
                node = _find(root, cmd)
                if node is None:
                    node = Node(cmd)
                    root.append(node)
                path.append(node)
                continue
            if self.NESTED and path and self.NESTED.match(cmd):
                node = _find(path[-1].children, cmd)
                if node is None:
                    node = Node(cmd)
                    path[-1].children.append(node)
                path.append(node)
                continue
            idx = None                                  # lệnh thay thế giữ nguyên vị trí cũ
            for pre in self.REPLACE:
                if cmd.startswith(pre):
                    hits = [i for i, n in enumerate(container) if n.text.startswith(pre)]
                    if hits:
                        idx = hits[0]
                        container[:] = [n for n in container if not n.text.startswith(pre)]
                    break
            container[:] = [n for n in container if n.text != f"{self.NEG} {cmd}"]
            if not any(n.text == cmd for n in container):
                if idx is not None:
                    container.insert(min(idx, len(container)), Node(cmd))
                else:
                    container.append(Node(cmd))
        return self._render(root), "\n".join(out)


def _ios_ifaces(nodes: list[Node]) -> list[tuple]:
    """[(tên, cidr hoặc None, shutdown, vlan access hoặc None)] từ cấu hình thụt lề."""
    out = []
    for n in nodes:
        if not n.text.startswith("interface "):
            continue
        cidr, shut, vlan = None, False, None
        for c in n.children:
            t = c.text
            m = re.match(r"ip address (\S+) (\S+)$", t) or re.match(r"ip address (\S+)$", t)
            if m and m.group(1) != "dhcp":
                try:
                    cidr = ipaddress.ip_interface(f"{m.group(1)}/{m.group(2)}" if m.lastindex == 2 else m.group(1))
                except ValueError:
                    pass
            if t == "shutdown":
                shut = True
            m = re.match(r"(?:switchport access vlan|port default vlan|port access vlan) (\d+)$", t)
            if m:
                vlan = m.group(1)
        out.append((n.text.split(None, 1)[1], cidr, shut, vlan))
    return out


def _short(name: str) -> str:
    return re.sub(r"^GigabitEthernet", "Gi", re.sub(r"^Ethernet", "Eth", name))


def _ios_show(sim: "IosSim", n: str, state: list[str]) -> Optional[str]:
    nodes = parse_nodes(state)
    m = re.match(r"^(?:show running-config|display current-configuration) interface (\S+)$", n)
    if m:
        want = m.group(1).lower()
        blk = next((x for x in nodes if x.text.lower() == f"interface {want}"), None)
        return "\n".join(render_nodes([blk], "")) if blk else f"% Invalid input detected: interface {m.group(1)}"
    if n in ("show vlan brief", "show vlan", "show vlans", "display vlan"):
        ifs = _ios_ifaces(nodes)
        rows = ["VLAN Name                             Status    Ports", "---- -------------------------------- --------- ----------------------"]
        for v in nodes:
            if v.text.startswith("vlan ") and v.text.split()[1].isdigit():
                vid = v.text.split()[1]
                name = next((c.text[5:] for c in v.children if c.text.startswith("name ")), f"VLAN{int(vid):04d}").strip('"')
                ports = ", ".join(_short(i[0]) for i in ifs if i[3] == vid)
                rows.append(f"{vid:<4} {name:<32} {'active':<9} {ports}")
        return "\n".join(rows)
    if n in ("show ip interface brief", "show interfaces status", "show interface brief", "display ip interface brief"):
        rows = ["Interface                  IP-Address        Status                 Protocol"]
        for name, cidr, shut, _v in _ios_ifaces(nodes):
            rows.append(f"{name:<26} {str(cidr.ip) if cidr else 'unassigned':<17} {'administratively down' if shut else 'up':<22} {'down' if shut else 'up'}")
        return "\n".join(rows)
    if n in ("show ip route", "show route"):
        rows = ["Codes: C - connected, S - static", ""]
        for name, cidr, shut, _v in _ios_ifaces(nodes):
            if cidr and not shut:
                rows.append(f"C    {cidr.network} is directly connected, {name}")
        for t in (x.text for x in nodes):
            m = re.match(r"ip route (\S+) (\S+) (\S+)(?: (\d+))?$", t)
            if m:
                try:
                    net = ipaddress.ip_network(f"{m.group(1)}/{m.group(2)}")
                except ValueError:
                    continue
                rows.append(f"S    {net} [{m.group(4) or 1}/0] via {m.group(3)}")
                continue
            m = re.match(r"ip route (\S+/\d+) (\S+)(?: (\d+))?$", t)       # NX-OS
            if m:
                rows.append(f"S    {m.group(1)} [{m.group(3) or 1}/0] via {m.group(2)}")
        return "\n".join(rows)
    return None


class NxosSim(IosSim):
    ERR = "% Invalid command at '^' marker."
    BLOCK = re.compile(r"^(interface \S+|vlan \d+|line \S+|router \S+.*|ip access-list \S+)$")
    NESTED = re.compile(r"^(hsrp \d+|neighbor \S+|address-family \S+ \S+)$")
    VERSION = "Cisco Nexus Operating System (NX-OS) Software\nNXOS: version 9.3(8)"

    def baseline(self) -> list[str]:
        return self._render(parse_nodes([
            f"hostname {self.name}", "feature ssh", "vlan 1",
            "interface Ethernet1/1", " switchport", " switchport mode trunk",
            "interface Ethernet1/2", " switchport", " switchport access vlan 1",
            "interface Ethernet1/3", " switchport", " switchport access vlan 1",
            "interface mgmt0", " ip address 192.168.100.10/24", "ntp server 10.0.0.1"]))


class CiscoApSim(IosSim):
    VERSION = "Cisco IOS Software, C3700 Software (AP3G2-K9W7-M), Version 15.3(3)JD"

    def baseline(self) -> list[str]:
        return self._render(parse_nodes([
            f"hostname {self.name}", "interface Dot11Radio0", " shutdown", "interface GigabitEthernet0", " no ip address"]))


class ArubaSim(IosSim):
    ERR = "Invalid input: command"
    BLOCK = re.compile(r"^(interface \S+|vlan \d+)$")
    VERSION = "Image stamp: HP ProCurve\nSoftware revision  : WC.16.11.0012"

    def baseline(self) -> list[str]:
        return self._render(parse_nodes([
            f'hostname "{self.name}"', "vlan 1", ' name "DEFAULT_VLAN"', "interface 1", ' name "uplink"',
            "sntp server priority 1 10.0.0.1"]))


class ComwareSim(IosSim):
    NEG, SEP = "undo", "#"
    EXITS, ENDS = ("quit", "exit"), ("return",)
    ERR = "% Unrecognized command found at '^' position."
    INVALID_FIRST = ("set", "delete", "hostname", "show", "uci")
    BLOCK = re.compile(r"^(interface \S+|vlan \d+|user-interface .+|line vty .+|ospf \d+|acl .+)$")
    REPLACE = ("sysname ", "description ", "port access vlan", "port default vlan", "port link-type", "name ",
               "port trunk pvid vlan")
    NEG_STORED = ()
    VERSION = "H3C Comware Software, Version 7.1.070, Release 6616P05"

    def baseline(self) -> list[str]:
        return self._render(parse_nodes([
            f"sysname {self.name}", "vlan 1", "interface GigabitEthernet1/0/1", " port link-type trunk",
            "interface GigabitEthernet1/0/2", " port link-type access", " port access vlan 1",
            "interface GigabitEthernet1/0/3", " port link-type access", " port access vlan 1"]))

    def show_config(self, state: list[str]) -> str:
        return "#\n" + "\n".join(state) + "\n#\nreturn"


class HuaweiSim(ComwareSim):
    ERR = "Error: Unrecognized command found at '^' position."
    VERSION = "Huawei Versatile Routing Platform Software\nVRP (R) software, Version 5.170 (S5735 V200R021C10SPC600)"

    def baseline(self) -> list[str]:
        return self._render(parse_nodes([
            f"sysname {self.name}", "vlan 1", "interface GigabitEthernet0/0/1", " port link-type trunk",
            "interface GigabitEthernet0/0/2", " port link-type access", " port default vlan 1",
            "interface GigabitEthernet0/0/3", " port link-type access", " port default vlan 1"]))


class TplinkSim(IosSim):
    ERR = "Error: invalid command."
    BLOCK = re.compile(r"^(interface \S+ \S+|vlan \d+)$")
    REPLACE = ("description ", "switchport pvid", "name ")
    VERSION = "Hardware Version: TL-SG3428 3.0\nFirmware Version: 3.0.2 Build 20230220 Rel.51234"

    def baseline(self) -> list[str]:
        return self._render(parse_nodes([
            "vlan 1", "interface gigabitEthernet 1/0/1", " switchport general allowed vlan 1 untagged", " switchport pvid 1"]))


# =====================================================================
#                                 Junos
# =====================================================================
class JunosSim(Simulator):
    SORT = True
    SINGLE = [re.compile(p) for p in (
        r"^(set system host-name)\s", r"^(set system domain-name)\s", r"^(set system time-zone)\s",
        r"^(set system login message)\s", r"^(set vlans \S+ vlan-id)\s", r"^(set interfaces \S+ description)\s",
        r"^(set interfaces \S+ unit \d+ description)\s", r"^(set interfaces \S+ unit \d+ family ethernet-switching interface-mode)\s",
        r"^(set protocols rstp bridge-priority)\s", r"^(set interfaces \S+ native-vlan-id)\s",
        r"^(set routing-options router-id)\s", r"^(set snmp location)\s", r"^(set snmp contact)\s",
        r"^(set system authentication-order)\s")]

    def baseline(self) -> list[str]:
        return sorted([
            f"set system host-name {self.name}", "set system services ssh", "set system services telnet",
            "set system login user admin class super-user", "set vlans default vlan-id 1",
            "set interfaces ge-0/0/0 unit 0 family ethernet-switching",
            "set interfaces ge-0/0/1 unit 0 family ethernet-switching",
            "set interfaces ge-0/0/2 unit 0 family ethernet-switching"])

    def version_text(self) -> str:
        return f"Hostname: {self.name}\nModel: {self.model or 'ex4300-48t'}\nJunos: 20.4R3.8"

    def is_config_cmd(self, base: str) -> bool:
        return norm_cmd(base) in ("show configuration", "show config")

    @staticmethod
    def _addrs(cfg: list[str]) -> list[tuple[str, str, str]]:
        out = []
        for ln in cfg:
            m = re.match(r"^set interfaces (\S+) unit (\d+) family inet address (\S+)", ln)
            if m and (m.group(1), m.group(2), m.group(3)) not in out:
                out.append((m.group(1), m.group(2), m.group(3)))
        return out

    def show(self, command: str, state: list[str]) -> str:
        n = norm_cmd(command)
        m = re.match(r"^show configuration (.+)$", n)
        if m:        # 'show configuration security policies' -> các dòng set thuộc nhánh đó (dạng display set)
            pre = ("set " + m.group(1)).lower()
            hits = [ln for ln in state if ln.lower() == pre or ln.lower().startswith(pre + " ")]
            return "\n".join(hits) if hits else "(trống - không có cấu hình ở nhánh này)"
        if n in ("show vlans", "show vlan"):
            rows = ["Routing instance  VLAN name       Tag   Interfaces"]
            for ln in state:
                v = re.match(r"^set vlans (\S+) vlan-id (\d+)$", ln)
                if v:
                    members = [re.match(r"^set interfaces (\S+) ", x).group(1) for x in state
                               if re.search(r"vlan members (\[ )?(.* )?(" + re.escape(v.group(1)) + "|" + v.group(2) + r")( \])?$", x)]
                    rows.append(f"default-switch    {v.group(1):<14} {v.group(2):<5} {', '.join(members)}")
            return "\n".join(rows)
        if n == "show interfaces terse":
            rows = ["Interface               Admin Link Proto    Local                 Remote"]
            names = []
            for ln in state:
                m2 = re.match(r"^set interfaces (\S+) ", ln)
                if m2 and m2.group(1) not in names:
                    names.append(m2.group(1))
            adrs = self._addrs(state)
            for nm in names:
                down = f"set interfaces {nm} disable" in state
                rows.append(f"{nm:<23} {'down' if down else 'up':<5} {'down' if down else 'up':<4}")
                for (i, u, a) in adrs:
                    if i == nm:
                        rows.append(f"{nm + '.' + u:<23} {'down' if down else 'up':<5} {'down' if down else 'up':<4} inet     {a}")
            return "\n".join(rows)
        if n == "show route":
            rows = []
            for (i, u, a) in self._addrs(state):
                net = ipaddress.ip_interface(a)
                rows.append(f"{str(net.network):<20} *[Direct/0] via {i}.{u}")
                rows.append(f"{str(net.ip) + '/32':<20} *[Local/0] Local via {i}.{u}")
            for ln in state:
                r = re.match(r"^set routing-options static route (\S+) next-hop (\S+)(?: preference (\d+))?", ln)
                if r:
                    rows.append(f"{r.group(1):<20} *[Static/{r.group(3) or 5}] > to {r.group(2)}")
            return "inet.0: " + str(len(rows)) + " destinations\n" + "\n".join(rows)
        return super().show(command, state)

    def apply(self, state: list[str], commands: list[str]) -> tuple[list[str], str]:
        cfg, out, failed = list(state), [], False
        for raw in commands:
            cmd = raw.strip()
            if not cmd:
                continue
            word = cmd.split()[0]
            if self.bad_trigger(cmd):
                out.append(f"error: syntax error, expecting <command>: {cmd}")
                failed = True
            elif word == "set" and len(cmd.split()) > 1:
                for rx in self.SINGLE:
                    m = rx.match(cmd)
                    if m:
                        pre = m.group(1)
                        cfg = [ln for ln in cfg if not (ln == pre or ln.startswith(pre + " "))]
                        break
                if cmd not in cfg:
                    cfg.append(cmd)
            elif word == "delete" and len(cmd.split()) > 1:
                target = "set " + cmd[7:].strip()
                keep = [ln for ln in cfg if not (ln == target or ln.startswith(target + " "))]
                if len(keep) == len(cfg):
                    out.append("warning: statement not found")
                cfg = keep
            elif word == "insert":
                m = re.match(r"^insert security policies from-zone (\S+) to-zone (\S+) policy (\S+) (before|after) policy (\S+)$", cmd)
                if not m:
                    out.append(f"error: syntax error, unknown command: {cmd}")
                    failed = True
                    continue
                fz, tz, new, where, ref = m.groups()
                pre = f"set security policies from-zone {fz} to-zone {tz} policy "
                mine = [ln for ln in cfg if ln.startswith(pre + new + " ")]
                if not mine or not any(ln.startswith(pre + ref + " ") for ln in cfg):
                    out.append(f"error: policy '{new if not mine else ref}' không tồn tại giữa zone {fz} -> {tz}")
                    failed = True
                    continue
                cfg = [ln for ln in cfg if ln not in mine]
                idxs = [i for i, ln in enumerate(cfg) if ln.startswith(pre + ref + " ")]
                at = idxs[0] if where == "before" else idxs[-1] + 1
                cfg[at:at] = mine
            elif cmd in ("rollback 0", "commit", "commit check"):
                pass
            else:
                out.append(f"error: syntax error, unknown command: {cmd}")
                failed = True
        if failed:
            return state, "\n".join(out)           # giống Junos: có lỗi thì không commit
        return (sorted(cfg) if self.SORT else cfg), "\n".join(out)


class JunosSrxSim(JunosSim):
    """Juniper SRX: có zone / address-book / policy / NAT và kiểm tra tham chiếu khi commit như firewall thật."""
    SORT = False          # thứ tự policy quan trọng -> giữ thứ tự tạo / insert

    SINGLE = JunosSim.SINGLE + [re.compile(p) for p in (
        r"^(set security zones security-zone \S+ description)\s",
        r"^(set security nat destination pool \S+ address)\s",
    )]
    POLICY_ACTION = re.compile(r"^(set security policies from-zone \S+ to-zone \S+ policy \S+ then) (permit|deny|reject)\b")

    def baseline(self) -> list[str]:
        pol = "set security policies from-zone trust to-zone untrust policy default-permit"
        return sorted([
            f"set system host-name {self.name}", "set system services ssh", "set system login user admin class super-user",
            "set interfaces ge-0/0/0 unit 0 family inet address 203.0.113.2/30",
            "set interfaces ge-0/0/1 unit 0 family inet address 192.168.1.1/24",
            "set security zones security-zone untrust interfaces ge-0/0/0.0",
            "set security zones security-zone trust interfaces ge-0/0/1.0",
            "set security zones security-zone trust host-inbound-traffic system-services ping",
            "set security zones security-zone trust host-inbound-traffic system-services ssh",
            f"{pol} match source-address any", f"{pol} match destination-address any", f"{pol} match application any",
            f"{pol} then permit", "set routing-options static route 0.0.0.0/0 next-hop 203.0.113.1"])

    def version_text(self) -> str:
        return f"Hostname: {self.name}\nModel: {self.model or 'srx300'}\nJunos: 20.4R3-S2.2"

    def apply(self, state: list[str], commands: list[str]) -> tuple[list[str], str]:
        cmds = []
        for c in commands:
            c = c.strip()
            m = self.POLICY_ACTION.match(c)
            if m:    # đổi hành động policy -> thay thế hành động cũ (permit/deny/reject)
                state = [ln for ln in state if not re.match(re.escape(m.group(1)) + r" (permit|deny|reject)\b", ln)]
            cmds.append(c)
        new_state, out = super().apply(state, cmds)
        if out and "error:" in out:
            return state, out
        problems = self._check(new_state)
        if problems:
            return state, "\n".join(["error: configuration check-out failed"] + [f"error: {p}" for p in problems])
        return new_state, out

    def show(self, command: str, state: list[str]) -> str:
        n = norm_cmd(command)
        if n == "show security policies":
            pol: dict[tuple, dict] = {}
            for ln in state:
                m = re.match(r"^set security policies from-zone (\S+) to-zone (\S+) policy (\S+) (match|then) (.+)$", ln)
                if not m:
                    continue
                d = pol.setdefault((m.group(1), m.group(2), m.group(3)), {"src": [], "dst": [], "app": [], "act": "?", "log": False})
                kind, val = m.group(4), m.group(5)
                toks = val.replace("[", " ").replace("]", " ").split()
                if kind == "match":
                    key, _, rest = val.partition(" ")
                    d[{"source-address": "src", "destination-address": "dst", "application": "app"}.get(key, "app")] += rest.replace("[", " ").replace("]", " ").split()
                elif toks[0] in ("permit", "deny", "reject"):
                    d["act"] = toks[0]
                elif toks[0] == "log":
                    d["log"] = True
            rows = ["Default policy: deny-all"]
            order: list[tuple] = []
            for (fz, tz, _n) in pol:
                if (fz, tz) not in order:
                    order.append((fz, tz))
            for fz0, tz0 in order:
                rows.append(f"From zone: {fz0}, To zone: {tz0}")
                for (fz, tz, name), d in pol.items():
                    if (fz, tz) != (fz0, tz0):
                        continue
                    rows += [f"  Policy: {name}, action-type: {d['act']}, State: enabled" + (", Logging: session-init/close" if d["log"] else ""),
                             f"    Source addresses: {', '.join(d['src']) or '-'}", f"    Destination addresses: {', '.join(d['dst']) or '-'}",
                             f"    Applications: {', '.join(d['app']) or '-'}"]
            return "\n".join(rows)
        if n == "show security zones":
            zones: dict[str, dict] = {}
            for ln in state:
                m = re.match(r"^set security zones security-zone (\S+) (interfaces|host-inbound-traffic system-services|description) (.+)$", ln)
                if m:
                    z = zones.setdefault(m.group(1), {"if": [], "svc": []})
                    if m.group(2) == "interfaces":
                        z["if"].append(m.group(3))
                    elif m.group(2).startswith("host"):
                        z["svc"].append(m.group(3))
            rows = []
            for name, z in sorted(zones.items()):
                rows += [f"Security zone: {name}", f"  Interfaces bound: {len(z['if'])}", "  Interfaces:"] + [f"    {i}" for i in z["if"]]
                rows.append(f"  Host-inbound services: {', '.join(z['svc']) or 'không có'}")
            return "\n".join(rows)
        m = re.match(r"^show security nat (source|destination)( rule all)?$", n)
        if m:
            hits = [ln for ln in state if ln.startswith(f"set security nat {m.group(1)}")]
            return "\n".join(hits) if hits else "Không có cấu hình NAT."
        return super().show(command, state)

    @staticmethod
    def _check(cfg: list[str]) -> list[str]:
        zones = {m.group(1) for ln in cfg for m in [re.match(r"set security zones security-zone (\S+)", ln)] if m}
        addrs = {m.group(1) for ln in cfg for m in [re.match(r"set security address-book \S+ address (\S+) \S+$", ln)] if m}
        sets = {m.group(1) for ln in cfg for m in [re.match(r"set security address-book \S+ address-set (\S+) ", ln)] if m}
        apps = {m.group(1) for ln in cfg for m in [re.match(r"set applications application (\S+)", ln)] if m}
        out: list[str] = []
        rx = re.compile(r"^set security policies from-zone (\S+) to-zone (\S+) policy (\S+) match (source-address|destination-address|application) (.+)$")
        for ln in cfg:
            m = rx.match(ln)
            if not m:
                continue
            fz, tz, pol, kind, val = m.groups()
            for z in (fz, tz):
                if z not in zones:
                    out.append(f"policy {pol}: zone '{z}' chưa được định nghĩa (security-zone)")
            for tok in val.replace("[", " ").replace("]", " ").split():
                if kind == "application":
                    if tok != "any" and not tok.startswith("junos-") and tok not in apps:
                        out.append(f"policy {pol}: application '{tok}' chưa được định nghĩa")
                elif tok != "any" and tok not in addrs and tok not in sets:
                    out.append(f"policy {pol}: {kind} '{tok}' chưa có trong address-book")
        return sorted(set(out))


# =====================================================================
#                               MikroTik
# =====================================================================
_MT_VERBS = ("add", "set", "remove", "enable", "disable", "print", "export", "get", "find", "unset")
_MT_SPLIT = re.compile(r"^(/\S.*?)\s+(" + "|".join(_MT_VERBS) + r")\b\s*(.*)$")
_MT_TOKENS = re.compile(r'(?:[^\s"\[]|"[^"]*"|\[[^\]]*\])+')


def _kv(tokens: list[str]) -> dict[str, str]:
    return {t.split("=", 1)[0]: t.split("=", 1)[1] for t in tokens if "=" in t and not t.startswith("[")}


def _merge_kv(line: str, updates: dict[str, str]) -> str:
    head, *rest = _MT_TOKENS.findall(line)
    pairs = _kv(rest)
    pairs.update(updates)
    keep = [t for t in rest if t.startswith("[") or "=" not in t]      # giữ định danh mục (vd 'telnet') và bộ lọc [find ...]
    return " ".join([head] + keep + [f"{k}={v}" for k, v in pairs.items()])


class MikroTikSim(Simulator):
    def baseline(self) -> list[str]:
        return ["/interface bridge", "add name=bridge", "/interface bridge port", "add bridge=bridge interface=ether2",
                "add bridge=bridge interface=ether3", "add bridge=bridge interface=ether4", "/interface wireless",
                "set [ find default-name=wlan1 ] disabled=yes mode=ap-bridge", "/system identity", f"set name={self.name}",
                "/ip service", "set telnet disabled=no"]

    def show_config(self, state: list[str]) -> str:
        return "# oct/24/2026 12:00:00 by RouterOS 7.11.2\n# software id = SIM0-0001\n#\n" + "\n".join(state)

    def version_text(self) -> str:
        return f"uptime: 1d2h\nversion: 7.11.2 (stable)\nboard-name: {self.model or 'RB750Gr3'}\nplatform: MikroTik"

    def is_config_cmd(self, base: str) -> bool:
        return norm_cmd(base).startswith("/export")

    def show(self, command: str, state: list[str]) -> str:
        n = norm_cmd(command)
        m = re.match(r"^(/\S.*?)\s+print\b.*$", n)
        if not m:
            return super().show(command, state)
        path = m.group(1)
        sec = {k.lower(): v for k, v in self._to_sections(state).items()}
        if path == "/interface":
            names = [f"ether{i}" for i in range(1, 6)] + [self._attrs(x).get("name", "") for x in sec.get("/interface bridge", []) if x.startswith("add")]
            rows = ["Flags: R - RUNNING", " #    NAME      TYPE"] + [f"{i:>2} R  {nm:<9} {'bridge' if nm.startswith('bridge') else 'ether'}" for i, nm in enumerate(names) if nm]
            return "\n".join(rows)
        items = sec.get(path)
        if not items:
            return "(không có mục nào)"
        return "\n".join(f"{i:>2}  {x[4:] if x.startswith('add ') else x}" for i, x in enumerate(items))

    @staticmethod
    def _to_sections(state: list[str]) -> dict[str, list[str]]:
        sec: dict[str, list[str]] = {}
        cur = None
        for ln in state:
            if ln.startswith("/"):
                cur = ln
                sec.setdefault(cur, [])
            elif cur is not None and ln.strip():
                sec[cur].append(ln.strip())
        return sec

    @staticmethod
    def _find_conds(tok: str) -> dict[str, str]:
        """'[find interface=ether2]' hoặc '[ find default-name=wlan1 ]' -> {'interface': 'ether2'}"""
        inner = re.sub(r"^\s*find\s*", "", tok.strip()[1:-1].strip())
        return _kv(_MT_TOKENS.findall(inner))

    @staticmethod
    def _attrs(line: str) -> dict[str, str]:
        have: dict[str, str] = {}
        for t in _MT_TOKENS.findall(line)[1:]:
            if t.startswith("["):
                have.update(MikroTikSim._find_conds(t))
            elif "=" in t:
                k, v = t.split("=", 1)
                have[k] = v
        return have

    @staticmethod
    def _matches(line: str, conds: dict[str, str]) -> bool:
        have = MikroTikSim._attrs(line)
        return all(have.get(k) == v for k, v in conds.items())

    def apply(self, state: list[str], commands: list[str]) -> tuple[list[str], str]:
        sec, out = self._to_sections(state), []
        for raw in commands:
            cmd = raw.strip()
            if not cmd:
                continue
            m = _MT_SPLIT.match(cmd)
            if not cmd.startswith("/") or not m:
                out.append(f"bad command name {cmd.split()[0].lstrip('/')} (line 1 column 1)")
                continue
            if self.bad_trigger(cmd):
                out.append("failure: not enough permissions (9)")
                continue
            path, verb, args = m.group(1).strip(), m.group(2), m.group(3)
            tokens = _MT_TOKENS.findall(args)
            items = sec.setdefault(path, [])
            if verb == "add":
                line = " ".join(["add"] + tokens)
                kv = _kv(tokens)
                dup = line in items
                if "name" in kv and any(self._attrs(i).get("name") == kv["name"] for i in items if i.startswith("add")):
                    dup = True
                if path.endswith("bridge vlan") and any(
                        (self._attrs(i).get("bridge"), self._attrs(i).get("vlan-ids")) ==
                        (kv.get("bridge"), kv.get("vlan-ids")) for i in items if i.startswith("add")):
                    dup = True
                if dup:
                    out.append("failure: already have such entry")
                else:
                    items.append(line)
            elif verb in ("set", "enable", "disable", "unset"):
                updates = _kv(tokens)
                if verb in ("enable", "disable"):
                    updates = {"disabled": "no" if verb == "enable" else "yes"}
                if tokens and not tokens[0].startswith("[") and "=" not in tokens[0]:      # vd: /ip service disable telnet
                    nm = tokens[0]
                    idx = next((i for i, ln in enumerate(items) if ln.split()[:2] == ["set", nm]), None)
                    if idx is None:
                        items.append(" ".join(["set", nm] + [f"{k}={v}" for k, v in updates.items()]))
                    else:
                        items[idx] = _merge_kv(items[idx], updates)
                    sec[path] = items
                    continue
                if tokens and tokens[0].startswith("["):
                    conds = self._find_conds(tokens[0])
                    hit = [i for i, ln in enumerate(items) if self._matches(ln, conds)]
                    if not hit:
                        out.append("failure: no such item")
                        continue
                    for i in hit:
                        items[i] = _merge_kv(items[i], updates)
                else:
                    idx = next((i for i, ln in enumerate(items) if ln.startswith("set ")), None)
                    if idx is None:
                        items.append(" ".join(["set"] + [f"{k}={v}" for k, v in updates.items()]))
                    else:
                        items[idx] = _merge_kv(items[idx], updates)
            elif verb == "remove":
                conds = self._find_conds(tokens[0]) if tokens and tokens[0].startswith("[") else {}
                keep = [ln for ln in items if not (conds and self._matches(ln, conds))]
                if len(keep) == len(items):
                    out.append("failure: no such item")
                items[:] = keep
            sec[path] = items
        new_state: list[str] = []
        for path, items in sec.items():
            if items:
                new_state.append(path)
                new_state.extend(items)
        return new_state, "\n".join(out)


# =====================================================================
#                                OpenWrt
# =====================================================================
class OpenWrtSim(Simulator):
    def baseline(self) -> list[str]:
        return [f"system.@system[0].hostname='{self.name}'", "wireless.radio0.disabled='1'",
                "wireless.default_radio0.ssid='OpenWrt'", "wireless.default_radio0.encryption='none'"]

    def show_config(self, state: list[str]) -> str:
        return "\n".join(state)

    def version_text(self) -> str:
        return "DISTRIB_ID='OpenWrt'\nDISTRIB_RELEASE='23.05.2'\nDISTRIB_DESCRIPTION='OpenWrt 23.05.2 r23630'"

    def is_config_cmd(self, base: str) -> bool:
        return norm_cmd(base) in ("uci export", "uci show")

    def show(self, command: str, state: list[str]) -> str:
        m = re.match(r"^uci show (\S+)$", norm_cmd(command))
        if m:
            hits = [ln for ln in state if ln.lower().startswith(m.group(1))]
            return "\n".join(hits) if hits else "uci: Entry not found"
        return super().show(command, state)

    @staticmethod
    def _unq(v: str) -> str:
        v = v.strip()
        return v[1:-1] if len(v) >= 2 and v[0] == v[-1] and v[0] in "'\"" else v

    def apply(self, state: list[str], commands: list[str]) -> tuple[list[str], str]:
        cfg, out = list(state), []
        for raw in commands:
            cmd = raw.strip()
            if not cmd:
                continue
            m = re.match(r"^uci\s+(set|add_list|delete)\s+(\S+?)(?:=(.*))?$", cmd)
            if m and not self.bad_trigger(cmd):
                verb, key, val = m.group(1), m.group(2), m.group(3)
                if verb == "set" and val is not None:
                    cfg = [ln for ln in cfg if not ln.startswith(key + "=")]
                    cfg.append(f"{key}='{self._unq(val)}'")
                elif verb == "add_list" and val is not None:
                    cfg.append(f"{key}+='{self._unq(val)}'")
                elif verb == "delete":
                    cfg = [ln for ln in cfg if not (ln.startswith(key + "=") or ln.startswith(key + "."))]
            elif re.match(r"^(uci\s+commit(\s+\S+)?|wifi(\s+\w+)?|/etc/init\.d/\S+\s+\w+)$", cmd):
                pass
            else:
                out.append(f"sh: {cmd.split()[0]}: not found")
        return cfg, "\n".join(out)


# =====================================================================
#                               Fortinet
# =====================================================================
class _FNode:
    def __init__(self, kind: str, name: str):
        self.kind, self.name, self.sets, self.children = kind, name, {}, []

    def child(self, kind: str, name: str) -> "_FNode":
        for c in self.children:
            if c.kind == kind and c.name == name:
                return c
        node = _FNode(kind, name)
        self.children.append(node)
        return node


class FortinetSim(Simulator):
    def baseline(self) -> list[str]:
        return self._render(self._parse([
            "config system global", f'set hostname "{self.name}"', "end",
            "config system interface", 'edit "port1"', "set vdom root", "set mode static", "next", "end"])[0])

    def version_text(self) -> str:
        return "Version: FortiSwitch-124F v7.2.5,build0432,230816 (GA)\nSerial-Number: FS124FSIM000001"

    def show_config(self, state: list[str]) -> str:
        return "\n".join(state)

    def is_config_cmd(self, base: str) -> bool:
        return norm_cmd(base) in ("show", "show full-configuration")

    def show(self, command: str, state: list[str]) -> str:
        m = re.match(r"^show (?:full-configuration )?(.+)$", norm_cmd(command))
        if m:
            root, _ = self._parse(state)
            node = next((c for c in root.children if c.kind == "config" and c.name.lower() == m.group(1)), None)
            if node:
                tmp = _FNode("root", "")
                tmp.children = [node]
                return "\n".join(self._render(tmp))
            return "(trống - không có cấu hình ở nhánh này)"
        return super().show(command, state)

    def _parse(self, lines: list[str]) -> tuple[_FNode, str]:
        return self._parse_into(_FNode("root", ""), lines)

    def _render(self, root: _FNode) -> list[str]:
        out: list[str] = []

        def walk(n: _FNode, depth: int) -> None:
            pad = "    " * depth
            out.append(f'{pad}edit "{n.name}"' if n.kind == "edit" else f"{pad}{n.kind} {n.name}")
            for k, v in n.sets.items():
                out.append(f"{pad}    set {k} {v}")
            for c in n.children:
                walk(c, depth + 1)
            out.append(f"{pad}{'next' if n.kind == 'edit' else 'end'}")

        for c in root.children:
            walk(c, 0)
        return out

    def apply(self, state: list[str], commands: list[str]) -> tuple[list[str], str]:
        base, _ = self._parse(state)
        cmds = [c for c in commands if c.strip() and not self.bad_trigger(c.strip())]
        merged, err = self._parse_into(base, cmds)
        return self._render(merged), err

    def _parse_into(self, root: _FNode, lines: list[str]) -> tuple[_FNode, str]:
        stack, out = [root], []
        for raw in lines:
            s = raw.strip()
            word, _, rest = s.partition(" ")
            rest = rest.strip()
            top = stack[-1]
            if word == "config" and rest:
                stack.append(top.child("config", rest))
            elif word == "edit" and rest and top.kind == "config":
                stack.append(top.child("edit", rest.strip('"')))
            elif word in ("next", "end") and len(stack) > 1:
                stack.pop()
            elif word == "set" and rest and top.kind != "root":
                k, _, v = rest.partition(" ")
                top.sets[k] = v
            elif word == "unset" and rest and top.kind != "root":
                top.sets.pop(rest, None)
            elif word == "delete" and rest and top.kind == "config":
                top.children = [c for c in top.children if not (c.kind == "edit" and c.name == rest.strip('"'))]
            else:
                out.append("Unknown action 0" if word not in ("set", "unset") else "command parse error (-61)")
        return root, "\n".join(out)


FAMILY_SIM = {
    "ios": IosSim, "nxos": NxosSim, "cisco_ap": CiscoApSim, "aruba_os": ArubaSim, "comware": ComwareSim,
    "huawei": HuaweiSim, "tplink": TplinkSim, "junos": JunosSim, "junos_srx": JunosSrxSim, "mikrotik": MikroTikSim, "openwrt": OpenWrtSim,
    "fortinet": FortinetSim, "generic": IosSim,
}


def make_simulator(vendor: Vendor, name: str, model: str = "") -> Simulator:
    return FAMILY_SIM.get(vendor.family, IosSim)(vendor, name, model)
