"""C-DATA FD1601S-B1 Hardware Provisioning Executor with Host Key Pinning."""
from __future__ import annotations

import base64
from dataclasses import dataclass
import hashlib
import hmac
import re
import socket
import time

from app.core.device_credentials import decrypt_secret
from app.core.ssh_identity import _normalize_sha256_fingerprint
from app.core.cdata_fd1601s_discovery import normalize_pon_port, _fingerprint, _read


class CDataExecutionError(RuntimeError):
    pass


@dataclass(frozen=True)
class CDataProvisionResult:
    success: bool
    pon_port: str
    onu_id: int
    serial_number: str
    message: str
    raw_transcript: str = ""


def provision_cdata_onu(
    *,
    host: str,
    port: int,
    username: str,
    encrypted_secret: str,
    pinned_host_key: str | None,
    pon_port: str,
    onu_id: int,
    serial_number: str,
    profile_name: str | None = None,
) -> CDataProvisionResult:
    """Execute bounded, safe ONU registration on C-DATA FD1601S-B1 OLT.
    
    Commands sent:
    - enable
    - config
    - interface gpon 0/0
    - ont add {pon} {onu_id} sn-auth {sn}
    """
    normalized_pon = normalize_pon_port(pon_port)
    pon = normalized_pon.rsplit("/", 1)[1]
    
    if not (1 <= onu_id <= 128):
        raise CDataExecutionError(f"ONU ID {onu_id} tidak valid (harus 1-128).")
    
    clean_sn = serial_number.strip().upper()
    if not re.fullmatch(r"[A-Z0-9_-]{8,64}", clean_sn):
        raise CDataExecutionError(f"Serial number {serial_number} tidak valid.")

    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None:
        raise CDataExecutionError("Provisioning diblokir: fingerprint host key SSH belum dipin.")
    if not host or not (1 <= port <= 65535):
        raise CDataExecutionError("Provisioning diblokir: endpoint management OLT tidak valid.")

    transport = None
    channel = None
    sock = None
    transcript = ""
    try:
        import paramiko
        sock = socket.create_connection((host, port), timeout=10)
        transport = paramiko.Transport(sock)
        transport.banner_timeout = 10
        transport.auth_timeout = 10
        transport.start_client(timeout=10)

        if not hmac.compare_digest(_fingerprint(transport.get_remote_server_key()), expected):
            raise CDataExecutionError("Provisioning diblokir: fingerprint server tidak cocok dengan host key yang dipin.")

        secret = decrypt_secret(encrypted_secret)
        try:
            transport.auth_password(username, secret, fallback=False)
        finally:
            secret = ""

        if not transport.is_authenticated():
            raise CDataExecutionError("Provisioning gagal: autentikasi SSH ditolak.")

        channel = transport.open_session(timeout=10)
        channel.get_pty(term="vt100", width=160, height=40)
        channel.invoke_shell()
        _read(channel, 1.2)

        # Standard C-DATA command sequence for ONU registration
        commands = [
            ("enable", 1.2),
            ("config", 1.2),
            ("interface gpon 0/0", 1.2),
            (f"ont add {pon} {onu_id} sn-auth {clean_sn} ont-lineprofile-name 2p ont-srvprofile-name 2p", 3.0),
        ]

        for cmd, wait in commands:
            channel.send(cmd + "\r")
            out = _read(channel, wait)
            transcript += out
            # Check for immediate CLI error responses
            if any(err in out.lower() for err in ("invalid input", "incomplete command", "unknown command", "error", "failed")):
                raise CDataExecutionError(f"OLT CLI menolak command '{cmd}': {out.strip()}")

        # Verify registration via show ont info
        channel.send(f"show ont info {pon} {onu_id}\r")
        verify_out = _read(channel, 3.0)
        transcript += verify_out

        return CDataProvisionResult(
            success=True,
            pon_port=normalized_pon,
            onu_id=onu_id,
            serial_number=clean_sn,
            message=f"ONU ID {onu_id} berhasil didaftarkan di PON {normalized_pon} (SN: {clean_sn}).",
            raw_transcript=transcript,
        )

    except Exception as exc:
        if isinstance(exc, CDataExecutionError):
            raise
        raise CDataExecutionError(f"Koneksi/eksekusi OLT gagal: {exc}") from exc
    finally:
        if channel is not None:
            try:
                channel.close()
            except Exception:
                pass
        if transport is not None:
            try:
                transport.close()
            except Exception:
                pass
        if sock is not None:
            try:
                sock.close()
            except Exception:
                pass


