"""Lớp driver trừu tượng + driver Netmiko (thiết bị thật) + driver giả lập (để thử)."""
from __future__ import annotations

import json
import re
import threading
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional

from core.config_tools import find_errors
from . import hostkeys
from .simulator import apply_pipes, make_simulator, norm_cmd
from .vendors import Vendor, get_vendor


class DriverError(Exception):
    """Lỗi kết nối/thực thi có thông điệp thân thiện."""


@dataclass
class ConnParams:
    name: str
    host: str
    vendor: str
    username: str = ""
    password: str = ""
    secret: str = ""
    port: int = 22
    protocol: str = "ssh"
    timeout: int = 30
    delay_factor: float = 1.0
    simulated: bool = False
    model: str = ""
    host_key_mode: str = "tofu"
    known_hosts: str = ""


@dataclass
class ApplyResult:
    output: str = ""
    errors: list[str] = field(default_factory=list)
    saved: bool = False
    pending_confirm: bool = False          # Junos: đã 'commit confirmed', cần xác nhận lại bằng commit


def friendly_error(exc: Exception) -> str:
    """Chuyển lỗi kỹ thuật thành thông điệp tiếng Việt dễ hiểu."""
    name = type(exc).__name__
    text = str(exc).strip()
    low = text.lower()
    if isinstance(exc, DriverError):
        return text
    if "BadHostKey" in name or "host key" in low and "not match" in low:
        return ("Khóa SSH của thiết bị ĐÃ THAY ĐỔI so với lần trước - có thể bị tấn công chen giữa, hoặc thiết bị vừa được thay/reset. "
                "Nếu bạn chắc chắn hợp lệ, vào tab Thiết bị và bấm '🔑 Quên khóa SSH' rồi kết nối lại.")
    if "not found in known_hosts" in low or ("known_hosts" in low and "not found" in low):
        return "Chế độ 'strict': chưa tin cậy khóa SSH của thiết bị này. Vào tab Thiết bị bấm '🔑 Tin cậy khóa SSH' trước."
    if "Authentication" in name or "authentication failed" in low or "auth fail" in low:
        return "Sai tên đăng nhập/mật khẩu (hoặc thiết bị từ chối phương thức xác thực)."
    if "Timeout" in name or "timed out" in low or "timeout" in low:
        return "Hết thời gian chờ: kiểm tra IP, cổng, firewall/ACL hoặc thiết bị có đang bật SSH không."
    if "ReadTimeout" in name or "pattern not detected" in low:
        return "Không nhận ra dấu nhắc lệnh (prompt) của thiết bị - có thể sai hãng đã chọn hoặc thiết bị phản hồi chậm."
    if "refused" in low:
        return "Thiết bị từ chối kết nối (cổng đóng hoặc dịch vụ SSH/Telnet chưa bật)."
    if "no route" in low or "unreachable" in low or "getaddrinfo" in low or "name or service not known" in low:
        return "Không tìm thấy đường tới thiết bị (sai IP/hostname hoặc mất mạng)."
    if "ModuleNotFoundError" in name or "No module named" in text:
        return "Thiếu thư viện Python: hãy chạy 'pip install -r requirements.txt'."
    return f"{name}: {text}" if text else name


class BaseDriver(ABC):
    def __init__(self, params: ConnParams):
        self.p = params
        self.vendor: Vendor = get_vendor(params.vendor)

    # --- vòng đời ---
    @abstractmethod
    def connect(self) -> None: ...

    @abstractmethod
    def disconnect(self) -> None: ...

    # --- thao tác ---
    @abstractmethod
    def run_show(self, command: str) -> str: ...

    @abstractmethod
    def apply(self, commands: list[str], save: bool = True, confirm_minutes: int = 0) -> ApplyResult: ...

    def confirm_commit(self) -> str:
        """Xác nhận thay đổi đang chờ (Junos commit confirmed). Thiết bị khác không cần."""
        return ""

    def get_config(self) -> str:
        return self.run_show(self.vendor.backup_cmd)

    def get_facts(self) -> dict:
        out = self.run_show(self.vendor.facts_cmd)
        return {"os_version": extract_version(out), "raw": out[:500]}

    def __enter__(self) -> "BaseDriver":
        self.connect()
        return self

    def __exit__(self, *exc) -> None:
        self.disconnect()


