"""Bộ máy template (Jinja2) + danh mục tác vụ + mẫu tùy chỉnh của người dùng."""
from __future__ import annotations

import ipaddress
import re
from pathlib import Path
from typing import Any, Optional

import jinja2
import yaml

from drivers.vendors import get_vendor


# Họ thiết bị dùng lại một phần template của họ khác (SRX dùng chung các tác vụ hệ thống/định tuyến của Junos)
TEMPLATE_INHERIT = {
    "junos_srx": ("junos", frozenset({
        "hostname", "banner", "timezone", "dns", "user_add", "l3_port", "static_route", "ospf", "ntp_syslog", "snmp",
        "snmp_v3", "secure_mgmt", "harden", "aaa_radius", "tacacs", "bgp", "discovery", "port_settings"})),
}
FAMILY_ALIASES = {"junos_srx": ("junos",)}      # field 'only: [junos]' cũng áp dụng cho SRX

CUSTOM_SAMPLES = {
    "junos_srx": ("set system host-name {{ device.name }}\nset security zones security-zone trust description \"LAN\"\n"
                  "set security address-book global address WEB1 10.1.1.10/32\n"),
    "ios": "hostname {{ device.name }}\nbanner motd #Thiet bi thuoc {{ device.site }}#\nlogging buffered 16384\nservice timestamps log datetime msec\n",
    "nxos": "hostname {{ device.name }}\nbanner motd #Thiet bi thuoc {{ device.site }}#\nntp server 10.0.0.1\n",
    "cisco_ap": "hostname {{ device.name }}\nbanner motd #Thiet bi thuoc {{ device.site }}#\n",
    "junos": "set system host-name {{ device.name }}\nset system login message \"Thiet bi thuoc {{ device.site }}\"\nset system ntp server 10.0.0.1\n",
    "aruba_os": "hostname \"{{ device.name }}\"\nlogging 10.0.0.2\n",
    "comware": "sysname {{ device.name }}\ninfo-center loghost 10.0.0.2\n",
    "huawei": "sysname {{ device.name }}\ninfo-center loghost 10.0.0.2\n",
    "mikrotik": "/system identity set name={{ device.name }}\n/system clock set time-zone-name=Asia/Ho_Chi_Minh\n",
    "openwrt": "uci set system.@system[0].hostname='{{ device.name }}'\nuci commit system\n",
    "fortinet": "config system global\nset hostname {{ device.name }}\nend\n",
    "tplink": "vlan 100\nname TEST\nexit\n",
    "generic": "{# Mỗi dòng là một lệnh theo cú pháp của hãng. Biến: device.name, device.ip, device.site #}\n",
    "mixed": ("{# Đã chọn thiết bị khác hãng: dùng if để gửi đúng cú pháp cho từng hãng #}\n"
              "{% if device.vendor.startswith('juniper') %}\nset system host-name {{ device.name }}\n"
              "{% elif device.vendor.startswith('cisco') %}\nhostname {{ device.name }}\n"
              "{% elif device.vendor.startswith('mikrotik') %}\n/system identity set name={{ device.name }}\n{% endif %}\n"),
}


def sample_for(families: "set[str] | list[str]") -> str:
    """Đoạn lệnh tùy chỉnh mẫu phù hợp với các họ thiết bị đang chọn."""
    fams = sorted(set(families))
    if not fams:
        return CUSTOM_SAMPLES["generic"]
    if len(fams) > 1:
        return CUSTOM_SAMPLES["mixed"]
    return CUSTOM_SAMPLES.get(fams[0], CUSTOM_SAMPLES["generic"])


def _as_bool(val: Any) -> bool:
    """Chuỗi 'false'/'0'/'no' từ CSV phải là False (bool('false') mặc định là True)."""
    if isinstance(val, str):
        return val.strip().lower() in ("1", "true", "yes", "y", "x", "có", "co", "on")
    return bool(val)