def provision_cdata_pppoe(
    *,
    host: str,
    port: int,
    username: str,
    encrypted_secret: str,
    pinned_host_key: str | None,
    pon_port: str,
    onu_id: int,
    serial_number: str,
    pppoe_username: str,
    pppoe_password: str,
    vlan: int = 100,
    line_profile_name: str = "pppoe-100",
    service_profile_name: str = "2p",
) -> CDataProvisionResult:
    """Apply the verified C-DATA WAN PPPoE sequence to one existing ONU."""
    normalized_pon = normalize_pon_port(pon_port)
    pon = normalized_pon.rsplit("/", 1)[1]
    clean_sn = serial_number.strip().upper()
    if not (1 <= onu_id <= 128) or not re.fullmatch(r"[A-Z0-9_-]{8,64}", clean_sn):
        raise CDataExecutionError("Data ONU tidak valid.")
    if not re.fullmatch(r"[A-Za-z0-9_.@_-]{1,64}", pppoe_username):
        raise CDataExecutionError("Username PPPoE tidak valid.")
    if not 1 <= vlan <= 4094:
        raise CDataExecutionError("VLAN tidak valid.")
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None:
        raise CDataExecutionError("Fingerprint host key SSH belum dipin.")
    transport = channel = sock = None
    transcript = ""
    try:
        import paramiko
        sock = socket.create_connection((host, port), timeout=10)
        transport = paramiko.Transport(sock)
        transport.banner_timeout = transport.auth_timeout = 10
        transport.start_client(timeout=10)
        if not hmac.compare_digest(_fingerprint(transport.get_remote_server_key()), expected):
            raise CDataExecutionError("Fingerprint server OLT tidak cocok.")
        secret = decrypt_secret(encrypted_secret)
        try:
            transport.auth_password(username, secret, fallback=False)
        finally:
            secret = ""
        if not transport.is_authenticated():
            raise CDataExecutionError("Autentikasi SSH OLT ditolak.")
        channel = transport.open_session(timeout=10)
        channel.get_pty(term="vt100", width=180, height=60)
        channel.invoke_shell()
        _read(channel, 1.0)
        commands = [
            ("enable", 1.0),
            ("conf", 1.0),
            ("interface gpon 0/0", 1.0),
            (f"ont modify {pon} {onu_id} ont-lineprofile-name {line_profile_name} ont-srvprofile-name {service_profile_name}", 2.0),
            # legacy WAN syntax is not accepted by the live firmware.
            (f"ont ipconfig {pon} {onu_id} ip-index 0 pppoe username {pppoe_username} password {pppoe_password} vlan {vlan} priority 1", 2.5),
            (f"ont ipconfig {pon} {onu_id} ip-index 0 connection-type route", 1.5),
            ("exit", 1.0),
            ("save", 3.0),
            ("interface gpon 0/0", 1.0),
            (f"ont reboot {pon} {onu_id}", 10.0),
        ]
        for cmd, wait in commands:
            channel.send(cmd + "\r")
            out = _read(channel, wait)
            transcript += out
            low = out.lower()
            if any(err in low for err in ("unknown command", "invalid", "error", "failed", "incorrect")):
                if "already exists" not in low:
                    raise CDataExecutionError(f"OLT menolak tahap {cmd.split()[0]}.")
        return CDataProvisionResult(True, normalized_pon, onu_id, clean_sn,
            f"WAN PPPoE ONU {clean_sn} diterapkan pada VLAN {vlan} dan ONU direboot.", transcript)
    except CDataExecutionError:
        raise
    except Exception as exc:
        raise CDataExecutionError(f"Eksekusi WAN PPPoE OLT gagal: {exc}") from exc
    finally:
        for obj in (channel, transport, sock):
            try:
                if obj is not None:
                    obj.close()
            except Exception:
                pass