_VER_RX = [
    re.compile(r"(Cisco IOS[^\n,]*Version [^\s,]+)", re.I),
    re.compile(r"(NX-OS[^\n]*version[:\s]+[^\s,]+)", re.I),
    re.compile(r"(Junos:\s*\S+)", re.I),
    re.compile(r"(VRP[^\n]*Version[^\n]*)", re.I),
    re.compile(r"(version\s*[:=]?\s*[\w.()\-]+)", re.I),
    re.compile(r"(RouterOS[^\n]*)|(version:\s*\S+)", re.I),
]


def extract_version(text: str) -> str:
    for rx in _VER_RX:
        m = rx.search(text or "")
        if m:
            return next(g for g in m.groups() if g).strip()[:80]
    for line in (text or "").split("\n"):
        if line.strip():
            return line.strip()[:80]
    return ""


# ---------------------------------------------------------------------------
SAVE_FALLBACK = {
    "tplink_jetstream": "copy running-config startup-config",
    "dell_os10": "copy running-configuration startup-configuration",
    "dell_powerconnect": "copy running-config startup-config",
    "extreme_exos": "save configuration",
}


class NetmikoDriver(BaseDriver):
    """Kết nối thiết bị thật qua Netmiko (SSH/Telnet)."""

    def __init__(self, params: ConnParams):
        super().__init__(params)
        self.conn = None

    def connect(self) -> None:
        try:
            from netmiko import ConnectHandler
        except ImportError as e:  # pragma: no cover
            raise DriverError("Chưa cài Netmiko. Chạy: pip install -r requirements.txt") from e
        p, v = self.p, self.vendor
        dtype = v.netmiko
        if p.protocol == "telnet":
            if not v.telnet_ok:
                raise DriverError(f"{v.label} không hỗ trợ Telnet trong ứng dụng này, hãy dùng SSH.")
            dtype += "_telnet"
        extra = {}
        if p.protocol != "telnet" and p.known_hosts:
            extra = hostkeys.netmiko_kwargs(p.host_key_mode, p.known_hosts, p.host, p.port)
            if p.host_key_mode == "strict" and not hostkeys.is_known(p.known_hosts, p.host, p.port):
                raise DriverError("Chế độ 'strict': chưa tin cậy khóa SSH của thiết bị này. Vào tab Thiết bị bấm '🔑 Tin cậy khóa SSH' trước.")
        self.conn = ConnectHandler(
            device_type=dtype, host=p.host, port=p.port, username=p.username, password=p.password,
            secret=p.secret, timeout=p.timeout, conn_timeout=min(p.timeout, 20), auth_timeout=min(p.timeout, 20),
            banner_timeout=30, global_delay_factor=p.delay_factor, **extra,
        )
        if p.host_key_mode == "tofu" and p.known_hosts and p.protocol != "telnet":
            hostkeys.save_after_connect(self.conn, p.known_hosts)
        if p.secret:
            try:
                self.conn.enable()
            except Exception:
                pass  # một số thiết bị không có chế độ enable

    def disconnect(self) -> None:
        if self.conn is not None:
            try:
                self.conn.disconnect()
            except Exception:
                pass
            self.conn = None

    def run_show(self, command: str) -> str:
        assert self.conn is not None, "Chưa kết nối"
        return self.conn.send_command(command, read_timeout=max(60, self.p.timeout * 2))

    def apply(self, commands: list[str], save: bool = True, confirm_minutes: int = 0) -> ApplyResult:
        assert self.conn is not None, "Chưa kết nối"
        v = self.vendor
        res = ApplyResult()
        if v.save == "commit":                       # Junos: cấu hình ứng viên -> commit check -> commit (confirmed)
            res.output = self.conn.send_config_set(commands, exit_config_mode=False)
            res.errors = find_errors(res.output, v.error_re)
            if not res.errors:
                chk = str(self.conn.commit(check=True))
                res.output += "\n" + chk
                if "check succeeds" not in chk.lower():
                    res.errors = [ln.strip() for ln in chk.split("\n") if "error" in ln.lower()] or ["commit check không thành công"]
            if res.errors:
                self.conn.send_config_set(["rollback 0"], exit_config_mode=False)   # hủy thay đổi
                self.conn.exit_config_mode()
                return res
            if confirm_minutes:
                res.output += "\n" + str(self.conn.commit(confirm=True, confirm_delay=int(confirm_minutes), comment="NetAutoConfig"))
                res.pending_confirm = True
            else:
                self.conn.commit(comment="NetAutoConfig")
            self.conn.exit_config_mode()
            res.saved = not res.pending_confirm
            return res
        res.output = self.conn.send_config_set(commands, read_timeout=max(60, self.p.timeout * 2))
        res.errors = find_errors(res.output, v.error_re)
        if res.errors:                                # lỗi -> KHÔNG lưu, khởi động lại sẽ trở về cũ
            return res
        if save and v.save == "netmiko":
            try:
                res.output += "\n" + str(self.conn.save_config())
                res.saved = True
            except NotImplementedError:
                cmd = SAVE_FALLBACK.get(v.key, "write memory")
                res.output += "\n" + self.conn.send_command_timing(cmd)
                res.saved = True
        elif v.save == "none":
            res.saved = True                          # MikroTik/OpenWrt... áp dụng và lưu ngay
        return res

    def confirm_commit(self) -> str:
        assert self.conn is not None, "Chưa kết nối"
        if self.vendor.save != "commit":
            return ""
        out = str(self.conn.commit(comment="NetAutoConfig confirm"))   # commit lần 2 = xác nhận
        self.conn.exit_config_mode()
        return out


