"""Kiểm tra tuân thủ cấu hình (golden config / baseline an toàn) trên bản sao lưu mới nhất của thiết bị - không cần kết nối lại."""
from __future__ import annotations

import csv
import html
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Optional

from drivers.vendors import VENDORS, get_vendor
from .config_facts import Facts, FactsStore

Check = Callable[[str, Facts], tuple[bool, str]]


@dataclass(frozen=True)
class Rule:
    id: str
    title: str
    severity: str                    # cao | trung bình | thấp
    families: tuple                  # họ thiết bị áp dụng
    check: Check
    fix_task: str = ""               # tác vụ của ứng dụng dùng để sửa
    fix_hint: str = ""


def _has(rx: str, flags=re.M | re.I) -> Check:
    return lambda text, f: (bool(re.search(rx, text, flags)), "")


def _absent(rx: str, why: str) -> Check:
    def chk(text: str, f: Facts) -> tuple[bool, str]:
        m = re.search(rx, text, re.M | re.I)
        return (m is None, f"Tìm thấy: {m.group(0).strip()}" if m else "")
    return chk


IOS = ("ios",)
NXOS = ("nxos",)
JUN = ("junos", "junos_srx")


def _ios_telnet(text: str, f: Facts) -> tuple[bool, str]:
    lines = re.findall(r"^\s*transport input (.*)$", text, re.M | re.I)
    if not lines:
        return False, "chưa giới hạn 'transport input' trên line vty (mặc định có thể cho Telnet)"
    bad = [ln for ln in lines if re.search(r"\b(telnet|all)\b", ln)]
    return (not bad, f"transport input {bad[0]}" if bad else "")


def _srx_any_any(text: str, f: Facts) -> tuple[bool, str]:
    pol: dict[tuple, dict] = {}
    for ln in text.split("\n"):
        m = re.match(r"^set security policies from-zone (\S+) to-zone (\S+) policy (\S+) (match (?:source-address|destination-address|application) \S+|then permit)", ln.strip())
        if m:
            pol.setdefault((m.group(1), m.group(2), m.group(3)), set()).add(m.group(4))
    bad = [f"{k[0]}→{k[1]}:{k[2]}" for k, v in pol.items()
           if {"match source-address any", "match destination-address any", "match application any", "then permit"} <= v]
    return (not bad, "policy 'cho phép tất cả': " + ", ".join(bad) if bad else "")


def _srx_untrust_services(text: str, f: Facts) -> tuple[bool, str]:
    bad = re.findall(r"^set security zones security-zone untrust host-inbound-traffic system-services (telnet|http|ftp)\b", text, re.M | re.I)
    return (not bad, f"zone untrust cho phép dịch vụ không an toàn: {', '.join(bad)}" if bad else "")


def _mt_service(name: str) -> Check:
    def chk(text: str, f: Facts) -> tuple[bool, str]:
        m = re.search(rf"^set {name} disabled=(yes|no)", text, re.M | re.I)
        if m:
            return (m.group(1).lower() == "yes", "" if m.group(1).lower() == "yes" else f"dịch vụ {name} đang BẬT")
        return False, f"chưa tắt dịch vụ {name}"
    return chk