def reboot_cdata_onu(
    *, host: str, port: int, username: str, encrypted_secret: str,
    pinned_host_key: str | None, pon_port: str, onu_id: int,
) -> CDataProvisionResult:
    """Reboot one ONU in place; the ONU keeps its registration."""
    normalized_pon = normalize_pon_port(pon_port)
    pon = normalized_pon.rsplit("/", 1)[1]
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None:
        raise CDataExecutionError("Reboot diblokir: fingerprint host key SSH belum dipin.")
    if not (1 <= onu_id <= 128):
        raise CDataExecutionError(f"ONU ID {onu_id} tidak valid (harus 1-128).")

    return _run_cdata_cli(
        host=host, port=port, username=username, encrypted_secret=encrypted_secret,
        expected=expected, commands=("enable", "config", "interface gpon 0/0", f"ont reboot {pon} {onu_id}"),
        result_message=f"ONU {onu_id} pada PON {normalized_pon} sedang direboot.",
    )


def factory_reset_cdata_onu(
    *, host: str, port: int, username: str, encrypted_secret: str,
    pinned_host_key: str | None, pon_port: str, onu_id: int,
) -> CDataProvisionResult:
    """Factory-reset one ONU. Registration survives; customer config is wiped."""
    normalized_pon = normalize_pon_port(pon_port)
    pon = normalized_pon.rsplit("/", 1)[1]
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None:
        raise CDataExecutionError("Factory reset diblokir: fingerprint host key SSH belum dipin.")
    if not (1 <= onu_id <= 128):
        raise CDataExecutionError(f"ONU ID {onu_id} tidak valid (harus 1-128).")

    return _run_cdata_cli(
        host=host, port=port, username=username, encrypted_secret=encrypted_secret,
        expected=expected, commands=("enable", "config", "interface gpon 0/0", f"ont factory-reset {pon} {onu_id}"),
        result_message=f"Factory reset ONU {onu_id} pada PON {normalized_pon} dikirim.",
    )


def _run_cdata_cli(
    *, host: str, port: int, username: str, encrypted_secret: str, expected: str,
    commands: tuple[str, ...], result_message: str,
) -> CDataProvisionResult:
    """Shared bounded SSH session: pin host key, run commands, reject CLI errors."""
    transport = None
    channel = None
    sock = None
    transcript = ""
    try:
        import paramiko
        sock = socket.create_connection((host, port), timeout=10)
        transport = paramiko.Transport(sock)
        transport.banner_timeout = 10
        transport.auth_timeout = 10
        transport.start_client(timeout=10)

        if not hmac.compare_digest(_fingerprint(transport.get_remote_server_key()), expected):
            raise CDataExecutionError("Perintah diblokir: fingerprint server tidak cocok dengan host key yang dipin.")

        secret = decrypt_secret(encrypted_secret)
        try:
            transport.auth_password(username, secret, fallback=False)
        finally:
            secret = ""
        if not transport.is_authenticated():
            raise CDataExecutionError("Autentikasi SSH OLT ditolak.")

        channel = transport.open_session(timeout=10)
        channel.get_pty(term="vt100", width=160, height=40)
        channel.invoke_shell()
        _read(channel, 1.2)

        for cmd in commands:
            channel.send(cmd + "\r")
            out = _read(channel, 3.0 if "ont" in cmd else 1.2)
            transcript += out
            low = out.lower()
            if any(err in low for err in ("invalid input", "unknown command", "incomplete command", "error", "failed")):
                raise CDataExecutionError(f"OLT menolak command '{cmd}': {out.strip()}")

        pon = commands[-1].split()[-2]
        onu = commands[-1].split()[-1]
        return CDataProvisionResult(
            success=True, pon_port=f"0/0/{pon}", onu_id=int(onu),
            serial_number="", message=result_message, raw_transcript=transcript,
        )
    except CDataExecutionError:
        raise
    except Exception as exc:
        raise CDataExecutionError(f"Eksekusi perintah OLT gagal: {exc}") from exc
    finally:
        for obj in (channel, transport, sock):
            try:
                if obj is not None:
                    obj.close()
            except Exception:
                pass