# ---------------------------------------------------------------------------
class MockDriver(BaseDriver):
    """Thiết bị giả lập: mô phỏng cú pháp lệnh và định dạng cấu hình theo hãng đã chọn (xem simulator.py).

    Đặt tên thiết bị chứa 'fail' để mô phỏng sai mật khẩu, 'timeout' để mô phỏng hết giờ,
    'badcmd' để mô phỏng thiết bị báo lỗi với lệnh SNMP.
    Cấu hình giả lập được lưu vào file (nếu đã gọi configure) nên còn nguyên sau khi mở lại ứng dụng.
    """

    STORE: dict[str, list[str]] = {}
    PENDING: dict[str, dict] = {}            # commit confirmed chưa xác nhận: key -> {prev, deadline}
    STATE_FILE: Optional[Path] = None
    _loaded = False
    _lock = threading.RLock()

    def __init__(self, params: ConnParams):
        super().__init__(params)
        self.sim = make_simulator(self.vendor, params.name, params.model)
        self.connected = False

    # ---- lưu trạng thái ----
    @classmethod
    def configure(cls, path: Optional[Path]) -> None:
        with cls._lock:
            cls.STATE_FILE = Path(path) if path else None
            cls._loaded = False

    @classmethod
    def reset(cls) -> None:
        with cls._lock:
            cls.STORE.clear()
            cls.PENDING.clear()
            cls._loaded = False

    @classmethod
    def key_for(cls, host: str, vendor: str) -> str:
        return f"{host}|{vendor}"

    @classmethod
    def forget(cls, host: str, vendor: str) -> None:
        """Đưa thiết bị giả lập về cấu hình ban đầu."""
        with cls._lock:
            cls._load()
            cls.STORE.pop(cls.key_for(host, vendor), None)
            cls.PENDING.pop(cls.key_for(host, vendor), None)
            cls._save()

    @classmethod
    def expire_pending(cls, host: str, vendor: str) -> bool:
        """(Dùng khi thử) ép hết hạn commit confirmed -> thiết bị tự quay về cấu hình cũ."""
        with cls._lock:
            cls._load()
            k = cls.key_for(host, vendor)
            if k in cls.PENDING:
                cls.PENDING[k]["deadline"] = 0
                cls._expire(k)
                cls._save()
                return True
            return False

    @classmethod
    def _expire(cls, key: str) -> None:
        pend = cls.PENDING.get(key)
        if pend and time.time() >= pend["deadline"]:
            cls.STORE[key] = pend["prev"]
            del cls.PENDING[key]

    @classmethod
    def _load(cls) -> None:
        if cls._loaded:
            return
        cls._loaded = True
        if cls.STATE_FILE and cls.STATE_FILE.exists():
            try:
                data = json.loads(cls.STATE_FILE.read_text(encoding="utf-8"))
                if isinstance(data.get("state"), dict):
                    cls.STORE.update(data["state"])
                    cls.PENDING.update(data.get("pending", {}))
                else:                                     # định dạng cũ
                    cls.STORE.update(data)
            except (OSError, ValueError, AttributeError):
                pass

    @classmethod
    def _save(cls) -> None:
        if cls.STATE_FILE:
            try:
                cls.STATE_FILE.write_text(json.dumps({"state": cls.STORE, "pending": cls.PENDING}, ensure_ascii=False, indent=1),
                                          encoding="utf-8")
            except OSError:
                pass

    def _key(self) -> str:
        return self.key_for(self.p.host, self.p.vendor)

    def _state(self) -> list[str]:
        with self._lock:
            self._load()
            self._expire(self._key())
            if self._key() not in self.STORE:
                self.STORE[self._key()] = self.sim.baseline()
                self._save()
            return list(self.STORE[self._key()])

    # ---- giao diện driver ----
    def connect(self) -> None:
        n = self.p.name.lower()
        if "fail" in n:
            raise DriverError("Sai tên đăng nhập/mật khẩu (giả lập).")
        if "timeout" in n:
            raise DriverError("Hết thời gian chờ (giả lập).")
        if "lostaccess" in n and self._key() in self.PENDING:
            raise DriverError("Hết thời gian chờ: mất kết nối sau thay đổi (giả lập 'lostaccess').")
        self._state()
        self.connected = True

    def disconnect(self) -> None:
        self.connected = False

    def run_show(self, command: str) -> str:
        base, *pipes = [p.strip() for p in command.split("|")]
        n, state = norm_cmd(base), self._state()
        facts = norm_cmd(self.vendor.facts_cmd)
        if self.sim.is_config_cmd(base):
            text = self.sim.show_config(state)
        elif n == facts or n in ("show version", "display version", "/system resource print", "get system status"):
            text = self.sim.version_text()
            if self.p.model and "model" not in text.lower():
                text += f"\nModel: {self.p.model}"
        else:
            text = self.sim.show(base, state)
        return apply_pipes(text, pipes) if pipes else text

    def apply(self, commands: list[str], save: bool = True, confirm_minutes: int = 0) -> ApplyResult:
        with self._lock:
            old = self._state()
            new_state, output = self.sim.apply(old, commands)
            self.STORE[self._key()] = new_state
            res = ApplyResult(output=output, saved=save)
            res.errors = find_errors(output, self.vendor.error_re)
            if self.vendor.save == "commit" and not res.errors:
                res.output = (output + "\n" if output else "") + "configuration check succeeds"
                if confirm_minutes:                      # commit confirmed: tự quay lại nếu không xác nhận kịp
                    self.PENDING[self._key()] = {"prev": old, "deadline": time.time() + int(confirm_minutes) * 60}
                    res.pending_confirm, res.saved = True, False
            self._save()
        return res

    def confirm_commit(self) -> str:
        with self._lock:
            self._load()
            self.PENDING.pop(self._key(), None)
            self._save()
        return "commit complete"


def get_driver(params: ConnParams) -> BaseDriver:
    if params.simulated or params.vendor == "mock":
        return MockDriver(params)
    return NetmikoDriver(params)
