"""Công cụ xử lý cấu hình: chuẩn hóa, băm, diff, và sinh lệnh hoàn tác (rollback).

Rollback ở đây là "best-effort" dựa trên so sánh cấu hình: lệnh nào mới thêm thì phủ định
(no / undo / delete), lệnh nào bị mất thì thêm lại. Luôn xem trước (preview) trước khi áp dụng.
"""
from __future__ import annotations

import difflib
import hashlib
import re
from typing import Iterable

# Các dòng "nhiễu" thay đổi mỗi lần đọc cấu hình (thời gian, dung lượng...) -> bỏ qua khi so sánh.
_VOLATILE_PATTERNS = [
    r"^\s*[!#]*\s*Building configuration",
    r"^\s*[!#]*\s*Current configuration\s*:",
    r"^\s*[!#]*\s*Last configuration change",
    r"^\s*[!#]*\s*NVRAM config last updated",
    r"^\s*[!#]*\s*No configuration change since last restart",
    r"^\s*[!#]*\s*Time:\s",
    r"^\s*[!#]*\s*Command:\s",
    r"^\s*[!#]*\s*Running configuration last done at",
    r"^\s*ntp clock-period",
    r"^\s*##\s*Last (commit|changed)",
    r"^\s*#\s*[a-z]{3}/\d{1,2}/\d{4}",         # MikroTik: "# jan/02/2024 10:00:00 by RouterOS"
    r"^\s*#\s*(software id|model|serial number)\b",
    r"^\s*#\s*\d{4}-\d{2}-\d{2}",
    r"^\s*Last configuration was (updated|saved)",
    r"^\s*;\s*(J|T)\w+ Configuration Editor",  # HP ProCurve header
    r"^\s*;\s*.*Configuration Editor",
    r"^\s*Using \d+ out of \d+ bytes",
]
_VOLATILE = [re.compile(p, re.I) for p in _VOLATILE_PATTERNS]


def normalize(text: str) -> str:
    """Bỏ dòng trống, khoảng trắng cuối dòng và các dòng nhiễu."""
    out = []
    for line in text.replace("\r", "").split("\n"):
        line = line.rstrip()
        if not line.strip():
            continue
        if any(p.search(line) for p in _VOLATILE):
            continue
        out.append(line)
    return "\n".join(out)


def config_hash(text: str) -> str:
    return hashlib.sha256(normalize(text).encode("utf-8", "replace")).hexdigest()


def unified_diff(old: str, new: str, old_name: str = "trước", new_name: str = "sau") -> str:
    a = normalize(old).split("\n") if old.strip() else []
    b = normalize(new).split("\n") if new.strip() else []
    return "\n".join(difflib.unified_diff(a, b, old_name, new_name, lineterm="", n=2))


# ---------------------------------------------------------------------------
Item = tuple[tuple[str, ...], str]   # (đường dẫn cha, dòng lệnh)


def parse_tree(text: str) -> list[Item]:
    """Phân tích cấu hình dạng thụt lề thành danh sách (đường_dẫn_cha, lệnh)."""
    items: list[Item] = []
    stack: list[tuple[int, str]] = []
    for raw in normalize(text).split("\n"):
        stripped = raw.strip()
        if not stripped or stripped[0] in "!#" or stripped == "end":
            continue
        indent = len(raw) - len(raw.lstrip(" "))
        while stack and stack[-1][0] >= indent:
            stack.pop()
        items.append((tuple(t for _, t in stack), stripped))
        stack.append((indent, stripped))
    return items


def negate(line: str, style: str) -> str:
    """Tạo lệnh phủ định theo kiểu của hãng."""
    if style == "junos":
        if line.startswith("set "):
            return "delete " + line[4:]
        if line.startswith("delete "):
            return "set " + line[7:]
        return line
    word = "no" if style == "no" else "undo"
    if line.startswith(word + " "):
        return line[len(word) + 1:]
    return f"{word} {line}"


_SENSITIVE = re.compile(r"(password|secret|key|community|cipher|\$\d\$)", re.I)


def rollback_commands(current: str, target: str, style: str, exit_cmd: str = "exit") -> tuple[list[str], list[str]]:
    """Sinh lệnh để đưa cấu hình `current` về giống `target`.

    Trả về (commands, warnings).
    """
    cur_items, tgt_items = parse_tree(current), parse_tree(target)
    cur_set, tgt_set = set(cur_items), set(tgt_items)
    to_undo = [i for i in cur_items if i not in tgt_set]
    to_add = [i for i in tgt_items if i not in cur_set]

    def prune(items: list[Item]) -> list[Item]:
        tops = {line for path, line in items if not path}
        return [(p, l) for p, l in items if not p or p[0] not in tops]

    undo, add = prune(to_undo), prune(to_add)
    ops: list[tuple[tuple[str, ...], str]] = [(p, negate(l, style)) for p, l in undo] + list(add)

    cmds: list[str] = []
    last_path: tuple[str, ...] = ()
    for path, cmd in ops:
        if path != last_path:
            cmds.extend([exit_cmd] * len(last_path))
            cmds.extend(path)
            last_path = path
        cmds.append(cmd)
    cmds.extend([exit_cmd] * len(last_path))

    warnings: list[str] = []
    if len(undo) + len(add) > 150:
        warnings.append(f"Có tới {len(undo) + len(add)} thay đổi - hãy kiểm tra kỹ trước khi áp dụng.")
    if any(_SENSITIVE.search(l) for _, l in undo + add):
        warnings.append("Có dòng chứa mật khẩu/khóa/community: thiết bị có thể lưu dạng băm nên khôi phục "
                        "chưa chắc chính xác - hãy kiểm tra thủ công.")
    if not cmds:
        warnings.append("Cấu hình hiện tại đã giống bản sao lưu - không có gì để khôi phục.")
    return cmds, warnings


def count_changes(diff_text: str) -> tuple[int, int]:
    """Đếm số dòng thêm/xóa trong unified diff."""
    add = rem = 0
    for line in diff_text.split("\n"):
        if line.startswith("+") and not line.startswith("+++"):
            add += 1
        elif line.startswith("-") and not line.startswith("---"):
            rem += 1
    return add, rem


def find_errors(output: str, pattern: str) -> list[str]:
    """Tìm các dòng báo lỗi trong output của thiết bị."""
    if not pattern:
        return []
    rx = re.compile(pattern, re.I)
    return [ln.strip() for ln in output.split("\n") if rx.search(ln)]


def chunks(seq: Iterable, n: int):
    seq = list(seq)
    for i in range(0, len(seq), n):
        yield seq[i:i + n]
