"""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 urllib.parse import urlsplit

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


def _wait_for_management_dhcp(send, pon: str, onu_id: int, management_vlan: int, *, timeout: float = 90.0, interval: float = 2.0) -> str:
    """Poll OLT readback after saving management DHCP configuration."""
    deadline = time.monotonic() + timeout
    while True:
        output = send(f"show ont ipconfig {pon} {onu_id}", 2.5)
        if "dhcp" in output.casefold() and re.search(rf"manage vlan\s*:\s*{management_vlan}\b", output, re.I):
            return output
        if time.monotonic() >= deadline:
            raise CDataExecutionError(f"OLT belum mengonfirmasi DHCP manajemen ONT pada VLAN {management_vlan}.")
        time.sleep(interval)


def _fd1602_line_profile_has_mapping(profile: str, mapping_index: int, vlan: int, gemport: int) -> bool:
    """Check a C-DATA FD1602 line-profile table inside the requested GEM block.

    FD1602 prints GEM ID as a section heading, then mapping rows as
    ``Mapping-ID VLAN Priority Port-ID Veip-ID``. GEM ID is not repeated on
    each row, so requiring it in the row falsely rejects valid profiles.
    """
    gem_headers = list(re.finditer(r"(?im)^\s*<Gem ID\s+(\d+)\s*>", profile))
    for index, header in enumerate(gem_headers):
        if int(header.group(1)) != gemport:
            continue
        end = gem_headers[index + 1].start() if index + 1 < len(gem_headers) else len(profile)
        next_tcont = re.search(r"(?im)^\s*<T-CONT\b", profile[header.end():end])
        if next_tcont:
            end = header.end() + next_tcont.start()
        block = profile[header.end():end]
        table = re.search(r"(?im)^\s*Mapping-ID\s+VLAN\b[^\n]*", block)
        if not table:
            continue
        found_rows = False
        for line in block[table.end():].splitlines():
            if re.match(r"^\s*-{5,}", line):
                if found_rows:
                    break
                continue
            row = re.match(r"^\s*(\d+)\s+(\d+)\b", line)
            if row:
                found_rows = True
                if int(row.group(1)) == mapping_index and int(row.group(2)) == vlan:
                    return True
    return False


def _parse_cdata_gem_vlan_mappings(info: str, gemport: int) -> dict[int, int]:
    """Parse only the selected GEM mapping table; fail closed on missing data."""
    gem = re.search(rf"<Gem ID\s+{gemport}\s*>", info, re.I)
    if not gem:
        raise CDataExecutionError("GEM layanan ONT tidak ditemukan pada pembacaan OLT.")
    tail = info[gem.end():]
    boundary = re.search(r"(?im)^\s*<(?:Gem ID|T-CONT)\b", tail)
    if boundary:
        tail = tail[:boundary.start()]
    header = re.search(r"(?im)^\s*Mapping-ID\s+VLAN[^\n]*", tail)
    if not header:
        raise CDataExecutionError("Tabel pemetaan VLAN ONT tidak dapat dibaca.")
    result = {}
    for line in tail[header.end():].splitlines():
        if re.match(r"^\s*-{5,}", line) and result:
            break
        match = re.match(r"^\s*(\d+)\s+(\d+)\b", line)
        if match:
            index, vlan = int(match.group(1)), int(match.group(2))
            if index in result and result[index] != vlan:
                raise CDataExecutionError("Pemetaan VLAN ONT tidak konsisten.")
            result[index] = vlan
    return result


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


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("Autentikasi SSH OLT ditolak.")

        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)

        # Register only when the selected ONU ID is empty. Re-entry after
        # deleting a BestWeb customer must safely reuse the same ONU/SN.
        commands = [
            ("enable", 1.2),
            ("config", 1.2),
            ("interface gpon 0/0", 1.2),
        ]
        for cmd, wait in commands:
            channel.send(cmd + "\r")
            out = _read(channel, wait)
            transcript += out
            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()}")

        channel.send(f"show ont info {pon} {onu_id}\r")
        verify_out = _read(channel, 3.0)
        transcript += verify_out
        serial_match = re.search(r"(?im)^\s*SN\s*:\s*([A-Z0-9_-]+)", verify_out)
        existing_sn = serial_match.group(1).upper() if serial_match else None
        if existing_sn and existing_sn != clean_sn:
            raise CDataExecutionError("ONU ID yang dipilih sudah terdaftar dengan serial ONT lain.")
        if not existing_sn:
            cmd = f"ont add {pon} {onu_id} sn-auth {clean_sn} ont-lineprofile-name 2p ont-srvprofile-name 2p"
            channel.send(cmd + "\r")
            out = _read(channel, 3.0)
            transcript += out
            if any(err in out.lower() for err in ("invalid input", "incomplete command", "unknown command", "error", "failed")):
                raise CDataExecutionError(f"OLT CLI menolak command registrasi ONU: {out.strip()}")
            channel.send(f"show ont info {pon} {onu_id}\r")
            verify_out = _read(channel, 3.0)
            transcript += verify_out
            serial_match = re.search(r"(?im)^\s*SN\s*:\s*([A-Z0-9_-]+)", verify_out)
            if not serial_match or serial_match.group(1).upper() != clean_sn:
                raise CDataExecutionError("OLT belum mengonfirmasi serial ONT setelah registrasi.")

        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,
    use_ipconfig_pppoe: bool = False,
    management_only: bool = False,
    line_profile_name: str = "pppoe-100",
    service_profile_name: str = "2p",
    management_vlan: int | None = None, management_gemport: int = 1, management_mapping_index: int = 3,
) -> CDataProvisionResult:
    """Create and verify an actual ONT WAN object on C-DATA FD1601S-B1.

    The older ``ont ipconfig ... pppoe`` syntax only populated IP host fields
    on this firmware; it did not create a WAN connection. Existing WANs are
    preserved unless they already match this customer's PPPoE service.
    """
    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 layanan atau manajemen tidak valid.")
    if management_vlan is not None and (not 1 <= management_vlan <= 4094 or not 1 <= management_gemport <= 255 or not 1 <= management_mapping_index <= 8):
        raise CDataExecutionError("GEM port atau mapping index manajemen tidak valid.")
    if management_only and management_vlan is None:
        raise CDataExecutionError("VLAN manajemen diperlukan sebelum sinkronisasi WAN ONT.")
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None:
        raise CDataExecutionError("Fingerprint 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 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)

        def send(command: str, wait: float = 2.0) -> str:
            channel.send(command + "\r")
            output = _read(channel, wait)
            low = output.casefold()
            no_ip_config_yet = (
                command.casefold().startswith("show ont ipconfig ")
                and re.search(r"(?im)^\s*error:\s*the ont does not configure ip information\.?\s*$", output) is not None
            )
            if any(marker in low for marker in ("unknown command", "invalid input", "incorrect", "error:", "command incomplete", "failed")) and not no_ip_config_yet:
                safe_output = output.replace(pppoe_username, "[redacted]").replace(pppoe_password, "[redacted]")
                safe_command = command.replace(pppoe_username, "[redacted]").replace(pppoe_password, "[redacted]")
                raise CDataExecutionError(f"OLT menolak perintah '{safe_command[:100]}': {safe_output.strip()[:400]}")
            return output

        for command in ("enable", "config", "interface gpon 0/0"):
            send(command, 1.0)
        if management_vlan is not None:
            current_ip_config = send(f"show ont ipconfig {pon} {onu_id}", 2.5)
            if not ("dhcp" in current_ip_config.casefold()
                    and re.search(rf"manage vlan\s*:\s*{management_vlan}\b", current_ip_config, re.I)):
                send(f"ont ipconfig {pon} {onu_id} ip-index 0 dhcp vlan {management_vlan} priority 0", 2.0)
                send(f"ont ipconfig {pon} {onu_id} ip-index 0 connection-type route", 2.0)
                if not management_only:
                    send(f"ont gemport mapping {pon} {onu_id} {management_gemport} {management_mapping_index} vlan {management_vlan}", 2.0)
                send("exit", 1.0)
                saved_management = send("save", 5.0)
                if re.search(r"(?:\[y/n\]|\(y/n\)|yes/no)", saved_management, re.I):
                    channel.send("y\r")
                    _read(channel, 5.0)
                send("interface gpon 0/0", 1.0)
                _wait_for_management_dhcp(send, pon, onu_id, management_vlan)
        if management_only:
            info = send(f"show ont info {pon} {onu_id}", 2.5)
            serial_match = re.search(r"(?im)^\s*SN\s*:\s*([A-Z0-9_-]+)", info)
            if not serial_match or serial_match.group(1).upper() != clean_sn:
                raise CDataExecutionError("Serial ONT tidak cocok saat memeriksa pemetaan VLAN.")
            mappings = _parse_cdata_gem_vlan_mappings(info, management_gemport)
            if vlan not in mappings.values():
                raise CDataExecutionError("VLAN layanan belum dipetakan pada GEM ONT; konfigurasi lain tidak diubah.")
            if management_vlan not in mappings.values():
                if management_mapping_index in mappings:
                    raise CDataExecutionError("Index pemetaan manajemen sudah dipakai VLAN lain; tidak ditimpa.")
                send(f"ont gemport mapping {pon} {onu_id} {management_gemport} {management_mapping_index} vlan {management_vlan}", 2.0)
                send("exit", 1.0)
                saved = send("save", 5.0)
                if re.search(r"(?:\[y/n\]|\(y/n\)|yes/no)", saved, re.I):
                    channel.send("y\r")
                    _read(channel, 5.0)
                send("interface gpon 0/0", 1.0)
                info = send(f"show ont info {pon} {onu_id}", 2.5)
                if management_vlan not in _parse_cdata_gem_vlan_mappings(info, management_gemport).values():
                    raise CDataExecutionError("OLT belum mengonfirmasi pemetaan VLAN manajemen.")
            return CDataProvisionResult(
                True, normalized_pon, onu_id, clean_sn,
                "Manajemen dan pemetaan VLAN ONT terverifikasi; WAN Internet akan disinkronkan.",
                "", False,
            )
        if use_ipconfig_pppoe:
            # An IP-host PPPoE session does not establish that Wi-Fi traffic
            # uses that WAN. This legacy path cannot claim service readiness.
            current_ip = send(f"show ont ipconfig {pon} {onu_id}", 2.5)
            index1 = re.search(r"(?im)^\s*ONT IP host index\s*:\s*1\s*$", current_ip)
            if index1:
                end_candidates = [m.start() for pattern in (
                    r"(?im)^\s*ONT IP host index\s*:", r"(?im)^\s*Internet IP index\s*:"
                ) for m in re.finditer(pattern, current_ip[index1.end():])]
                end = index1.end() + min(end_candidates) if end_candidates else len(current_ip)
                current_index = current_ip[index1.start():end]
                matches_ipconfig = (
                    re.search(r"(?im)^\s*ONT config type\s*:\s*PPPOE\s*$", current_index) is not None
                    and pppoe_username.casefold() in current_index.casefold()
                    and re.search(rf"(?im)^\s*ONT manage VLAN\s*:\s*{vlan}\s*$", current_index) is not None
                    and pppoe_password in current_index
                )
                if not matches_ipconfig:
                    raise CDataExecutionError("IP host Internet index 1 ONT sudah dipakai konfigurasi lain; tidak ditimpa.")
            else:
                if not re.search(r"(?im)^\s*Internet IP index\s*:\s*--\s*$", current_ip):
                    raise CDataExecutionError("Index Internet ONT tidak kosong atau tidak dapat dibaca; tidak ditimpa.")
                send(f"ont ipconfig {pon} {onu_id} ip-index 1 pppoe username {pppoe_username} password {pppoe_password} vlan {vlan} priority 0", 3.0)
                send("exit", 1.0)
                saved = send("save", 5.0)
                if re.search(r"(?:\[y/n\]|\(y/n\)|yes/no)", saved, re.I):
                    channel.send("y\r")
                    _read(channel, 5.0)
                send("interface gpon 0/0", 1.0)
            verified_ip = send(f"show ont ipconfig {pon} {onu_id}", 3.0)
            index1 = re.search(r"(?im)^\s*ONT IP host index\s*:\s*1\s*$", verified_ip)
            if not index1:
                raise CDataExecutionError("OLT belum mengonfirmasi IP host PPPoE ONT pada index 1.")
            end_candidates = [m.start() for pattern in (
                r"(?im)^\s*ONT IP host index\s*:", r"(?im)^\s*Internet IP index\s*:"
            ) for m in re.finditer(pattern, verified_ip[index1.end():])]
            end = index1.end() + min(end_candidates) if end_candidates else len(verified_ip)
            verified_index = verified_ip[index1.start():end]
            config_ok = (
                re.search(r"(?im)^\s*ONT config type\s*:\s*PPPOE\s*$", verified_index) is not None
                and pppoe_username.casefold() in verified_index.casefold()
                and re.search(rf"(?im)^\s*ONT manage VLAN\s*:\s*{vlan}\s*$", verified_index) is not None
                and pppoe_password in verified_index
            )
            if not config_ok:
                raise CDataExecutionError("OLT belum mengonfirmasi PPPoE, username, password, dan VLAN ONT.")
            address_match = re.search(r"(?im)^\s*ONT IP\s*:\s*([^\s]+)", verified_index)
            runtime_ready = bool(address_match and address_match.group(1) not in {"-", "0.0.0.0"})
            return CDataProvisionResult(True, normalized_pon, onu_id, clean_sn,
                f"IP host PPPoE ONU {clean_sn} VLAN {vlan} tersimpan; akses Internet Wi-Fi belum terverifikasi.",
                "", False)

        current = send(f"show ont wan config {pon} {onu_id}", 2.5)
        lower = current.casefold()
        no_wan = "no wan exist" in lower
        bindings = ("eth-1", "eth-2", "eth-3", "eth-4", "ssid-1", "ssid-2", "ssid-3",
                    "5g-ssid-1", "5g-ssid-2", "5g-ssid-3")
        matches = (
            not no_wan
            and pppoe_username.casefold() in lower
            and re.search(rf"\b{vlan}\b", current) is not None
            and "pppoe" in lower
            and re.search(r"(?im)^\s*connect mode\s*:\s*route\s*$", current) is not None
            and re.search(r"(?im)^\s*connect type\s*:\s*(?:tr069[- ]?)?internet\s*$", current) is not None
            and all(binding in lower for binding in bindings)
        )
        if not no_wan and not matches:
            raise CDataExecutionError("WAN ONU sudah ada tetapi tidak cocok; tidak ditimpa untuk menjaga layanan lain.")
        runtime = send(f"show ont wan status {pon} {onu_id}", 2.5)
        runtime_ready = (
            re.search(r"(?im)^\s*Connection status\s*:\s*enable\s*$", runtime) is not None
            and re.search(r"(?im)^\s*Connect mode\s*:\s*route\s*$", runtime) is not None
            and re.search(r"(?im)^\s*Connect type\s*:\s*TR069[- ]?Internet\s*$", runtime) is not None
            and re.search(rf"(?im)^\s*VLAN id\s*:\s*{vlan}\s*$", runtime) is not None
            and re.search(r"(?im)^\s*DSP\s+mode\s*:\s*PPPoE\s*$", runtime) is not None
        )
        # OLT saved configuration and ONT runtime are separate read models.
        # Reapply the exact same customer WAN when saved settings match but
        # runtime is disabled/bridged; never overwrite a different WAN.
        if no_wan or not runtime_ready:
            # This firmware exposes WAN activation through the CLI enable command;
            # the documented modify/connection-status command is absent here.
            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-3", 2.0)
            send(f"ont wan {pon} {onu_id} 1 option binding 5g-ssid 1-3", 2.0)
            send("exit", 1.0)
            saved = send("save", 5.0)
            if re.search(r"(?:\[y/n\]|\(y/n\)|yes/no)", saved, re.I):
                channel.send("y\r")
                _read(channel, 5.0)
            send("interface gpon 0/0", 1.0)
            current = send(f"show ont wan config {pon} {onu_id}", 3.0)
            lower = current.casefold()
            if (pppoe_username.casefold() not in lower
                    or re.search(rf"\b{vlan}\b", current) is None
                    or "pppoe" not in lower
                    or re.search(r"(?im)^\s*connect mode\s*:\s*route\s*$", current) is None
                    or re.search(r"(?im)^\s*connect type\s*:\s*(?:tr069[- ]?)?internet\s*$", current) is None
                    or not all(binding in lower for binding in bindings)):
                raise CDataExecutionError("OLT belum mengonfirmasi WAN PPPoE/VLAN dan binding yang diminta.")
        runtime = send(f"show ont wan status {pon} {onu_id}", 2.5)
        runtime_ready = (
            re.search(r"(?im)^\s*Connection status\s*:\s*enable\s*$", runtime) is not None
            and re.search(r"(?im)^\s*Connect mode\s*:\s*route\s*$", runtime) is not None
            and re.search(r"(?im)^\s*Connect type\s*:\s*TR069[- ]?Internet\s*$", runtime) is not None
            and re.search(rf"(?im)^\s*VLAN id\s*:\s*{vlan}\s*$", runtime) is not None
            and re.search(r"(?im)^\s*DSP\s+mode\s*:\s*PPPoE\s*$", runtime) is not None
        )
        runtime_note = "runtime Internet aktif" if runtime_ready else "runtime ONT belum aktif; BestWeb akan memulihkan dan memeriksa ulang"
        return CDataProvisionResult(True, normalized_pon, onu_id, clean_sn,
            f"WAN PPPoE ONU {clean_sn} VLAN {vlan}; {runtime_note}.", "", runtime_ready)
    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 configure_cdata_acs(
    *, host: str, port: int, username: str, encrypted_secret: str,
    pinned_host_key: str | None, pon_port: str, onu_id: int, acs_url: str,
) -> CDataProvisionResult:
    """Configure the bounded TR-069 controls of one already-registered ONU."""
    normalized_pon = normalize_pon_port(pon_port)
    pon = normalized_pon.rsplit("/", 1)[1]
    parsed = urlsplit((acs_url or "").strip())
    if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password:
        raise CDataExecutionError("URL CWMP/ACS tidak valid.")
    if not (1 <= onu_id <= 128):
        raise CDataExecutionError("ONU ID tidak valid.")
    expected = _normalize_sha256_fingerprint(pinned_host_key)
    if expected is None:
        raise CDataExecutionError("Aktivasi ACS diblokir: fingerprint host key SSH belum dipin.")
    acs_port = parsed.port or (443 if parsed.scheme == "https" else 80)
    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("Aktivasi ACS diblokir: 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=160, height=40)
        channel.invoke_shell()
        _read(channel, 1.0)

        def send(command: str, wait: float = 2.0) -> str:
            channel.send(command + "\r")
            output = _read(channel, wait)
            if any(token in output.casefold() for token in ("unknown command", "invalid input", "incorrect", "error:", "failed")):
                raise CDataExecutionError(f"OLT menolak konfigurasi ACS: {output.strip()[:260]}")
            return output

        for command in ("enable", "config", "interface gpon 0/0"):
            send(command, 1.0)
        send(f"ont tr069 {pon} {onu_id} tr069-management enable")
        send(f"ont tr069 {pon} {onu_id} acs-url {parsed.geturl()}")
        send(f"ont tr069 {pon} {onu_id} acs-port {acs_port}")
        send(f"ont tr069 {pon} {onu_id} ip-index 0")
        send(f"ont tr069 {pon} {onu_id} inform enable")
        send("exit", 1.0)
        saved = send("save", 5.0)
        if re.search(r"(?:\[y/n\]|\(y/n\)|yes/no)", saved, re.I):
            channel.send("y\r")
            _read(channel, 5.0)
        send("interface gpon 0/0", 1.0)
        verification = send(f"show ont tr069 {pon} {onu_id}", 2.5)
        low = verification.casefold()
        if "management" not in low or "enable" not in low or parsed.hostname.casefold() not in low:
            raise CDataExecutionError("OLT belum mengonfirmasi konfigurasi TR-069 yang diminta.")
        return CDataProvisionResult(True, normalized_pon, onu_id, "", "TR-069 aktif; menunggu Inform ONT ke GenieACS.")
    except CDataExecutionError:
        raise
    except Exception as exc:
        raise CDataExecutionError(f"Aktivasi ACS gagal: {exc}") from exc
    finally:
        for item in (channel, transport, sock):
            try:
                if item is not None:
                    item.close()
            except Exception:
                pass


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:
    """Poll OLT read-only until the expected ONU serial is online or times out."""
    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 in ("enable", "config", "interface gpon 0/0"):
            channel.send(command + "\r")
            _read(channel, 1.0)
        deadline = time.monotonic() + 90.0
        while True:
            channel.send(f"show ont info {pon} {onu_id}\r")
            output = _read(channel, 3.0)
            upper = output.upper()
            if clean_sn in upper and re.search(r"RUN\s+STATE\s*:\s*ONLINE", upper):
                return True
            if time.monotonic() >= deadline:
                return False
            time.sleep(3.0)
    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,
    serial_number: str | None = None,
) -> CDataProvisionResult:
    """Remove only the intended ONU; an already absent ONU is idempotent."""
    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.")
    if not 1 <= onu_id <= 128:
        raise CDataExecutionError("ONU ID tidak valid.")
    wanted = (serial_number or "").strip().upper()
    if not re.fullmatch(r"[A-Z0-9_-]{8,64}", wanted):
        raise CDataExecutionError("Serial ONT diperlukan untuk memastikan target penghapusan.")
    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("Rollback diblokir: fingerprint server 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)

        def send(command, delay=2.0, *, allow_absent=False):
            channel.send(command + "\r")
            output = _read(channel, delay)
            absent = re.search(r"(?i)there is no ont available", output) is not None
            # Offline ONTs on this C-DATA firmware prepend this informational
            # ranging line to a valid `show ont info` response.  It is not a
            # rejected CLI command, and the serial below remains the guard
            # that prevents deleting the wrong ONU.
            ranging_unavailable = (
                command.casefold().startswith("show ont info ")
                and re.search(r"(?i)error:\s*ranging info get failed\.", output) is not None
            )
            bad = any(x in output.casefold() for x in
                      ("invalid input", "unknown command", "incomplete command", "error", "failed"))
            if bad and not ranging_unavailable and not (allow_absent and absent):
                raise CDataExecutionError(f"OLT menolak perintah '{command}': {output.strip()[:300]}")
            return output

        for command in ("enable", "config", "interface gpon 0/0"):
            send(command, 1.0)
        observed = send(f"show ont info {pon} {onu_id}", 2.5, allow_absent=True)
        if re.search(r"(?i)there is no ont available", observed):
            return CDataProvisionResult(True, normalized_pon, onu_id, wanted,
                                       "ONU sudah tidak terdaftar di OLT.")
        match = re.search(r"(?im)^\s*SN\s*:\s*([A-Z0-9_-]+)", observed)
        if not match or match.group(1).upper() != wanted:
            raise CDataExecutionError("Serial ONT di OLT tidak cocok; penghapusan dibatalkan.")
        send(f"ont delete {pon} {onu_id}", 3.0)
        verify = send(f"show ont info {pon} {onu_id}", 2.5, allow_absent=True)
        if not re.search(r"(?i)there is no ont available", verify):
            raise CDataExecutionError("OLT belum mengonfirmasi ONU terhapus; data pelanggan dipertahankan.")
        send("exit", 1.0)
        saved = send("save", 5.0)
        if re.search(r"(?:\[y/n\]|\(y/n\)|yes/no)", saved, re.I):
            channel.send("y\r")
            _read(channel, 5.0)
        return CDataProvisionResult(True, normalized_pon, onu_id, wanted,
                                   f"ONU {onu_id} pada PON {normalized_pon} terhapus dan terverifikasi.")
    except CDataExecutionError:
        raise
    except Exception as exc:
        raise CDataExecutionError(f"Rollback C-DATA gagal: {exc}") from exc
    finally:
        for obj in (channel, transport, sock):
            try:
                if obj is not None:
                    obj.close()
            except Exception:
                pass


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,
    management_vlan: int | None = None, management_gemport: int = 1, management_mapping_index: int = 3,
    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 atau manajemen tidak valid.")
    if management_vlan is not None and (not 1 <= management_vlan <= 4094 or not 1 <= management_gemport <= 255 or not 1 <= management_mapping_index <= 8):
        raise CDataExecutionError("GEM port atau mapping index manajemen 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)
        last_stage = "CLI session"

        def safe_stage(command: str) -> str:
            tokens = command.casefold().split()
            if not tokens:
                return "CLI command"
            if tokens[0] == "show":
                return " ".join(tokens[:3])
            if tokens[0] == "ont" and len(tokens) > 1:
                return " ".join(tokens[:2])
            return tokens[0]

        def send(command: str, wait: float = 2.0) -> str:
            nonlocal last_stage
            last_stage = safe_stage(command)
            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
            )
            no_ip_config_yet = (
                command.casefold().startswith("show ont ipconfig ")
                and re.search(r"(?im)^\s*error:\s*the ont does not configure ip information\.?\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 or no_ip_config_yet):
                raise CDataExecutionError(f"OLT FD1602 menolak tahap {last_stage}.")
            return output

        send("enable", 1.0)
        send("config", 1.0)
        def send_paged(command: str) -> str:
            nonlocal last_stage
            last_stage = safe_stage(command)
            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)
        if management_vlan is not None:
            if not _fd1602_line_profile_has_mapping(
                line_profile, management_mapping_index, management_vlan, management_gemport
            ):
                raise CDataExecutionError(
                    f"Line profile {line_profile_name} tidak memetakan VLAN manajemen {management_vlan}; ONU tidak diubah."
                )
        if not vlan_mapping.search(line_profile):
            raise CDataExecutionError(f"Line profile {line_profile_name} tidak memetakan VLAN {vlan}; 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)

        if management_vlan is not None:
            current_ip_config = send(f"show ont ipconfig {pon} {onu_id}", 2.5)
            if not ("dhcp" in current_ip_config.casefold()
                    and re.search(rf"manage vlan\s*:\s*{management_vlan}\b", current_ip_config, re.I)):
                send(f"ont ipconfig {pon} {onu_id} ip-index 0 dhcp vlan {management_vlan} priority 0", 2.0)
                send(f"ont ipconfig {pon} {onu_id} ip-index 0 connection-type route", 2.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()
        no_wan_exists = "no wan exist" in existing_lower
        wan_matches = (
            not no_wan_exists
            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 re.search(r"(?im)^\s*connect mode\s*:\s*route\s*$", existing_wan) is not None
            # This OLT reports the service type it writes as either
            # "Internet" or "TR069-Internet".  Both represent the same
            # routed PPPoE WAN; treating the latter as a mismatch makes a
            # valid existing customer WAN fail every later onboarding retry.
            and re.search(r"(?im)^\s*connect type\s*:\s*(?:tr069[- ]?)?internet\s*$", existing_wan) is not None
            and all(binding in existing_lower for binding in required_bindings)
        )
        if not no_wan_exists and not wan_matches:
            raise CDataExecutionError("WAN aktif di ONU tidak sesuai PPPoE/VLAN/binding pelanggan; konfigurasi ditahan agar layanan lain tidak tertimpa.")
        # The FD1602 can retain a correct saved WAN while its runtime side is
        # still disabled/bridged after registration or reboot. Re-send the
        # same customer WAN in that state; a saved tuple alone cannot create a
        # PPPoE session.
        current_runtime = send(f"show ont wan status {pon} {onu_id}", 2.5)
        runtime_ready_before = (
            re.search(r"(?im)^\s*Connection status\s*:\s*enable\s*$", current_runtime) is not None
            and re.search(r"(?im)^\s*Connect mode\s*:\s*route\s*$", current_runtime) is not None
            and re.search(rf"(?im)^\s*VLAN id\s*:\s*{vlan}\s*$", current_runtime) is not None
            and re.search(r"(?im)^\s*DSP\s+mode\s*:\s*PPPoE\s*$", current_runtime) is not None
        )
        if no_wan_exists or not runtime_ready_before:
            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("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)
        rebooted = not same_serial or not wan_matches or not runtime_ready_before
        if rebooted:
            send("interface gpon 0/0", 1.0)
            send(f"ont reboot {pon} {onu_id}", 10.0)
            channel.send("interface gpon 0/0\r")
            _read(channel, 1.0)
        else:
            send("interface gpon 0/0", 1.0)

        if management_vlan is not None:
            _wait_for_management_dhcp(send, pon, onu_id, management_vlan)

        # ONTs may take longer than a fixed sleep to return after reboot. Do not
        # report a false failure while the OLT is still applying WAN settings.
        ready_deadline = time.monotonic() + (90.0 if rebooted else 20.0)
        online_row = re.compile(
            rf"^\s*\S+\s+{pon}\s+{onu_id}\s+{re.escape(clean_sn)}\s+\S+\s+Online(?:\s|$)",
            re.I | re.M,
        )
        while True:
            inventory = send(f"show ont info {pon} all", 2.5)
            if online_row.search(inventory):
                break
            if time.monotonic() >= ready_deadline:
                raise CDataExecutionError("ONU belum kembali online di OLT setelah konfigurasi/reboot.")
            time.sleep(2.0)

        while True:
            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 management_vlan is None or ("dhcp" in ip_config.casefold() and re.search(rf"manage vlan\s*:\s*{management_vlan}\b", ip_config, re.I)):
                break
            if time.monotonic() >= ready_deadline:
                raise CDataExecutionError(f"OLT belum mengonfirmasi DHCP manajemen pada VLAN {management_vlan}.")
            time.sleep(2.0)
        # Verify runtime administrative state separately from the saved WAN
        # configuration. A saved PPPoE tuple can coexist with a disabled WAN,
        # in which case the MikroTik secret is provisioned but no PPPoE session
        # can ever appear.
        wan_runtime = send(f"show ont wan status {pon} {onu_id}", 3.0)
        connection_status = re.search(
            r"(?im)^\s*Connection status\s*:\s*(\S+)\s*$", wan_runtime
        )
        if not connection_status:
            raise CDataExecutionError(
                "OLT tidak mengembalikan Connection status WAN ONT; provisioning ditahan."
            )
        if connection_status.group(1).casefold() != "enable":
            raise CDataExecutionError(
                "WAN PPPoE ONT masih dinonaktifkan pada OLT (Connection status: "
                f"{connection_status.group(1)}); konfigurasi tersimpan saja tidak cukup untuk membentuk sesi."
            )
        if (not re.search(r"(?im)^\s*Connect mode\s*:\s*route\s*$", wan_runtime)
                or not re.search(rf"(?im)^\s*VLAN id\s*:\s*{vlan}\s*$", wan_runtime)
                or not re.search(r"(?im)^\s*DSP mode\s*:\s*PPPoE\s*$", wan_runtime)):
            raise CDataExecutionError(
                "Runtime WAN ONT tidak cocok dengan mode route, PPPoE, dan VLAN pelanggan."
            )
        return CDataProvisionResult(True, normalized, onu_id, clean_sn,
            f"ONU {clean_sn} terdaftar; WAN PPPoE VLAN {vlan} dan status runtime enable terverifikasi pada FD1602.", "")
    except CDataExecutionError:
        raise
    except Exception as exc:
        raise CDataExecutionError(f"Eksekusi FD1602 gagal saat {last_stage}: {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, require_wan_runtime: bool = True,
) -> 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,
        )
        # Inventory Online only proves GPON registration. On FD1602 a saved
        # WAN may still be administratively disabled (and shown as bridge),
        # which cannot establish a PPPoE session.
        if not row.search(output):
            return False
        if not require_wan_runtime:
            return True
        channel.send(f"show ont wan status {pon} {onu_id}\r")
        wan_runtime = _read(channel, 3.0)
        low = wan_runtime.lower()
        if any(marker in low for marker in ("unknown command", "incorrect port", "command incomplete", "error:")):
            raise CDataExecutionError("OLT menolak pembacaan status WAN runtime FD1602.")
        return bool(
            re.search(r"(?im)^\s*Connection status\s*:\s*enable\s*$", wan_runtime)
            and re.search(r"(?im)^\s*Connect mode\s*:\s*route\s*$", wan_runtime)
            and re.search(r"(?im)^\s*DSP\s+mode\s*:\s*PPPoE\s*$", wan_runtime)
        )
    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