def verify_cdata_onu(
    *, host: str, port: int, username: str, encrypted_secret: str,
    pinned_host_key: str | None, pon_port: str, onu_id: int, serial_number: str,
) -> bool:
    """Read back one ONU and require the expected serial to be present."""
    normalized_pon = normalize_pon_port(pon_port)
    pon = normalized_pon.rsplit("/", 1)[1]
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    clean_sn = serial_number.strip().upper()
    if expected is None or not clean_sn:
        raise CDataExecutionError("Verifikasi ONU diblokir: host-key atau SN belum siap.")
    import paramiko
    sock = socket.create_connection((host, port), timeout=10)
    transport = paramiko.Transport(sock)
    channel = None
    try:
        transport.start_client(timeout=10)
        if not hmac.compare_digest(_fingerprint(transport.get_remote_server_key()), expected):
            raise CDataExecutionError("Fingerprint server OLT tidak cocok saat verifikasi.")
        secret = decrypt_secret(encrypted_secret)
        try:
            transport.auth_password(username, secret, fallback=False)
        finally:
            secret = ""
        if not transport.is_authenticated():
            raise CDataExecutionError("Autentikasi SSH OLT ditolak saat verifikasi.")
        channel = transport.open_session(timeout=10)
        channel.get_pty(term="vt100", width=180, height=60)
        channel.invoke_shell()
        _read(channel, 1.0)
        for command, wait in (("enable", 1.0), ("config", 1.0), ("interface gpon 0/0", 1.0), (f"show ont info {pon} {onu_id}", 3.0)):
            channel.send(command + "\r")
            output = _read(channel, wait)
        upper = output.upper()
        online = bool(re.search(r"RUN\s+STATE\s*:\s*ONLINE", upper))
        return clean_sn in upper and online
    finally:
        for obj in (channel, transport, sock):
            try:
                if obj is not None:
                    obj.close()
            except Exception:
                pass


def read_cdata_ont_optical_power(
    *, host: str, port: int, username: str, encrypted_secret: str,
    pinned_host_key: str | None, pon_port: str, onu_id: int,
) -> tuple[str | None, str | None]:
    """Read ONU Rx/Tx optical power from a C-DATA FD1601S-B1 OLT."""
    normalized_pon = normalize_pon_port(pon_port)
    pon = normalized_pon.rsplit("/", 1)[1]
    if not (1 <= onu_id <= 128):
        raise CDataExecutionError("ONU ID tidak valid saat membaca level optik.")
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None:
        raise CDataExecutionError("Pembacaan redaman diblokir: host key OLT belum dipin.")
    transport = channel = sock = None
    try:
        import paramiko
        sock = socket.create_connection((host, port), timeout=10)
        transport = paramiko.Transport(sock)
        transport.banner_timeout = transport.auth_timeout = 10
        transport.start_client(timeout=10)
        if not hmac.compare_digest(_fingerprint(transport.get_remote_server_key()), expected):
            raise CDataExecutionError("Fingerprint server OLT tidak cocok saat membaca level optik.")
        secret = decrypt_secret(encrypted_secret)
        try:
            transport.auth_password(username, secret, fallback=False)
        finally:
            secret = ""
        if not transport.is_authenticated():
            raise CDataExecutionError("Autentikasi OLT ditolak saat membaca level optik.")
        channel = transport.open_session(timeout=10)
        channel.get_pty(term="vt100", width=180, height=60)
        channel.invoke_shell()
        _read(channel, 1.0)
        for command in ("enable", "config", "interface gpon 0/0"):
            channel.send(command + "\r")
            _read(channel, 1.0)
        channel.send(f"show ont optical-info {pon} {onu_id}\r")
        output = _read(channel, 3.0)
        if any(marker in output.lower() for marker in ("invalid input", "unknown command", "incomplete command", "not found")):
            raise CDataExecutionError("OLT menolak pembacaan informasi optik ONU.")
        def extract(label: str) -> str | None:
            match = re.search(rf"^\s*{label}\s*:\s*(-?\d+(?:\.\d+)?)\s*$", output, re.IGNORECASE | re.MULTILINE)
            return match.group(1) if match else None
        rx = extract(r"Rx optical power\(dBm\)")
        tx = extract(r"Tx optical power\(dBm\)")
        if rx is None and tx is None:
            raise CDataExecutionError("OLT tidak mengembalikan nilai Rx/Tx optik untuk ONU ini.")
        return rx, tx
    except CDataExecutionError:
        raise
    except Exception as exc:
        raise CDataExecutionError(f"Gagal membaca level optik ONU dari OLT: {exc}") from exc
    finally:
        for obj in (channel, transport, sock):
            try:
                if obj is not None:
                    obj.close()
            except Exception:
                pass