RULES: list[Rule] = [
    # ---------- Cisco IOS ----------
    Rule("ios-ssh2", "SSH phiên bản 2", "cao", IOS, _has(r"^ip ssh version 2"), "harden", "Tác vụ 'Tăng cường bảo mật quản trị'"),
    Rule("ios-telnet", "Chỉ SSH trên line vty (tắt Telnet)", "cao", IOS, _ios_telnet, "secure_mgmt", "Tác vụ 'Chỉ SSH, tắt Telnet'"),
    Rule("ios-snmp", "Không dùng community SNMP mặc định (public/private)", "cao", IOS + NXOS,
         _absent(r"^snmp-server community (public|private)\b", ""), "snmp", "Đặt community khó đoán bằng 'SNMP v2c'/'SNMP v3'"),
    Rule("ios-pwenc", "Mã hóa mật khẩu (service password-encryption)", "trung bình", IOS, _has(r"^service password-encryption"), "harden"),
    Rule("ios-http", "Tắt HTTP server quản trị", "trung bình", IOS, _absent(r"^ip http server\b", ""), "harden"),
    # ---------- Cisco NX-OS ----------
    Rule("nxos-ssh", "Bật SSH (feature ssh)", "cao", NXOS, _has(r"^feature ssh"), "secure_mgmt"),
    Rule("nxos-telnet", "Tắt Telnet (không có feature telnet)", "cao", NXOS, _absent(r"^feature telnet\b", ""), "secure_mgmt"),
    # ---------- dùng chung Cisco ----------
    Rule("cisco-ntp", "Có máy chủ NTP", "trung bình", IOS + NXOS, _has(r"^ntp server"), "ntp_syslog"),
    Rule("cisco-syslog", "Gửi log về máy chủ Syslog", "trung bình", IOS + NXOS, _has(r"^logging (host|server)\b"), "ntp_syslog"),
    Rule("cisco-banner", "Có banner cảnh báo đăng nhập", "thấp", IOS + NXOS, _has(r"^banner (motd|login)\b"), "banner"),
    # ---------- Juniper (EX/QFX/SRX) ----------
    Rule("jun-ssh2", "SSH phiên bản 2", "cao", JUN, _has(r"^set system services ssh protocol-version v2"), "harden"),
    Rule("jun-root", "Cấm root đăng nhập qua SSH", "cao", JUN, _has(r"^set system services ssh root-login deny"), "harden"),
    Rule("jun-telnet", "Tắt Telnet", "cao", JUN, _absent(r"^set system services telnet\b", ""), "secure_mgmt"),
    Rule("jun-http", "Tắt web-management HTTP", "trung bình", JUN, _absent(r"^set system services web-management http\b", ""), "harden"),
    Rule("jun-snmp", "Không dùng community SNMP mặc định", "cao", JUN, _absent(r"^set snmp community (public|private)\b", ""), "snmp"),
    Rule("jun-ntp", "Có máy chủ NTP", "trung bình", JUN, _has(r"^set system ntp server"), "ntp_syslog"),
    Rule("jun-syslog", "Gửi log về máy chủ Syslog", "trung bình", JUN, _has(r"^set system syslog host"), "ntp_syslog"),
    Rule("jun-banner", "Có thông báo đăng nhập (login message)", "thấp", JUN, _has(r"^set system login message"), "banner"),
    # ---------- SRX ----------
    Rule("srx-anyany", "Không có policy 'cho phép tất cả' (any-any-any permit)", "cao", ("junos_srx",), _srx_any_any, "srx_policy_delete",
         "Xóa hoặc thu hẹp policy bằng 'Xóa security policy' / 'Security policy'"),
    Rule("srx-untrust", "Zone untrust không mở Telnet/HTTP/FTP vào thiết bị", "cao", ("junos_srx",), _srx_untrust_services, "srx_zone"),
    # ---------- Huawei / Comware ----------
    Rule("vrp-ssh", "Bật SSH (stelnet/ssh server)", "cao", ("huawei", "comware"), _has(r"^(stelnet server enable|ssh server enable)"), "secure_mgmt"),
    Rule("vrp-telnet", "Tắt Telnet", "cao", ("huawei", "comware"), _has(r"^(undo telnet server enable|telnet server disable)"), "secure_mgmt"),
    Rule("vrp-snmp", "Không dùng community SNMP mặc định", "cao", ("huawei", "comware"),
         _absent(r"^snmp-agent community (read|write) (cipher )?(public|private)\b", ""), "snmp"),
    Rule("vrp-ntp", "Có máy chủ NTP", "trung bình", ("huawei", "comware"), _has(r"^ntp-service unicast-server"), "ntp_syslog"),
    Rule("vrp-syslog", "Gửi log về máy chủ (info-center loghost)", "trung bình", ("huawei", "comware"), _has(r"^info-center loghost"), "ntp_syslog"),
    # ---------- MikroTik ----------
    Rule("mt-telnet", "Tắt dịch vụ Telnet", "cao", ("mikrotik",), _mt_service("telnet"), "secure_mgmt"),
    Rule("mt-ftp", "Tắt dịch vụ FTP", "cao", ("mikrotik",), _mt_service("ftp"), "secure_mgmt"),
    Rule("mt-ntp", "Bật NTP client", "trung bình", ("mikrotik",), _has(r"^/system ntp client\s*\n.*enabled=yes", re.M | re.I | re.S), "ntp_syslog"),
]


