"""Quét mạng tìm thiết bị: kiểm tra cổng SSH/Telnet, đọc banner và SNMP sysDescr (tự cài đặt, không cần thư viện)."""
from __future__ import annotations

import ipaddress
import os
import random
import socket
import threading
from concurrent.futures import ThreadPoolExecutor
from typing import Callable, Optional

from drivers.vendors import BANNER_HINTS, SNMP_HINTS, guess_vendor

MAX_HOSTS = 4096


def expand_targets(text: str) -> list[str]:
    """Hỗ trợ: 192.168.1.0/24 | 192.168.1.10-192.168.1.50 | 192.168.1.10-50 | 10.0.0.1, 10.0.0.2"""
    hosts: list[str] = []
    for part in [p.strip() for p in text.replace(";", ",").replace("\n", ",").split(",") if p.strip()]:
        if "/" in part:
            net = ipaddress.ip_network(part, strict=False)
            if len(hosts) + net.num_addresses > MAX_HOSTS + 2:
                raise ValueError(f"Dải quét quá lớn (tối đa {MAX_HOSTS} địa chỉ).")
            hosts += [str(h) for h in (net.hosts() if net.num_addresses > 2 else net)]
        elif "-" in part:
            a, b = [x.strip() for x in part.split("-", 1)]
            start = ipaddress.ip_address(a)
            end = ipaddress.ip_address(b) if "." in b else ipaddress.ip_address(
                ".".join(a.split(".")[:3] + [b]))
            if int(end) < int(start):
                raise ValueError(f"Dải IP không hợp lệ: {part}")
            if int(end) - int(start) + len(hosts) > MAX_HOSTS:
                raise ValueError(f"Dải quét quá lớn (tối đa {MAX_HOSTS} địa chỉ).")
            hosts += [str(ipaddress.ip_address(i)) for i in range(int(start), int(end) + 1)]
        else:
            hosts.append(str(ipaddress.ip_address(part)))
        if len(hosts) > MAX_HOSTS:
            raise ValueError(f"Dải quét quá lớn (tối đa {MAX_HOSTS} địa chỉ).")
    return hosts