def deprovision_cdata_onu(
    *,
    host: str,
    port: int,
    username: str,
    encrypted_secret: str,
    pinned_host_key: str | None,
    pon_port: str,
    onu_id: int,
) -> CDataProvisionResult:
    """Safe rollback/deprovisioning on C-DATA OLT."""
    normalized_pon = normalize_pon_port(pon_port)
    pon = normalized_pon.rsplit("/", 1)[1]
    
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None:
        raise CDataExecutionError("Rollback diblokir: fingerprint host key SSH belum dipin.")

    transport = None
    channel = None
    sock = None
    transcript = ""
    try:
        import paramiko
        sock = socket.create_connection((host, port), timeout=10)
        transport = paramiko.Transport(sock)
        transport.start_client(timeout=10)

        if not hmac.compare_digest(_fingerprint(transport.get_remote_server_key()), expected):
            raise CDataExecutionError("Rollback diblokir: fingerprint server tidak cocok.")

        secret = decrypt_secret(encrypted_secret)
        try:
            transport.auth_password(username, secret, fallback=False)
        finally:
            secret = ""

        channel = transport.open_session(timeout=10)
        channel.get_pty(term="vt100", width=160, height=40)
        channel.invoke_shell()
        _read(channel, 1.2)

        commands = [
            ("enable", 1.2),
            ("config", 1.2),
            ("interface gpon 0/0", 1.2),
            (f"ont delete {pon} {onu_id}", 3.0),
        ]

        for cmd, wait in commands:
            channel.send(cmd + "\r")
            transcript += _read(channel, wait)

        return CDataProvisionResult(
            success=True,
            pon_port=normalized_pon,
            onu_id=onu_id,
            serial_number="",
            message=f"ONU ID {onu_id} pada PON {normalized_pon} berhasil dihapus (rollback).",
            raw_transcript=transcript,
        )
    except Exception as exc:
        raise CDataExecutionError(f"Rollback C-DATA gagal: {exc}") from exc
    finally:
        if transport is not None:
            transport.close()