def rules_for(vendor_key: str) -> list[Rule]:
    fam = get_vendor(vendor_key).family if vendor_key in VENDORS else ""
    return [r for r in RULES if fam in r.families]


def evaluate(device: dict, config: str, facts: Facts) -> list[dict]:
    out = []
    for r in rules_for(device["vendor"]):
        try:
            ok, detail = r.check(config, facts)
        except Exception as e:  # noqa: BLE001
            ok, detail = False, f"lỗi kiểm tra: {e}"
        out.append({"device": device["name"], "ip": device["ip"], "rule": r.id, "title": r.title, "severity": r.severity,
                    "status": "đạt" if ok else "KHÔNG ĐẠT", "detail": detail, "fix_task": r.fix_task, "fix_hint": r.fix_hint})
    return out


def run_compliance(db, store: FactsStore, devices: list[dict]) -> list[dict]:
    rows: list[dict] = []
    for d in devices:
        b = db.last_backup(d["id"])
        if not b:
            rows.append({"device": d["name"], "ip": d["ip"], "rule": "-", "title": "Chưa có bản sao lưu để kiểm tra", "severity": "-",
                         "status": "chưa có dữ liệu", "detail": "Hãy sao lưu thiết bị trước", "fix_task": "", "fix_hint": ""})
            continue
        rows += evaluate(d, b["config"], store.get(d))
    return rows


def score(rows: list[dict]) -> Optional[int]:
    judged = [r for r in rows if r["status"] in ("đạt", "KHÔNG ĐẠT")]
    return round(100 * sum(r["status"] == "đạt" for r in judged) / len(judged)) if judged else None


def export(path: Path | str, rows: list[dict]) -> None:
    p, cols = Path(path), ["device", "ip", "title", "severity", "status", "detail", "fix_hint"]
    if p.suffix.lower() == ".csv":
        with open(p, "w", newline="", encoding="utf-8-sig") as fh:
            w = csv.writer(fh)
            w.writerow(cols)
            for r in rows:
                w.writerow([r.get(c, "") for c in cols])
    elif p.suffix.lower() == ".xlsx":
        import openpyxl
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.append(cols)
        for r in rows:
            ws.append([r.get(c, "") for c in cols])
        wb.save(p)
    else:
        e = html.escape
        body = "".join(f"<tr class='{'bad' if r['status'] == 'KHÔNG ĐẠT' else ''}'>" + "".join(f"<td>{e(str(r.get(c, '')))}</td>" for c in cols) + "</tr>" for r in rows)
        sc = score(rows)
        p.write_text(f"""<!doctype html><html lang="vi"><meta charset="utf-8"><title>Báo cáo tuân thủ</title>
<style>body{{font-family:Segoe UI,Arial,sans-serif;margin:24px}}table{{border-collapse:collapse;width:100%}}td,th{{border:1px solid #d0d7de;padding:6px 10px;text-align:left}}
th{{background:#f1f5f9}}tr.bad td{{background:#fef2f2}}</style><h1>Báo cáo tuân thủ cấu hình</h1><p>Điểm tuân thủ: <b>{sc if sc is not None else '-'}%</b></p>
<table><tr>{''.join(f'<th>{c}</th>' for c in cols)}</tr>{body}</table></html>""", encoding="utf-8")
