"""Che thông tin nhạy cảm (mật khẩu, khóa, community...) trước khi lưu lịch sử, báo cáo hoặc hiển thị."""
from __future__ import annotations

import re
from typing import Iterable

MASK = "********"
_Q = r'(?:"[^"]*"|\S+)'

# (regex, thay thế) - giữ nguyên phần lệnh, chỉ che giá trị bí mật
_PATTERNS: list[tuple[re.Pattern, str]] = [(re.compile(p, re.I), r) for p, r in [
    # Cisco / Huawei / Comware: secret|password [loại] giá_trị
    (r"\b(secret|password|passphrase)(\s+(?:\d\s+|cipher\s+|simple\s+|irreversible-cipher\s+)?)" + _Q, rf"\1\2{MASK}"),
    (r"^(\s*key)(\s+(?:\d\s+)?)\S+\s*$", rf"\1\2{MASK}"),                              # radius/tacacs: key X
    (r"(\btacacs-server host \S+ key\s+(?:\d\s+)?)\S+", rf"\1{MASK}"),
    (r"(\bradius-server host \S+ key\s+(?:\d\s+)?)\S+", rf"\1{MASK}"),
    (r"(\bsnmp-server community\s+)\S+", rf"\1{MASK}"),
    (r"(\bsnmp-agent community\s+(?:read|write)\s+(?:cipher\s+)?)\S+", rf"\1{MASK}"),
    (r"(\bsnmp-server user \S+ \S+ (?:v3 )?auth \S+ )\S+( priv \S+ (?:\d+ )?)\S+", rf"\1{MASK}\2{MASK}"),
    (r"(\bwpa-psk (?:ascii|hex) (?:\d\s+)?)\S+", rf"\1{MASK}"),
    (r"(\bpre-shared-key\s+(?:\d\s+)?)\S+", rf"\1{MASK}"),
    # Junos
    (r"(\bset snmp community\s+)\S+", rf"\1{MASK}"),
    (r"(\b(?:authentication-password|privacy-password|plain-text-password-value|encrypted-password|secret|ascii-text|"
     r"authentication-key|tacplus-server \S+ secret)\s+)" + _Q, rf"\1{MASK}"),
    # MikroTik / OpenWrt / Fortinet
    (r"(\b(?:password|wpa2-pre-shared-key|wpa-pre-shared-key|psk|passphrase|secret|key)=)" + _Q, rf"\1{MASK}"),
    (r"(\buci set wireless\.\S+\.key=)\S+", rf"\1{MASK}"),
    (r"(\bset (?:password|psk|passwd|key|secret|passphrase) )" + _Q, rf"\1{MASK}"),
    (r"(/snmp community add name=)\S+", rf"\1{MASK}"),
]]


def redact_text(text: str) -> str:
    """Che từng dòng văn bản."""
    if not text:
        return text
    out = []
    for line in text.split("\n"):
        for rx, rep in _PATTERNS:
            line = rx.sub(rep, line)
        out.append(line)
    return "\n".join(out)


def redact_lines(lines: Iterable[str]) -> list[str]:
    return redact_text("\n".join(lines)).split("\n") if lines else []