def provision_cdata_fd1602_onu(
    *, host: str, port: int, username: str, encrypted_secret: str,
    pinned_host_key: str | None, pon_port: str, onu_id: int, serial_number: str,
    pppoe_username: str, pppoe_password: str, vlan: int = 100,
    line_profile_name: str = "lp_ppi", service_profile_name: str = "sp_ppi",
) -> CDataProvisionResult:
    """Provision FD1602 using its own CLI grammar and confirmed live profiles."""
    normalized = normalize_pon_port(pon_port)
    frame_slot, pon = normalized.rsplit('/', 1)[0], normalized.rsplit('/', 1)[1]
    clean_sn = serial_number.strip().upper()
    if frame_slot != "0/0" or not 1 <= int(pon) <= 2:
        raise CDataExecutionError("FD1602 hanya dikonfigurasi untuk PON 0/0/1-2 pada OLT ini.")
    if not 1 <= onu_id <= 128 or not re.fullmatch(r"[A-Z0-9_-]{8,64}", clean_sn):
        raise CDataExecutionError("ONU ID atau serial number tidak valid.")
    if not re.fullmatch(r"[A-Za-z0-9_.@_-]{1,64}", pppoe_username):
        raise CDataExecutionError("Username PPPoE tidak valid.")
    if not 1 <= vlan <= 4094:
        raise CDataExecutionError("VLAN PPPoE tidak valid.")
    for value in (line_profile_name, service_profile_name):
        if not re.fullmatch(r"[A-Za-z0-9_-]{1,32}", value):
            raise CDataExecutionError("Nama profil OLT tidak valid.")
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None:
        raise CDataExecutionError("Provisioning FD1602 diblokir: host key SSH belum dipin.")

    transport = channel = sock = None
    try:
        import paramiko
        sock = socket.create_connection((host, port), timeout=10)
        transport = paramiko.Transport(sock)
        transport.banner_timeout = transport.auth_timeout = 10
        transport.start_client(timeout=10)
        if not hmac.compare_digest(_fingerprint(transport.get_remote_server_key()), expected):
            raise CDataExecutionError("Fingerprint server FD1602 tidak cocok dengan host key yang dipin.")
        secret = decrypt_secret(encrypted_secret)
        try:
            transport.auth_password(username, secret, fallback=False)
        finally:
            secret = ""
        if not transport.is_authenticated():
            raise CDataExecutionError("Autentikasi SSH FD1602 ditolak.")
        channel = transport.open_session(timeout=10)
        channel.get_pty(term="vt100", width=180, height=60)
        channel.invoke_shell()
        _read(channel, 1.0)

        def send(command: str, wait: float = 2.0) -> str:
            channel.send(command + "\r")
            output = _read(channel, wait)
            low = output.lower()
            empty_ont_inventory = (
                command.casefold().startswith("show ont info ")
                and re.search(r"(?im)^\s*error:\s*there is no ont available\.?\s*$", output) is not None
            )
            cli_error = any(marker in low for marker in ("unknown command", "invalid input", "incorrect", "error:", "command incomplete"))
            if cli_error and not empty_ont_inventory:
                raise CDataExecutionError(f"OLT FD1602 menolak tahap {command.split()[0]}.")
            return output

        send("enable", 1.0)
        send("config", 1.0)
        def send_paged(command: str) -> str:
            channel.send(command + "\r")
            pages = []
            output = ""
            for _ in range(12):
                page = _read(channel, 1.5)
                pages.append(page)
                output += page
                if re.search(r"(?m)^[^\r\n]*\(config\)#\s*$", output):
                    break
                channel.send(" ")
            else:
                raise CDataExecutionError(f"Output profil OLT terlalu panjang pada tahap {command.split()[2]}.")
            low = output.lower()
            if any(marker in low for marker in ("unknown command", "invalid input", "incorrect", "error:", "command incomplete")):
                raise CDataExecutionError(f"OLT FD1602 menolak pembacaan profil {command.split()[-1]}.")
            return output

        line_profile = send_paged(f"show ont-line-profile gpon profile-name {line_profile_name}")
        srv_profile = send_paged(f"show ont-srv-profile gpon profile-name {service_profile_name}")
        if line_profile_name.casefold() not in line_profile.casefold():
            raise CDataExecutionError(f"Line profile {line_profile_name} tidak ditemukan atau tidak valid.")
        vlan_mapping = re.compile(rf"^\s*\d+\s+{vlan}\s+(?:-|\d+)\s+", re.M)
        management_mapping = re.compile(r"^\s*\d+\s+160\s+(?:-|\d+)\s+", re.M)
        if not vlan_mapping.search(line_profile):
            raise CDataExecutionError(f"Line profile {line_profile_name} tidak memetakan VLAN {vlan}; ONU tidak diubah.")
        if not management_mapping.search(line_profile):
            raise CDataExecutionError(f"Line profile {line_profile_name} tidak memetakan VLAN manajemen 160; ONU tidak diubah.")
        if service_profile_name.casefold() not in srv_profile.casefold():
            raise CDataExecutionError(f"Service profile {service_profile_name} tidak ditemukan atau tidak valid.")

        send("interface gpon 0/0", 1.0)
        inventory = send(f"show ont info {pon} all", 2.5)
        rows = re.findall(r"^\s*\S+\s+\d+\s+(\d+)\s+([A-Z0-9_-]{8,64})\s+.*$", inventory, re.I | re.M)
        same_serial = [(int(row_id), sn.upper()) for row_id, sn in rows if sn.upper() == clean_sn]
        id_occupants = [sn.upper() for row_id, sn in rows if int(row_id) == onu_id]
        if same_serial and same_serial != [(onu_id, clean_sn)]:
            raise CDataExecutionError("Serial ONT sudah terdaftar pada ONU ID lain di PON ini.")
        if id_occupants and id_occupants != [clean_sn]:
            raise CDataExecutionError("ONU ID yang dipilih sudah digunakan serial ONT lain.")
        if not same_serial:
            found = send(f"show ont autofind {pon} all", 2.5)
            if not re.search(rf"^\s*SN\s*:\s*{re.escape(clean_sn)}\s*(?:\(|$)", found, re.I | re.M):
                raise CDataExecutionError("Serial ONT tidak ditemukan pada Auto SN di PON yang dipilih; ONU tidak didaftarkan.")
            send(f"ont add {pon} {onu_id} sn-auth {clean_sn} ont-lineprofile-name {line_profile_name} ont-srvprofile-name {service_profile_name}", 3.0)

        existing_wan = send(f"show ont wan config {pon} {onu_id}", 2.5)
        required_bindings = ("eth-1", "eth-2", "eth-3", "eth-4", "ssid-1", "ssid-2", "ssid-3", "ssid-4",
                             "5g-ssid-1", "5g-ssid-2", "5g-ssid-3", "5g-ssid-4")
        existing_lower = existing_wan.casefold()
        wan_matches = (
            "no wan exist" not in existing_lower
            and pppoe_username.casefold() in existing_lower
            and re.search(rf"\b{vlan}\b", existing_wan) is not None
            and "pppoe" in existing_lower
            and "connect mode                     : route" in existing_lower
            and "connect type                     : internet" in existing_lower
            and all(binding in existing_lower for binding in required_bindings)
        )
        if not wan_matches:
            send(f"ont wan {pon} {onu_id} 1 vlan {vlan} ipv4 pppoe username {pppoe_username} password {pppoe_password}", 3.0)
        send(f"ont wan {pon} {onu_id} 1 option service-type internet", 2.0)
        send(f"ont wan {pon} {onu_id} 1 option binding eth 1-4", 2.0)
        send(f"ont wan {pon} {onu_id} 1 option binding ssid 1-4", 2.0)
        send(f"ont wan {pon} {onu_id} 1 option binding 5g-ssid 1-4", 2.0)
        send(f"ont ipconfig {pon} {onu_id} ip-index 0 dhcp vlan 160 priority 0", 2.0)
        send(f"ont ipconfig {pon} {onu_id} ip-index 0 connection-type route", 2.0)
        send("exit", 1.0)
        save_output = send("save", 5.0)
        if re.search(r"(?:\[y/n\]|\(y/n\)|yes/no)", save_output, re.I):
            channel.send("y\r")
            _read(channel, 5.0)
        if not same_serial or not wan_matches:
            send("interface gpon 0/0", 1.0)
            send(f"ont reboot {pon} {onu_id}", 10.0)
            time.sleep(15)
            channel.send("interface gpon 0/0\r")
            _read(channel, 1.0)
        else:
            send("interface gpon 0/0", 1.0)
        wan_config = send(f"show ont wan config {pon} {onu_id}", 3.0)
        ip_config = send(f"show ont ipconfig {pon} {onu_id}", 3.0)
        if (pppoe_username.casefold() not in wan_config.casefold()
                or not re.search(rf"\b{vlan}\b", wan_config)
                or "pppoe" not in wan_config.casefold()):
            raise CDataExecutionError("OLT belum mengonfirmasi WAN PPPoE dan VLAN pada FD1602.")
        if "dhcp" not in ip_config.casefold() or not re.search(r"manage vlan\s*:\s*160", ip_config, re.I):
            raise CDataExecutionError("OLT belum mengonfirmasi DHCP manajemen pada VLAN 160.")
        return CDataProvisionResult(True, normalized, onu_id, clean_sn,
            f"ONU {clean_sn} terdaftar; WAN PPPoE VLAN {vlan} dan DHCP manajemen VLAN 160 terverifikasi pada FD1602.", "")
    except CDataExecutionError:
        raise
    except Exception as exc:
        raise CDataExecutionError(f"Eksekusi FD1602 gagal: {exc}") from exc
    finally:
        for obj in (channel, transport, sock):
            try:
                if obj is not None:
                    obj.close()
            except Exception:
                pass


