"""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


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 save; never repeat the configuration command."""
    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} setelah {int(timeout)} detik."
            )
        time.sleep(interval)


@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("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",
    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 or (management_vlan is not None and not 1 <= management_vlan <= 4094):
        raise CDataExecutionError("VLAN layanan atau manajemen tidak valid.")
    if management_vlan is not None and (not 1 <= management_gemport <= 255 or not 1 <= management_mapping_index <= 8):
        raise CDataExecutionError("GEM port atau mapping index manajemen 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
    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)
        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:
            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 tr069-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 _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,
) -> 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,
    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 or (management_vlan is not None and not 1 <= management_vlan <= 4094):
        raise CDataExecutionError("VLAN PPPoE atau manajemen tidak valid.")
    if management_vlan is not None and (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)
        management_mapping = re.compile(
            rf"^\s*{management_mapping_index}\s+{management_vlan}\s+{management_gemport}(?:\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 management_vlan is not None and not management_mapping.search(line_profile):
            raise CDataExecutionError(
                f"Line profile {line_profile_name} harus memetakan VLAN manajemen {management_vlan} "
                f"ke GEM {management_gemport}/index {management_mapping_index}; 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()
        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
            and re.search(r"(?im)^\s*connect type\s*:\s*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.")
        if no_wan_exists:
            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)

        if management_vlan is not None:
            current_ip_config = send(f"show ont ipconfig {pon} {onu_id}", 2.5)
            ip_management_matches = (
                "dhcp" in current_ip_config.casefold()
                and re.search(rf"manage vlan\\s*:\\s*{management_vlan}\\b", current_ip_config, re.I) is not None
            )
            if not ip_management_matches:
                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)
        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
        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)

        # 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/IP 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)
            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:
                break
            ip_config = send(f"show ont ipconfig {pon} {onu_id}", 3.0)
            if "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)
        return CDataProvisionResult(True, normalized, onu_id, clean_sn,
            f"ONU {clean_sn} terdaftar; WAN PPPoE VLAN {vlan} 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,
) -> 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