class TaskUnsupported(Exception):
    """Hãng/họ thiết bị này chưa có template cho tác vụ."""


class TemplateError(Exception):
    """Dữ liệu nhập sai hoặc template lỗi."""


_SPLIT = re.compile(r"[,\s;]+")


def _f_ports(value: Any) -> list[str]:
    return [p for p in _SPLIT.split(str(value or "").strip()) if p]


def _vlan_tokens(value: Any) -> list[str]:
    return [t for t in re.split(r"[,\s;]+", str(value or "").strip()) if t]


def _f_vlanlist(value: Any) -> str:
    return ",".join(_vlan_tokens(value))


def _f_vlanitems(value: Any) -> list[str]:
    return _vlan_tokens(value)


def _f_vlanspace(value: Any) -> str:
    return " ".join(_vlan_tokens(value))


def _f_vlanto(value: Any) -> str:
    """'10,30-40' -> '10 30 to 40' (kiểu Huawei/Comware)."""
    return " ".join(t.replace("-", " to ") for t in _vlan_tokens(value))


def _f_quote(value: Any) -> str:
    return '"' + str(value).replace('"', "'") + '"'


def _iface(value: Any) -> ipaddress.IPv4Interface | ipaddress.IPv6Interface:
    return ipaddress.ip_interface(str(value).strip())


def _f_ipaddr(value: Any) -> str:
    """'10.1.1.1/24' -> '10.1.1.1'"""
    return str(_iface(value).ip)


def _f_netmask(value: Any) -> str:
    """'10.1.1.1/24' -> '255.255.255.0'"""
    return str(_iface(value).netmask)


def _f_wildcard(value: Any) -> str:
    """'10.1.1.1/24' -> '0.0.0.255'"""
    return str(_iface(value).hostmask)


def _f_network(value: Any) -> str:
    """'10.1.1.1/24' -> '10.1.1.0'"""
    return str(_iface(value).network.network_address)


def _f_lines(value: Any) -> list[str]:
    return [ln.strip() for ln in re.split(r"[\n;]+", str(value or "")) if ln.strip()]


def _f_areaid(value: Any) -> str:
    """'0' -> '0.0.0.0'; '10' -> '0.0.0.10'; giữ nguyên nếu đã là dạng chấm."""
    v = str(value).strip()
    return v if "." in v else str(ipaddress.IPv4Address(int(v)))


def _f_aclnet(value: Any) -> str:
    """Nguồn/đích ACL kiểu Cisco IOS: any | host X | net wildcard."""
    v = str(value).strip()
    if v.lower() == "any" or v.lower().startswith("host "):
        return v.lower() if v.lower() == "any" else v
    if "/" in v:
        i = _iface(v)
        return f"{i.network.network_address} {i.hostmask}"
    return f"host {v}"


def _f_aclcidr(value: Any) -> str:
    """Nguồn/đích kiểu NX-OS/Junos: any | a.b.c.d/len."""
    v = str(value).strip()
    if v.lower() == "any":
        return "any"
    return v if "/" in v else f"{v}/32"


def _is_ipnet(value: Any) -> bool:
    return bool(re.fullmatch(r"\d{1,3}(\.\d{1,3}){3}(/\d{1,2})?", str(value).strip()))


def _f_ipnet(value: Any) -> str:
    v = str(value).strip()
    return v if "/" in v else f"{v}/32"


def _f_junos_addr(value: Any) -> str:
    """Tên đối tượng address-book Junos: any | tên có sẵn | tự đặt tên cho IP/prefix."""
    v = str(value).strip()
    if v.lower() == "any":
        return "any"
    if _is_ipnet(v):
        n = _f_ipnet(v)
        return ("H_" + n[:-3]) if n.endswith("/32") else "N_" + n.replace("/", "_")
    return v


def _f_need(value: Any, message: str) -> Any:
    """Bắt buộc có giá trị (dùng cho trường chỉ cần với một số hãng)."""
    if value is None or str(value).strip() == "":
        raise TemplateError(message)
    return value