# ---------------- SNMP v2c GET tối giản ----------------
def _len(n: int) -> bytes:
    if n < 0x80:
        return bytes([n])
    b = n.to_bytes((n.bit_length() + 7) // 8, "big")
    return bytes([0x80 | len(b)]) + b


def _tlv(tag: int, body: bytes) -> bytes:
    return bytes([tag]) + _len(len(body)) + body


def _int(v: int) -> bytes:
    return _tlv(0x02, v.to_bytes(max(1, (v.bit_length() + 8) // 8), "big", signed=True))


def _oid(oid: str) -> bytes:
    parts = [int(x) for x in oid.strip(".").split(".")]
    body = bytes([parts[0] * 40 + parts[1]])
    for p in parts[2:]:
        chunk = [p & 0x7F]
        p >>= 7
        while p:
            chunk.append(0x80 | (p & 0x7F))
            p >>= 7
        body += bytes(reversed(chunk))
    return _tlv(0x06, body)


def build_snmp_get(community: str, oid: str, req_id: int) -> bytes:
    varbind = _tlv(0x30, _oid(oid) + _tlv(0x05, b""))
    pdu = _tlv(0xA0, _int(req_id) + _int(0) + _int(0) + _tlv(0x30, varbind))
    return _tlv(0x30, _int(1) + _tlv(0x04, community.encode()) + pdu)


def _read(buf: bytes, pos: int) -> tuple[int, bytes, int]:
    tag, ln = buf[pos], buf[pos + 1]
    pos += 2
    if ln & 0x80:
        n = ln & 0x7F
        ln = int.from_bytes(buf[pos:pos + n], "big")
        pos += n
    return tag, buf[pos:pos + ln], pos + ln


def _children(body: bytes) -> list[tuple[int, bytes]]:
    out, pos = [], 0
    while pos < len(body):
        tag, content, pos = _read(body, pos)
        out.append((tag, content))
    return out


def parse_snmp_response(buf: bytes) -> Optional[str]:
    try:
        _, body, _ = _read(buf, 0)
        kids = _children(body)                      # version, community, PDU
        pdu = next(c for t, c in kids if t == 0xA2)
        fields = _children(pdu)                     # reqid, err, errindex, varbinds
        if int.from_bytes(fields[1][1], "big", signed=True) != 0:
            return None
        vb = _children(fields[3][1])[0][1]
        _, value = _children(vb)                    # oid, value
        return value[1].decode("utf-8", "replace") if value[0] == 0x04 else None
    except Exception:
        return None


def snmp_get(ip: str, oid: str, community: str = "public", timeout: float = 1.5, port: int = 161) -> Optional[str]:
    req = build_snmp_get(community, oid, random.randint(1, 2**30))
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.settimeout(timeout)
        try:
            s.sendto(req, (ip, port))
            data, _ = s.recvfrom(4096)
        except (socket.timeout, OSError):
            return None
    return parse_snmp_response(data)


SYS_DESCR, SYS_NAME = "1.3.6.1.2.1.1.1.0", "1.3.6.1.2.1.1.5.0"


# ---------------- Quét ----------------
def _tcp_open(ip: str, port: int, timeout: float) -> bool:
    try:
        with socket.create_connection((ip, port), timeout=timeout):
            return True
    except OSError:
        return False


def _banner(ip: str, port: int, timeout: float) -> str:
    try:
        with socket.create_connection((ip, port), timeout=timeout) as s:
            s.settimeout(timeout)
            return s.recv(255).decode("utf-8", "replace").strip().split("\n")[0]
    except OSError:
        return ""


def probe_host(ip: str, community: str = "public", use_snmp: bool = True, timeout: float = 1.0) -> Optional[dict]:
    ports = [p for p in (22, 23) if _tcp_open(ip, p, timeout)]
    descr = name = None
    if use_snmp:
        descr = snmp_get(ip, SYS_DESCR, community, timeout + 0.5)
        if descr:
            name = snmp_get(ip, SYS_NAME, community, timeout + 0.5)
    if not ports and not descr:
        return None
    banner = _banner(ip, 22, timeout) if 22 in ports else ""
    vendor = guess_vendor(descr or "", SNMP_HINTS) or guess_vendor(banner, BANNER_HINTS)
    return {"ip": ip, "ports": ",".join(map(str, ports)), "banner": banner, "sysdescr": (descr or "")[:120],
            "name": name or ip, "vendor": vendor, "protocol": "ssh" if 22 in ports else "telnet"}


def scan(targets: list[str], community: str = "public", use_snmp: bool = True, workers: int = 64,
         progress: Optional[Callable[[int, int], None]] = None,
         cancel: Optional[threading.Event] = None) -> list[dict]:
    found: list[dict] = []
    done = 0
    lock = threading.Lock()

    def work(ip: str) -> None:
        nonlocal done
        if cancel is not None and cancel.is_set():
            return
        r = probe_host(ip, community, use_snmp)
        with lock:
            done += 1
            if r:
                found.append(r)
            if progress:
                progress(done, len(targets))

    with ThreadPoolExecutor(max_workers=workers) as ex:
        list(ex.map(work, targets))
    return sorted(found, key=lambda d: tuple(int(x) for x in d["ip"].split(".")))


def ping(host: str, count: int = 4, timeout_s: int = 2) -> str:
    """Ping bằng lệnh hệ điều hành (Windows/Linux/macOS)."""
    import subprocess
    flag = "-n" if os.name == "nt" else "-c"
    cmd = ["ping", flag, str(count), host]
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=count * timeout_s + 5)
        return (r.stdout or "") + (r.stderr or "")
    except Exception as e:
        return f"Không chạy được ping: {e}"