def verify_cdata_fd1602_onu(
    *, host: str, port: int, username: str, encrypted_secret: str,
    pinned_host_key: str | None, pon_port: str, onu_id: int, serial_number: str,
) -> bool:
    """Read-only FD1602 ONT check using its GPON inventory row format."""
    normalized = normalize_pon_port(pon_port)
    pon = normalized.rsplit('/', 1)[1]
    clean_sn = serial_number.strip().upper()
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None or not clean_sn or not 1 <= onu_id <= 128:
        raise CDataExecutionError("Verifikasi FD1602 diblokir: host key, SN, atau ONU ID tidak valid.")
    transport = channel = sock = None
    try:
        import paramiko
        sock = socket.create_connection((host, port), timeout=8)
        transport = paramiko.Transport(sock)
        transport.banner_timeout = transport.auth_timeout = 8
        transport.start_client(timeout=8)
        if not hmac.compare_digest(_fingerprint(transport.get_remote_server_key()), expected):
            raise CDataExecutionError("Fingerprint server FD1602 tidak cocok saat verifikasi.")
        secret = decrypt_secret(encrypted_secret)
        try:
            transport.auth_password(username, secret, fallback=False)
        finally:
            secret = ""
        if not transport.is_authenticated():
            raise CDataExecutionError("Autentikasi SSH FD1602 ditolak saat verifikasi.")
        channel = transport.open_session(timeout=8)
        channel.get_pty(term="vt100", width=180, height=50)
        channel.invoke_shell()
        _read(channel, 0.8)
        for command in ("enable", "config", "interface gpon 0/0"):
            channel.send(command + "\r")
            _read(channel, 0.8)
        channel.send(f"show ont info {pon} all\r")
        output = _read(channel, 3.0)
        low = output.lower()
        if any(marker in low for marker in ("unknown command", "incorrect port", "command incomplete", "error:")):
            raise CDataExecutionError("OLT menolak pembacaan inventory ONT FD1602.")
        row = re.compile(
            rf"^\s*\S+\s+{re.escape(pon)}\s+{onu_id}\s+{re.escape(clean_sn)}\s+\S+\s+Online(?:\s|$)",
            re.I | re.M,
        )
        return bool(row.search(output))
    except CDataExecutionError:
        raise
    except Exception as exc:
        raise CDataExecutionError(f"Gagal memverifikasi ONU FD1602: {exc}") from exc
    finally:
        for obj in (channel, transport, sock):
            try:
                if obj is not None:
                    obj.close()
            except Exception:
                pass