def _check_vlan(token: str) -> None:
    m = re.fullmatch(r"(\d{1,4})(?:-(\d{1,4}))?", token)
    if not m:
        raise TemplateError(f"VLAN không hợp lệ: '{token}'")
    lo, hi = int(m.group(1)), int(m.group(2) or m.group(1))
    if not (1 <= lo <= 4094 and 1 <= hi <= 4094 and lo <= hi):
        raise TemplateError(f"VLAN phải trong khoảng 1-4094: '{token}'")


class TaskCatalog:
    def __init__(self, base_dir: Path, custom_dir: Path):
        self.base_dir = Path(base_dir)
        self.templates_dir = self.base_dir / "templates"
        self.custom_dir = Path(custom_dir)
        self.custom_dir.mkdir(parents=True, exist_ok=True)
        with open(self.base_dir / "tasks.yaml", encoding="utf-8") as fh:
            self.tasks: dict[str, dict] = yaml.safe_load(fh)["tasks"]
        self.env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(str(self.templates_dir)),
            trim_blocks=True, lstrip_blocks=True, undefined=jinja2.StrictUndefined, autoescape=False,
        )
        self.env.filters.update(ports=_f_ports, vlanlist=_f_vlanlist, vlanspace=_f_vlanspace,
                                vlanto=_f_vlanto, vlanitems=_f_vlanitems, q=_f_quote, ipaddr=_f_ipaddr,
                                netmask=_f_netmask, wildcard=_f_wildcard, network=_f_network, lines=_f_lines,
                                areaid=_f_areaid, aclnet=_f_aclnet, aclcidr=_f_aclcidr, need=_f_need,
                                junos_addr=_f_junos_addr, ipnet=_f_ipnet)
        self.env.tests["ipnet"] = _is_ipnet

    # ---- tra cứu -------------------------------------------------------
    def task_ids(self) -> list[str]:
        return list(self.tasks)

    def label(self, task_id: str) -> str:
        return self.tasks[task_id]["label"]

    def group(self, task_id: str) -> str:
        return self.tasks[task_id].get("group", "Khác")

    def display(self, task_id: str) -> str:
        """Tên hiển thị trong danh sách chọn: 'Nhóm › Tên tác vụ'."""
        return f"{self.group(task_id)} › {self.label(task_id)}"

    def fields(self, task_id: str) -> list[dict]:
        return self.tasks[task_id].get("fields", [])

    @staticmethod
    def field_applies(field: dict, families: "set[str] | list[str] | None") -> bool:
        """Field có dùng cho (ít nhất một trong) các họ thiết bị đang chọn không? Không chọn gì -> hiện tất cả."""
        only = field.get("only")
        if not only or not families:
            return True
        fams = set(families)
        for f in list(fams):
            fams.update(FAMILY_ALIASES.get(f, ()))
        return bool(set(only) & fams)

    def fields_for(self, task_id: str, families: "set[str] | list[str] | None" = None) -> list[dict]:
        return [f for f in self.fields(task_id) if self.field_applies(f, families)]

    def template_name(self, task_id: str, vendor_key: str) -> str | None:
        """Tên template (tương đối) dùng cho hãng này, có tính kế thừa; None nếu chưa có."""
        fam = get_vendor(vendor_key).family
        if (self.templates_dir / fam / f"{task_id}.j2").exists():
            return f"{fam}/{task_id}.j2"
        parent = TEMPLATE_INHERIT.get(fam)
        if parent and task_id in parent[1] and (self.templates_dir / parent[0] / f"{task_id}.j2").exists():
            return f"{parent[0]}/{task_id}.j2"
        return None

    def template_path(self, task_id: str, vendor_key: str) -> Path:
        name = self.template_name(task_id, vendor_key)
        return self.templates_dir / (name or f"{get_vendor(vendor_key).family}/{task_id}.j2")

    def supported(self, task_id: str, vendor_key: str) -> bool:
        return self.template_name(task_id, vendor_key) is not None

    def support_matrix(self) -> dict[str, list[str]]:
        """{task_id: [danh sách family có template]}"""
        from drivers.vendors import VENDORS
        return {t: sorted({v.family for k, v in VENDORS.items() if self.supported(t, k)}) for t in self.tasks}

    # ---- render --------------------------------------------------------
    @staticmethod
    def device_ctx(device: dict, index: int = 1) -> dict:
        return {"name": device.get("name", ""), "ip": device.get("ip", ""), "site": device.get("site", ""),
                "vendor": device.get("vendor", ""), "tags": device.get("tags", ""),
                "model": device.get("model", ""), "index": index, "id": device.get("id", 0)}

    def _expand(self, value: Any, ctx: dict) -> Any:
        if isinstance(value, str) and ("{{" in value or "{%" in value):
            try:
                return self.env.from_string(value).render(device=ctx)
            except jinja2.TemplateError as e:
                raise TemplateError(f"Lỗi biến '{value}': {e}") from e
        return value

    def _prepare(self, task_id: str, variables: dict, ctx: dict, family: str = "") -> dict:
        data: dict[str, Any] = {}
        for f in self.fields(task_id):
            name, kind = f["name"], f.get("kind", "text")
            label = f["label"]
            if family and not self.field_applies(f, [family]):      # field của hãng khác: dùng mặc định, không kiểm tra
                if kind == "bool":
                    data[name] = _as_bool(f.get("default", False))
                elif kind == "choice":
                    data[name] = str(f.get("default", f["options"][0]["value"]))
                else:
                    data[name] = str(f.get("default", "") or "")
                continue
            if kind == "choice":
                values = [str(o["value"]) for o in f["options"]]
                raw = variables.get(name, f.get("default", values[0]))
                val = str(self._expand(raw, ctx)).strip()
                if val not in values:
                    raise TemplateError(f"Giá trị '{val}' không hợp lệ cho '{label}' (chọn: {', '.join(values)})")
                data[name] = val
                continue
            raw = variables.get(name, f.get("default", False if kind == "bool" else ""))
            val = self._expand(raw, ctx)
            if kind == "bool":
                data[name] = _as_bool(val)
                continue
            val = "" if val is None else str(val).strip()
            if f.get("required") and not val:
                raise TemplateError(f"Thiếu trường bắt buộc: {label}")
            if val:
                self._validate(kind, val, f)
            data[name] = val
        return data

    @staticmethod
    def _validate(kind: str, val: str, f: dict) -> None:
        label = f["label"]
        try:
            if kind == "vlan":
                _check_vlan(val)
            elif kind == "vlans":
                for tok in _vlan_tokens(val):
                    _check_vlan(tok)
            elif kind == "vlanlines":
                for line in _f_lines(val):
                    _check_vlan(line.split(None, 1)[0])
            elif kind == "list":
                if not _f_ports(val):
                    raise TemplateError(f"Trường '{label}' không hợp lệ")
            elif kind == "int":
                if not re.fullmatch(r"-?\d{1,10}", val):
                    raise TemplateError(f"'{label}' phải là số nguyên (đang nhập: '{val}')")
                if "min" in f and int(val) < int(f["min"]) or "max" in f and int(val) > int(f["max"]):
                    raise TemplateError(f"'{label}' phải trong khoảng {f.get('min', '-')}..{f.get('max', '-')}")
            elif kind == "ip":
                ipaddress.ip_address(val)
            elif kind == "portrange":
                if not re.fullmatch(r"\d{1,5}(-\d{1,5})?", val) or any(int(x) > 65535 or int(x) < 1 for x in val.split("-")):
                    raise ValueError("cổng 1-65535, hoặc dải 8000-8010")
            elif kind == "addr":
                if val.lower() != "any":
                    if re.fullmatch(r"[\d.]+(/\d{1,2})?", val):
                        ipaddress.ip_interface(val if "/" in val else val + "/32")
                    elif not re.fullmatch(r"[A-Za-z0-9_.\-]{1,63}", val):
                        raise ValueError("chỉ dùng chữ, số, _ . -")
            elif kind == "cidr":
                if "/" not in val:
                    raise ValueError("thiếu /prefix")
                ipaddress.ip_interface(val)
            elif kind == "cidrs":
                for tok in _f_ports(val):
                    if "/" not in tok:
                        raise ValueError("thiếu /prefix")
                    ipaddress.ip_interface(tok)
        except TemplateError:
            raise
        except ValueError as e:
            ex = {"ip": "10.0.0.1", "cidr": "10.0.0.1/24", "cidrs": "10.0.0.0/24", "portrange": "443 hoặc 8000-8010",
                  "addr": "any | 10.1.1.0/24 | tên-đối-tượng"}.get(kind, "")
            raise TemplateError(f"'{label}' không hợp lệ ({e}). Ví dụ: {ex}") from e
        except Exception as e:  # noqa: BLE001
            raise TemplateError(f"'{label}' không hợp lệ: {e}") from e

    @staticmethod
    def _clean(text: str) -> list[str]:
        return [ln.strip() for ln in text.replace("\r", "").split("\n") if ln.strip()]

    def render(self, task_id: str, device: dict, variables: dict, index: int = 1) -> list[str]:
        if task_id not in self.tasks:
            raise TemplateError(f"Không có tác vụ '{task_id}'")
        if not self.supported(task_id, device["vendor"]):
            raise TaskUnsupported(
                f"{get_vendor(device['vendor']).label} chưa có template cho tác vụ '{self.label(task_id)}'. "
                f"Hãy dùng 'Lệnh tùy chỉnh'.")
        ctx = self.device_ctx(device, index)
        fam = get_vendor(device["vendor"]).family
        data = self._prepare(task_id, variables, ctx, fam)
        try:
            tpl = self.env.get_template(self.template_name(task_id, device["vendor"]))
            return self._clean(tpl.render(device=ctx, **data))
        except jinja2.TemplateError as e:
            raise TemplateError(f"Lỗi template {fam}/{task_id}: {e}") from e

    def render_custom(self, text: str, device: dict, variables: Optional[dict] = None, index: int = 1) -> list[str]:
        ctx = self.device_ctx(device, index)
        try:
            tpl = self.env.from_string(text)
            return self._clean(tpl.render(device=ctx, **(variables or {})))
        except jinja2.TemplateError as e:
            raise TemplateError(f"Lỗi trong lệnh tùy chỉnh: {e}") from e

    # ---- mẫu tùy chỉnh -------------------------------------------------
    @staticmethod
    def _safe(name: str) -> str:
        s = re.sub(r"[^\w\- ]+", "", name, flags=re.UNICODE).strip().replace(" ", "_")
        if not s:
            raise TemplateError("Tên mẫu không hợp lệ")
        return s

    def list_custom(self) -> list[str]:
        return sorted(p.stem for p in self.custom_dir.glob("*.j2"))

    def save_custom(self, name: str, text: str) -> None:
        (self.custom_dir / f"{self._safe(name)}.j2").write_text(text, encoding="utf-8")

    def load_custom(self, name: str) -> str:
        return (self.custom_dir / f"{self._safe(name)}.j2").read_text(encoding="utf-8")

    def delete_custom(self, name: str) -> None:
        p = self.custom_dir / f"{self._safe(name)}.j2"
        if p.exists():
            p.unlink()


def parse_kv_lines(text: str) -> dict[str, str]:
    """'ten=gia tri' mỗi dòng -> dict (dùng cho biến của lệnh tùy chỉnh)."""
    out: dict[str, str] = {}
    for line in text.split("\n"):
        if "=" in line and not line.strip().startswith("#"):
            k, v = line.split("=", 1)
            if k.strip():
                out[k.strip()] = v.strip()
    return out
