"""Kiểm tra khóa SSH của thiết bị (chống kẻ chen giữa đường truyền).

Chế độ:  tofu   = tin ở lần kết nối đầu tiên rồi ghi nhớ; lần sau khóa đổi -> CHẶN (khuyến nghị, mặc định)
         strict = chỉ kết nối thiết bị đã được 'tin cậy khóa' từ trước
         off    = không kiểm tra (không khuyến nghị)
"""
from __future__ import annotations

from pathlib import Path


def _entry_hosts(host: str, port: int) -> set[str]:
    return {host, f"[{host}]:{port}"} if port != 22 else {host}


def is_known(path: Path | str, host: str, port: int = 22) -> bool:
    p = Path(path)
    if not p.exists():
        return False
    want = _entry_hosts(host, port)
    for line in p.read_text(encoding="utf-8", errors="ignore").splitlines():
        parts = line.split()
        if len(parts) >= 3 and not line.startswith("#") and want & set(parts[0].split(",")):
            return True
    return False


def forget_host(path: Path | str, host: str, port: int = 22) -> int:
    """Xóa khóa đã lưu của một thiết bị (khi thiết bị được thay/reset hợp lệ). Trả về số dòng đã xóa."""
    p = Path(path)
    if not p.exists():
        return 0
    want, keep, removed = _entry_hosts(host, port), [], 0
    for line in p.read_text(encoding="utf-8", errors="ignore").splitlines():
        parts = line.split()
        if len(parts) >= 3 and not line.startswith("#") and want & set(parts[0].split(",")):
            removed += 1
        else:
            keep.append(line)
    p.write_text("\n".join(keep) + ("\n" if keep else ""), encoding="utf-8")
    return removed


def netmiko_kwargs(mode: str, path: Path | str, host: str, port: int = 22) -> dict:
    """Tham số Netmiko tương ứng với chế độ kiểm tra khóa."""
    if mode == "off":
        return {}
    kw = {"alt_host_keys": True, "alt_key_file": str(path)}
    if mode == "strict":
        kw["ssh_strict"] = True
    return kw


def save_after_connect(conn, path: Path | str) -> None:
    """Ghi nhớ khóa của thiết bị vừa kết nối (TOFU)."""
    try:
        conn.remote_conn_pre.save_host_keys(str(path))
    except Exception:
        pass


def trust_host(path: Path | str, host: str, port: int = 22, timeout: float = 8.0) -> str:
    """Lấy khóa SSH hiện tại của thiết bị và ghi vào danh sách tin cậy. Trả về dấu vân tay (fingerprint)."""
    import base64
    import hashlib
    import socket

    import paramiko                      # có sẵn khi đã cài Netmiko

    sock = socket.create_connection((host, port), timeout=timeout)
    tr = paramiko.Transport(sock)
    try:
        tr.start_client(timeout=timeout)
        key = tr.get_remote_server_key()
    finally:
        tr.close()
    hk = paramiko.HostKeys()
    if Path(path).exists():
        hk.load(str(path))
    hk.add(host if port == 22 else f"[{host}]:{port}", key.get_name(), key)
    hk.save(str(path))
    fp = base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
    return f"SHA256:{fp}"
