from fastapi import APIRouter, Request, Form, Depends, status, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from sqlalchemy.exc import IntegrityError
from app.core.database import get_db
from app.models.models import Customer, CustomerType, CustomerStatus, ProvisioningJob, ProvisioningEvent, ServicePackage, ODP, OLTDevice, MikrotikDevice, Site, AuditLog, DeviceCredential
from app.core.provisioning import provision_customer
from app.core.customer_identity import validate_nik, customer_code_for, default_pppoe_username, encrypt_default_pppoe_password, decrypt_pppoe_password, allocate_customer_id
from app.core.device_credentials import encrypt_secret
from app.core.olt_adapters import get_olt_adapter, UnsupportedOLTError
from app.core.onboarding import run_onboarding, refresh_customer_online_status
from app.core.olt_vendor_profiles import get_vendor_profile, vendor_profiles_for_ui
from app.core.cdata_fd1601s_discovery import (
    DiscoveryUnavailableError,
    InvalidPonPortError,
    discover_unregistered_onts,
    normalize_pon_port,
)
from app.core.security import require_roles, get_current_user
from datetime import datetime, timezone
import asyncio
import json
import os
import uuid

router = APIRouter(dependencies=[Depends(require_roles("admin_cs"))])
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))

def _site_id_for_olt(olt, sites):
    import re
    device_words = set(re.findall(r"[a-z0-9]+", " ".join(filter(None, [olt.name, olt.location, olt.pop_name])).casefold()))
    matches = []
    for site in sites:
        site_words = set(re.findall(r"[a-z0-9]+", " ".join(filter(None, [site.code, site.name, site.area])).casefold()))
        site_words = {word for word in site_words if len(word) >= 4 and word not in {"site", "mikrotik"}}
        if site_words & device_words:
            matches.append(site.id)
    return matches[0] if len(matches) == 1 else None

@router.get("/api/customers/{customer_id}/acs")
async def customer_acs_status(customer_id: int, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    customer = await db.get(Customer, customer_id)
    if not customer or customer.is_archived:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if not customer.ont_sn:
        return {"connected": False, "registered": False, "message": "Serial ONT belum tercatat di pelanggan."}
    from app.core.genieacs import GenieACSUnavailable, get_customer_device
    try:
        device = await asyncio.to_thread(get_customer_device, customer.ont_sn)
    except GenieACSUnavailable as exc:
        return JSONResponse(status_code=503, content={"connected": False, "registered": False, "message": str(exc)})
    if device is None:
        return {"connected": False, "registered": False, "message": "ONT belum ditemukan di GenieACS berdasarkan serial number."}
    last_inform = device.get("last_inform")
    fresh = False
    if last_inform:
        try:
            from datetime import timedelta
            stamp = datetime.fromisoformat(last_inform.replace("Z", "+00:00"))
            fresh = (datetime.now(timezone.utc) - stamp) <= timedelta(minutes=15)
        except (ValueError, TypeError):
            pass
    return {"connected": fresh, "registered": True, "message": "Inform ONT diterima ACS" if fresh else "ONT terdaftar; menunggu Inform terbaru", **device}


async def _latest_acs_setup_event(db, customer_id: int):
    return await db.scalar(select(ProvisioningEvent).where(
        ProvisioningEvent.customer_id == customer_id,
        ProvisioningEvent.target == "acs_configuration",
    ).order_by(ProvisioningEvent.id.desc()).limit(1))


@router.get("/api/customers/{customer_id}/acs/configuration")
async def customer_acs_configuration_status(customer_id: int, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    customer = await db.get(Customer, customer_id)
    if not customer or customer.is_archived:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    event = await _latest_acs_setup_event(db, customer_id)
    state = {"running": "processing", "processing": "processing", "success": "success", "failed": "failed"}.get(event.status if event else "", "not_configured")
    return {"status": state, "message": event.message if event else "Konfigurasi ACS belum dimulai."}


@router.post("/api/customers/{customer_id}/acs/configuration")
async def configure_customer_acs(customer_id: int, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    customer = await db.get(Customer, customer_id)
    if not customer or customer.is_archived:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if not customer.ont_sn or not customer.olt_port or not customer.onu_id or not customer.olt_device_id:
        raise HTTPException(status_code=422, detail="Data ONT, OLT, PON, atau ONU ID belum lengkap.")
    latest = await _latest_acs_setup_event(db, customer_id)
    if latest and latest.status == "processing":
        raise HTTPException(status_code=409, detail="Konfigurasi ACS sedang diproses.")
    olt = await db.get(OLTDevice, customer.olt_device_id)
    if not olt or not olt.is_active or olt.vendor.casefold() != "c-data" or olt.model.upper() not in {"FD1601S-B1", "FD1602S-B1"}:
        raise HTTPException(status_code=409, detail="Konfigurasi ACS manual saat ini memerlukan OLT C-DATA FD1601S-B1 atau FD1602S-B1.")
    credential = await db.get(DeviceCredential, olt.credential_id) if olt.credential_id else None
    pinned = os.getenv(f"OLT_{olt.id}_SSH_HOST_KEY_SHA256")
    if not olt.is_active or olt.management_protocol != "ssh" or not credential or not credential.is_active or not pinned:
        raise HTTPException(status_code=409, detail="OLT, credential SSH, atau host key belum siap.")
    running = ProvisioningEvent(customer_id=customer.id, target="acs_configuration", status="processing",
        vendor=olt.vendor, olt_device_id=olt.id, adapter_key="cdata-tr069-manual",
        payload_summary=json.dumps({"pon_port": customer.olt_port, "onu_id": customer.onu_id, "serial": customer.ont_sn}),
        message="Konfigurasi TR-069 sedang dikirim dan diverifikasi pada OLT.")
    db.add(running)
    await db.commit()
    stage_message = ""
    try:
        from app.core.cdata_executor import configure_cdata_acs
        result = await asyncio.to_thread(configure_cdata_acs, host=olt.host, port=olt.api_port or 22,
            username=credential.username, encrypted_secret=credential.encrypted_secret, pinned_host_key=pinned,
            pon_port=customer.olt_port, onu_id=customer.onu_id,
            acs_url=os.getenv("GENIEACS_CWMP_URL", "http://161.248.172.10:7547"))
        stage_message = result.message
        # ACS is WiFi/LAN management only.  Subscriber PPPoE is owned by the
        # FD1602 IP Host provisioning path; attempting a second ACS WAN write
        # creates a false ACS failure and can interfere with a healthy session.
        final_status = "success"
        message = f"{stage_message} ACS siap untuk pengaturan WiFi/LAN; PPPoE pelanggan tidak diubah."
    except Exception as exc:
        final_status = "failed"
        prefix = f"{stage_message} " if stage_message else ""
        message = f"{prefix}Aktivasi ACS WiFi/LAN gagal: {str(exc)[:400]}"
    db.add(ProvisioningEvent(customer_id=customer.id, target="acs_configuration", status=final_status,
        vendor=olt.vendor, olt_device_id=olt.id, adapter_key="cdata-tr069-manual",
        payload_summary=running.payload_summary, message=message))
    await db.commit()
    return {"status": final_status, "message": message}


@router.post("/api/customers/{customer_id}/acs/refresh")
async def customer_acs_refresh(customer_id: int, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    customer = await db.get(Customer, customer_id)
    if not customer or customer.is_archived:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    from app.core.genieacs import GenieACSUnavailable, refresh_customer_device
    try:
        result = await asyncio.to_thread(refresh_customer_device, customer.ont_sn or "")
    except GenieACSUnavailable as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc
    return {**result, "message": "Permintaan refresh data ONT dikirim ke GenieACS. Hasil tampil setelah ONT mengirim Inform."}

@router.get("/api/customers/{customer_id}/acs/wifi")
async def customer_acs_wifi(customer_id: int, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    customer = await db.get(Customer, customer_id)
    if not customer or customer.is_archived: raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if not customer.ont_sn: return {"found": False, "data": [], "message": "Serial ONT belum tercatat."}
    from app.core.genieacs import GenieACSUnavailable, get_wifi_configuration
    try: return await asyncio.to_thread(get_wifi_configuration, customer.ont_sn)
    except GenieACSUnavailable as exc: raise HTTPException(status_code=503, detail=str(exc)) from exc


@router.post("/api/customers/{customer_id}/acs/wifi")
async def customer_acs_wifi_update(customer_id: int, payload: dict, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    customer = await db.get(Customer, customer_id)
    if not customer or customer.is_archived: raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if not customer.ont_sn: raise HTTPException(status_code=422, detail="Serial ONT belum tercatat.")
    try: wlan = int(payload.get("wlan"))
    except (TypeError, ValueError): raise HTTPException(status_code=422, detail="WLAN tidak valid.")
    ssid = payload.get("ssid")
    password = payload.get("password")
    open_network = payload.get("open_network") if "open_network" in payload else None
    if open_network is not None and not isinstance(open_network, bool): raise HTTPException(status_code=422, detail="Mode keamanan WiFi tidak valid.")
    if ssid is not None and (not isinstance(ssid, str) or not ssid.strip() or len(ssid) > 32): raise HTTPException(status_code=422, detail="SSID wajib 1-32 karakter.")
    if password is not None and (not isinstance(password, str) or len(password) < 8 or len(password) > 63): raise HTTPException(status_code=422, detail="Password WiFi harus 8-63 karakter.")
    if open_network is False and not password: raise HTTPException(status_code=422, detail="Masukkan password 8-63 karakter untuk mengaktifkan WPA2.")
    if open_network is True and password: raise HTTPException(status_code=422, detail="Password harus dikosongkan saat jaringan dibuka.")
    from app.core.genieacs import GenieACSUnavailable, set_wifi_configuration
    try:
        result = await asyncio.to_thread(set_wifi_configuration, customer.ont_sn, wlan=wlan, ssid=ssid.strip() if isinstance(ssid, str) else None, password=password, open_network=open_network)
    except GenieACSUnavailable as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc
    customer.acs_wifi_status = "queued" if result.get("queued") else "pending_verification"
    customer.acs_last_sync = datetime.now(timezone.utc)
    action = "acs_wifi_open" if open_network is True else ("acs_wifi_wpa2" if open_network is False else "acs_wifi_update")
    db.add(AuditLog(user_id=user.id, action=action, entity="customer", entity_id=customer.id, detail=f"WLAN {wlan}"))
    await db.commit()
    if result.get("changed") is False:
        result["message"] = "Nilai WiFi yang diminta sudah sesuai dengan laporan ONT."
    elif result.get("queued"):
        result["message"] = "Task diterima GenieACS; menunggu ONT menerima task dan melaporkan hasil melalui Inform."
    else:
        result["message"] = "Task GenieACS selesai; baca-balik ONT akan memastikan nilai yang diterapkan."
    return result


@router.post("/api/customers/{customer_id}/acs/dhcp-server")
async def customer_acs_dhcp_server_update(customer_id: int, payload: dict, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    customer = await db.get(Customer, customer_id)
    if not customer or customer.is_archived:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if not customer.ont_sn:
        raise HTTPException(status_code=422, detail="Serial ONT belum tercatat.")
    enabled = payload.get("enabled")
    if not isinstance(enabled, bool):
        raise HTTPException(status_code=422, detail="Status DHCP server harus aktif atau nonaktif.")
    from app.core.genieacs import GenieACSUnavailable, set_dhcp_server_configuration
    try:
        result = await asyncio.to_thread(set_dhcp_server_configuration, customer.ont_sn, enabled=enabled)
    except GenieACSUnavailable as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc
    customer.acs_wifi_status = "queued" if result.get("queued") else "pending_verification"
    customer.acs_last_sync = datetime.now(timezone.utc)
    db.add(AuditLog(
        user_id=user.id, action="acs_dhcp_server_toggle", entity="customer",
        entity_id=customer.id, detail="DHCP server " + ("aktif" if enabled else "nonaktif"),
    ))
    await db.commit()
    result["message"] = (
        "Status DHCP Server sudah sesuai dengan nilai terbaru yang dilaporkan ONT."
        if not result.get("changed") else
        "Perintah DHCP server diterima GenieACS; baca ulang setelah ONT mengirim Inform untuk memverifikasi hasil."
    )
    return result


@router.get("/add-customer", response_class=HTMLResponse)
async def add_customer_page(request: Request, db: AsyncSession = Depends(get_db)):
    packages = (await db.execute(select(ServicePackage).where(
        ServicePackage.is_active == True,
        ServicePackage.service_type == "bulanan_ppp",
        ServicePackage.service_mode == "private_pppoe",
    ).order_by(ServicePackage.name))).scalars().all()
    odps = (await db.execute(select(ODP).where(ODP.is_active == True).order_by(ODP.code))).scalars().all()
    olts = (await db.execute(select(OLTDevice).where(OLTDevice.is_active == True).order_by(OLTDevice.name))).scalars().all()
    mikrotiks = (await db.execute(select(MikrotikDevice).where(MikrotikDevice.is_active == True).order_by(MikrotikDevice.name))).scalars().all()
    sites = (await db.execute(select(Site).where(Site.is_active == True))).scalars().all()
    routes = (await db.execute(select(Customer.odp_id, Customer.olt_device_id, Customer.mikrotik_device_id).where(
        Customer.is_archived == False, Customer.odp_id.is_not(None)
    ))).all()
    routes_by_odp = {}
    for odp_id, olt_id, mt_id in routes:
        routes_by_odp.setdefault(odp_id, []).append((olt_id, mt_id))
    odp_site_ids, odp_mikrotik_ids = {}, {}
    for odp in odps:
        mapped_mt = odp.mikrotik_device_id
        known = routes_by_odp.get(odp.id, [])
        known_mts = {mt_id for _, mt_id in known if mt_id is not None}
        if mapped_mt is None and len(known_mts) == 1:
            mapped_mt = next(iter(known_mts))
        mt = await db.get(MikrotikDevice, mapped_mt) if mapped_mt else None
        site_id = mt.site_id if mt else None
        if site_id is None:
            known_olts = {olt_id for olt_id, mt_id in known if olt_id is not None and (mapped_mt is None or mt_id == mapped_mt)}
            if len(known_olts) == 1:
                known_olt = await db.get(OLTDevice, next(iter(known_olts)))
                site_id = _site_id_for_olt(known_olt, sites) if known_olt else None
        if site_id:
            odp_site_ids[odp.id] = site_id
        if mapped_mt:
            odp_mikrotik_ids[odp.id] = mapped_mt
    olt_site_ids = {olt.id: _site_id_for_olt(olt, sites) for olt in olts}
    mikrotik_site_ids = {mt.id: mt.site_id for mt in mikrotiks if mt.site_id}
    return templates.TemplateResponse(request=request, name="add_customer.html", context={
        "packages": packages, "odps": odps, "olts": olts, "mikrotiks": mikrotiks,
        "odp_site_ids": odp_site_ids, "odp_mikrotik_ids": odp_mikrotik_ids,
        "olt_site_ids": olt_site_ids, "mikrotik_site_ids": mikrotik_site_ids,
        "vendor_profiles": vendor_profiles_for_ui(), "submission_key": str(uuid.uuid4())
    })


@router.get("/api/olt-devices/{olt_device_id}/auto-sn")
async def auto_sn_discovery(
    olt_device_id: int,
    pon_port: str,
    db: AsyncSession = Depends(get_db),
):
    """Read unregistered ONT serials through the pinned, read-only OLT session."""
    try:
        normalized_port = normalize_pon_port(pon_port)
    except InvalidPonPortError as exc:
        raise HTTPException(status_code=422, detail=str(exc)) from exc

    olt = await db.get(OLTDevice, olt_device_id)
    if olt is None or not olt.is_active:
        raise HTTPException(status_code=404, detail="OLT tidak tersedia")
    profile = get_vendor_profile(olt.vendor, olt.model)
    if profile is None or profile.key not in {"cdata-fd1601s-b1", "cdata-fd1602s-b1"} or profile.discovery_state != "ready":
        raise HTTPException(status_code=409, detail="Auto SN belum tersedia untuk model OLT ini")
    pon_number = int(normalized_port.rsplit("/", 1)[1])
    max_pon = 2 if profile.key == "cdata-fd1602s-b1" else 1
    if pon_number > max_pon:
        raise HTTPException(status_code=422, detail=f"OLT {olt.name} hanya memiliki PON 1 sampai {max_pon}.")
    if not olt.credential_id:
        return JSONResponse(status_code=503, content={"available": False, "results": [], "olt_device_id": olt_device_id, "pon_port": normalized_port, "reason": "Credential Vault OLT belum terikat."})
    credential = await db.get(DeviceCredential, olt.credential_id)
    if credential is None or not credential.is_active or credential.protocol.casefold() != "ssh":
        return JSONResponse(status_code=503, content={"available": False, "results": [], "olt_device_id": olt_device_id, "pon_port": normalized_port, "reason": "Credential SSH OLT tidak tersedia."})
    try:
        results = await asyncio.to_thread(
            discover_unregistered_onts,
            host=olt.host,
            port=olt.api_port,
            username=credential.username,
            encrypted_secret=credential.encrypted_secret,
            pinned_host_key=os.getenv(f"OLT_{olt.id}_SSH_HOST_KEY_SHA256"),
            pon_port=normalized_port,
        )
    except DiscoveryUnavailableError as exc:
        return JSONResponse(status_code=503, content={"available": False, "results": [], "olt_device_id": olt_device_id, "pon_port": normalized_port, "reason": str(exc)})
    return {"available": True, "results": [item.__dict__ for item in results], "olt_device_id": olt_device_id, "pon_port": normalized_port}

@router.post("/add-customer")
async def add_customer(
    request: Request,
    submission_key: str = Form(...),
    name: str = Form(...),
    nik: str = Form(...),
    address: str = Form(...),
    phone: str = Form(...),
    cust_type: str = Form(...),
    play_type: str = Form("1play"),
    harga_paket: int = Form(...),
    service_profile: str = Form(None),
    package_id: int | None = Form(None),
    provisioning_mode: str = Form("private_pppoe"),
    service_modes_json: str = Form("[\"pppoe\"]"),
    ont_management_mode: str = Form("none"),
    management_pppoe_username: str = Form(None),
    management_pppoe_password: str = Form(None),
    pppoe_username: str = Form(None),
    pppoe_password: str = Form(None),
    onu_id: int | None = Form(None),
    wan_vlan: int = Form(175),
    service_vlan: int = Form(175),
    pppoe_vlan: int = Form(100),
    hotspot_vlan: int = Form(150),
    iptv_vlan: int = Form(15),
    olt_vlan_profile: str = Form("bnbv1009"),
    ont_sn: str = Form(None),
    ont_brand: str = Form(None),
    olt_device_id: int | None = Form(None),
    mikrotik_device_id: int | None = Form(None),
    olt_fields_json: str = Form("{}"),
    olt_vendor: str = Form("ZTE"),
    olt_model: str = Form("C320"),
    olt_port: str = Form(None),
    odp_info: str = Form(None),
    odp_id: int | None = Form(None),
    odp_latitude: str = Form(None),
    odp_longitude: str = Form(None),
    ont_sn_mode: str = Form("manual"),
    onu_id_mode: str = Form("manual"),
    olt_port_mode: str = Form("manual"),
    ont_brand_mode: str = Form("manual"),
    mikrotik_user: str = Form(None),
    vlan_id: int | None = Form(None),
    db: AsyncSession = Depends(get_db)
):
    submission_key = (submission_key or "").strip()
    if len(submission_key) > 64 or not submission_key:
        raise HTTPException(status_code=422, detail="Token pengiriman form tidak valid. Muat ulang halaman lalu coba lagi.")
    # Validate all operational PSB data on the server as well as in the browser.
    name, address, phone = ((value or "").strip() for value in (name, address, phone))
    ont_sn, ont_brand, olt_port = ((value or "").strip() for value in (ont_sn, ont_brand, olt_port))
    if not name or len(name) > 160:
        raise HTTPException(status_code=422, detail="Nama pelanggan wajib diisi (maksimal 160 karakter).")
    if not address or len(address) > 1000:
        raise HTTPException(status_code=422, detail="Alamat pelanggan wajib diisi (maksimal 1000 karakter).")
    if not phone or len(phone) > 32:
        raise HTTPException(status_code=422, detail="Nomor HP wajib diisi (maksimal 32 karakter).")
    if not package_id:
        raise HTTPException(status_code=422, detail="Paket layanan wajib dipilih.")
    if not odp_id or not olt_device_id or not mikrotik_device_id:
        raise HTTPException(status_code=422, detail="ODP, OLT, dan MikroTik/NAS wajib dipilih.")
    if not ont_sn or not ont_brand or not olt_port or onu_id is None:
        raise HTTPException(status_code=422, detail="ONT SN, ONU ID, OLT port, dan merek ONT wajib diisi.")
    if not 1 <= onu_id <= 128:
        raise HTTPException(status_code=422, detail="ONU ID harus berada pada rentang 1 sampai 128.")
    if not 1 <= pppoe_vlan <= 4094 or not 1 <= iptv_vlan <= 4094:
        raise HTTPException(status_code=422, detail="VLAN PPPoE dan IPTV harus berada pada rentang 1 sampai 4094.")
    existing_job = await db.scalar(select(ProvisioningJob).where(ProvisioningJob.submission_key == submission_key))
    if existing_job:
        return RedirectResponse(url=f"/provisioning/{existing_job.id}/transit", status_code=status.HTTP_303_SEE_OTHER)
    try:
        nik = validate_nik(nik)
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc))
    if await db.scalar(select(Customer.id).where(Customer.nik == nik)):
        raise HTTPException(status_code=409, detail="NIK sudah terdaftar")
    package = await db.get(ServicePackage, package_id) if package_id else None
    if package_id and (not package or not package.is_active or package.service_type != "bulanan_ppp" or package.service_mode != "private_pppoe"):
        raise HTTPException(status_code=400, detail="PSB hanya menerima paket bulanan PPPoE")
    if package:
        harga_paket, service_profile = package.price, package.mikrotik_profile
        provisioning_mode = package.service_mode
        olt_vlan_profile, service_vlan, iptv_vlan = package.olt_vlan_profile, package.service_vlan, package.iptv_vlan
        pppoe_vlan, hotspot_vlan = package.pppoe_vlan, package.hotspot_vlan
    if play_type != "1play":
        raise HTTPException(status_code=422, detail="Form PSB ini hanya menerima layanan 1Play PPPoE")
    service_modes = ["pppoe"]
    provisioning_mode = "private_pppoe"
    # PPPoE identity is generated only from the immutable customer code below;
    # manual form values are intentionally ignored to prevent mismatched data.
    pppoe_username = None
    pppoe_password = None
    service_modes_json = json.dumps(service_modes, separators=(",", ":"))
    selected_odp = await db.get(ODP, odp_id) if odp_id else None
    if selected_odp is None or not selected_odp.is_active:
        raise HTTPException(status_code=400, detail="Pilih ODP aktif sebelum provisioning")
    selected_olt = await db.get(OLTDevice, olt_device_id) if olt_device_id else None
    if selected_olt is None or not selected_olt.is_active:
        raise HTTPException(status_code=400, detail="Pilih OLT aktif sebelum provisioning")
    # Report reused serials before live Auto-SN verification. A serial that is
    # already provisioned is expected to be absent from the unregistered list;
    # checking Auto-SN first would misleadingly describe it as a stale result.
    ont_sn = (ont_sn or "").strip()
    existing_customer = (await db.execute(select(Customer.id, Customer.customer_code).where(
        func.upper(func.trim(Customer.ont_sn)) == ont_sn.upper()
    ).limit(1))).first() if ont_sn else None
    if existing_customer:
        customer_label = existing_customer.customer_code or f"ID {existing_customer.id}"
        raise HTTPException(status_code=409, detail=(
            f"ONT SN sudah terikat pada pelanggan {customer_label}. "
            "Satu ONT hanya dapat dipakai untuk satu pelanggan; pilih ONT lain melalui Auto SN."
        ))

    # A C-DATA installation must use a serial observed live by Auto SN on the
    # selected PON.  Form values and earlier discovery results become stale as
    # soon as an ONT is moved, replaced, or powered off; accepting them would
    # register an offline ONU and make the later PPPoE failure misleading.
    selected_profile = get_vendor_profile(selected_olt.vendor, selected_olt.model)
    if selected_profile and selected_profile.key in {"cdata-fd1601s-b1", "cdata-fd1602s-b1"}:
        if any(mode != "auto" for mode in (ont_sn_mode, onu_id_mode, olt_port_mode, ont_brand_mode)):
            raise HTTPException(status_code=422, detail="Untuk OLT C-DATA, pilih ONT melalui Auto SN. Input manual diblokir agar serial, PON, dan ONU ID selalu sesuai perangkat fisik.")
        if not selected_olt.credential_id:
            raise HTTPException(status_code=503, detail="Credential SSH OLT belum terikat; Auto SN tidak dapat diverifikasi.")
        credential = await db.get(DeviceCredential, selected_olt.credential_id)
        if credential is None or not credential.is_active or credential.protocol.casefold() != "ssh":
            raise HTTPException(status_code=503, detail="Credential SSH OLT tidak tersedia; Auto SN tidak dapat diverifikasi.")
        try:
            live_results = await asyncio.to_thread(
                discover_unregistered_onts,
                host=selected_olt.host,
                port=selected_olt.api_port,
                username=credential.username,
                encrypted_secret=credential.encrypted_secret,
                pinned_host_key=os.getenv(f"OLT_{selected_olt.id}_SSH_HOST_KEY_SHA256"),
                pon_port=olt_port,
            )
        except DiscoveryUnavailableError as exc:
            raise HTTPException(status_code=503, detail=f"Auto SN tidak dapat diverifikasi saat submit: {exc}") from exc
        live_match = next((item for item in live_results if item.serial_number.casefold() == ont_sn.casefold()), None)
        if live_match is None:
            raise HTTPException(status_code=409, detail="ONT SN tidak lagi terdeteksi sebagai perangkat belum terdaftar pada PON yang dipilih. ONT mungkin sudah terdaftar, berpindah PON, atau tidak sedang terdeteksi. Klik Cari SN lagi pada OLT/PON yang benar dan pilih hasil terbaru sebelum menyimpan.")
        # Allocate only the current, live discovery values.  This prevents an
        # old dropdown result from pairing a correct serial with a stale ONU ID.
        ont_sn = live_match.serial_number
        olt_port = live_match.port
        onu_id = live_match.onu_id
        if live_match.brand:
            ont_brand = live_match.brand
    mapped_mikrotik_id = selected_odp.mikrotik_device_id
    if mapped_mikrotik_id is None:
        known_mt_ids = set((await db.execute(select(Customer.mikrotik_device_id).where(
            Customer.odp_id == selected_odp.id, Customer.is_archived == False,
            Customer.mikrotik_device_id.is_not(None)
        ))).scalars().all())
        if len(known_mt_ids) == 1:
            mapped_mikrotik_id = next(iter(known_mt_ids))
    if mapped_mikrotik_id is None:
        raise HTTPException(status_code=400, detail="ODP belum dipetakan ke MikroTik/site. Lengkapi relasi ODP sebelum PSB.")
    if mikrotik_device_id and mikrotik_device_id != mapped_mikrotik_id:
        raise HTTPException(status_code=400, detail="MikroTik yang dipilih tidak sesuai dengan pemetaan ODP.")
    mikrotik_device_id = mapped_mikrotik_id
    selected_mikrotik = await db.get(MikrotikDevice, mikrotik_device_id) if mikrotik_device_id else None
    if mikrotik_device_id and (selected_mikrotik is None or not selected_mikrotik.is_active):
        raise HTTPException(status_code=400, detail="MikroTik/NAS tidak tersedia")
    if selected_mikrotik is None and selected_odp and selected_odp.mikrotik_device_id:
        selected_mikrotik = await db.get(MikrotikDevice, selected_odp.mikrotik_device_id)
    if selected_mikrotik is None or not selected_mikrotik.is_active:
        raise HTTPException(status_code=400, detail="Pilih MikroTik/NAS aktif sebelum provisioning")
    if selected_mikrotik.site_id is None:
        raise HTTPException(status_code=400, detail="MikroTik belum dipetakan ke site.")
    selected_site = await db.get(Site, selected_mikrotik.site_id)
    olt_site_id = _site_id_for_olt(selected_olt, [selected_site] if selected_site else [])
    if olt_site_id is None or olt_site_id != selected_mikrotik.site_id:
        raise HTTPException(status_code=400, detail="OLT yang dipilih tidak cocok dengan site MikroTik/ODP.")
    vendor, model, adapter_key, olt_fields = olt_vendor, olt_model, None, {}
    if selected_olt:
        vendor, model = selected_olt.vendor, selected_olt.model
        if vendor.casefold() == "c-data" and model.casefold() in {"fd1601s-b1", "fd1602s-b1"}:
            try:
                olt_port = normalize_pon_port(olt_port)
            except (InvalidPonPortError, ValueError) as exc:
                raise HTTPException(status_code=422, detail="Format OLT port C-DATA tidak valid.") from exc
        profile = get_vendor_profile(vendor, model)
        if profile is None:
            raise HTTPException(status_code=422, detail=f"Profil provisioning belum tersedia untuk {vendor} {model}")
        if profile.execution_state != "live_supported":
            raise HTTPException(status_code=422, detail=f"PSB otomatis diblokir: executor live untuk {vendor} {model} belum tersedia. Tidak ada pelanggan atau konfigurasi MikroTik yang dibuat.")
        try:
            supplied_fields = json.loads(olt_fields_json or "{}")
        except json.JSONDecodeError:
            raise HTTPException(status_code=422, detail="Field provisioning OLT tidak valid")
        if not isinstance(supplied_fields, dict):
            raise HTTPException(status_code=422, detail="Field provisioning OLT harus berupa objek")
        allowed = {field["key"] for field in profile.fields}
        olt_fields = {key: str(value).strip()[:160] for key, value in supplied_fields.items() if key in allowed and str(value).strip()}
        profile_name = {"1play": "1p", "2play": "2p", "3play": "3p"}[play_type]
        for profile_key in ("line_profile", "service_profile", "ont_line_profile", "ont_srv_profile"):
            if profile_key in allowed:
                olt_fields[profile_key] = profile_name
        missing = [field["label"] for field in profile.fields if field.get("required") == "true" and not olt_fields.get(field["key"])]
        if missing:
            raise HTTPException(status_code=422, detail="Field OLT wajib: " + ", ".join(missing))
        adapter_key = profile.key
    if vendor.casefold() == "c-data" and model.casefold() == "fd1601s-b1":
        pppoe_vlan, hotspot_vlan, iptv_vlan = 100, 150, 200
    # WODA FD1602 subscriber service is VLAN 178; enforce it server-side.
    if vendor.casefold() == "c-data" and model.casefold() == "fd1602s-b1" and selected_olt and "woda" in (selected_olt.name or "").casefold():
        pppoe_vlan = 178
        wan_vlan = 178
    service_vlan = pppoe_vlan
    new_customer = Customer(
        name=name,
        nik=nik,
        address=address,
        phone=phone,
        type=cust_type,
        play_type=play_type,
        harga_paket=harga_paket,
        service_package_id=package.id if package else None,
        service_profile_id=package.service_profile_id if package else None,
        service_mode=package.service_mode if package else provisioning_mode,
        service_profile=service_profile,
        ont_management_mode=ont_management_mode if ont_management_mode in {"none", "pppoe"} else "none",
        management_pppoe_username=management_pppoe_username,
        management_pppoe_password=management_pppoe_password,
        provisioning_mode=provisioning_mode,
        service_modes_json=service_modes_json,
        # PPPoE identity is assigned after the immutable customer code exists.
        pppoe_username=None,
        pppoe_password=None,
        onu_id=onu_id,
        wan_vlan=wan_vlan,
        service_vlan=service_vlan,
        pppoe_vlan=pppoe_vlan,
        hotspot_vlan=hotspot_vlan,
        iptv_vlan=iptv_vlan,
        olt_vlan_profile=olt_vlan_profile,
        ont_sn=ont_sn,
        ont_brand=ont_brand,
        olt_device_id=selected_olt.id if selected_olt else None,
        mikrotik_device_id=selected_mikrotik.id if selected_mikrotik else None,
        olt_vendor=vendor,
        olt_model=model,
        olt_adapter_key=adapter_key,
        olt_fields_json=json.dumps(olt_fields, sort_keys=True) if olt_fields else None,
        olt_port=olt_port,
        odp_info=odp_info,
        odp_id=selected_odp.id if selected_odp else None,
        odp_latitude=odp_latitude,
        odp_longitude=odp_longitude,
        ont_sn_mode=ont_sn_mode if ont_sn_mode in {"auto", "manual"} else "manual",
        onu_id_mode=onu_id_mode if onu_id_mode in {"auto", "manual"} else "manual",
        olt_port_mode=olt_port_mode if olt_port_mode in {"auto", "manual"} else "manual",
        ont_brand_mode=ont_brand_mode if ont_brand_mode in {"auto", "manual"} else "manual",
        hardware_discovery_status="unavailable",
        acs_wifi_status="not_configured",
        mikrotik_user=mikrotik_user,
        vlan_id=vlan_id,
        status=CustomerStatus.REQUEST
    )
    try:
        new_customer.id = await allocate_customer_id(db)
        db.add(new_customer)
        await db.flush()
        new_customer.customer_code = customer_code_for(new_customer.id)
        new_customer.pppoe_username = default_pppoe_username(new_customer.customer_code)
        new_customer.pppoe_password = encrypt_default_pppoe_password(new_customer.customer_code)
        new_customer.pppoe_secret_version = 1
        job = ProvisioningJob(
            customer_id=new_customer.id, target="onboarding", status="queued",
            vendor=vendor, adapter_key=adapter_key or "integrated-onboarding",
            olt_device_id=selected_olt.id, mikrotik_device_id=selected_mikrotik.id,
            payload_summary=json.dumps({"mode": "private_pppoe", "service_profile": service_profile or ""}, sort_keys=True),
            attempts=0, submission_key=submission_key, progress_percent=10,
            current_activity="Provisioning diterima; menunggu worker.",
            result_message="Data tersimpan; pekerjaan provisioning sudah masuk antrean.",
        )
        db.add(job)
        await db.flush()
        db.add_all([
            ProvisioningEvent(customer_id=new_customer.id, job_id=job.id, target="onboarding_activity", status="success", activity_name="Validasi data pelanggan", progress_percent=5, message="Validasi PSB dan kecocokan site berhasil."),
            ProvisioningEvent(customer_id=new_customer.id, job_id=job.id, target="onboarding_activity", status="success", activity_name="Menyimpan data pelanggan dan pekerjaan", progress_percent=10, message="Data pelanggan tersimpan dan pekerjaan provisioning persisten dibuat."),
            ProvisioningEvent(customer_id=new_customer.id, job_id=job.id, target="onboarding_activity", status="pending", activity_name="Mengonfigurasi dan memverifikasi ONT/OLT", progress_percent=50, message="Menunggu worker menjalankan tahapan OLT/ONT."),
            ProvisioningEvent(customer_id=new_customer.id, job_id=job.id, target="onboarding_activity", status="pending", activity_name="Mengatur secret PPPoE di MikroTik", progress_percent=70, message="Menunggu verifikasi OLT sebelum konfigurasi MikroTik."),
            ProvisioningEvent(customer_id=new_customer.id, job_id=job.id, target="onboarding_activity", status="pending", activity_name="Memeriksa sesi PPPoE dan upstream MikroTik", progress_percent=90, message="Menunggu secret MikroTik aktif."),
        ])
        await db.commit()
    except IntegrityError:
        await db.rollback()
        existing_job = await db.scalar(select(ProvisioningJob).where(ProvisioningJob.submission_key == submission_key))
        if existing_job:
            return RedirectResponse(url=f"/provisioning/{existing_job.id}/transit", status_code=status.HTTP_303_SEE_OTHER)
        duplicate_serial = await db.scalar(select(Customer.id).where(
            func.upper(func.trim(Customer.ont_sn)) == ont_sn.upper()
        ))
        if duplicate_serial:
            raise HTTPException(status_code=409, detail="ONT SN sudah terikat ke pelanggan lain. Pilih ONT yang belum digunakan.")
        raise
    return RedirectResponse(url=f"/provisioning/{job.id}/transit", status_code=status.HTTP_303_SEE_OTHER)

@router.get("/provisioning/{job_id}/transit", response_class=HTMLResponse)
async def provisioning_transit_page(job_id: int, request: Request, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    job = await db.get(ProvisioningJob, job_id)
    if not job or job.target != "onboarding":
        raise HTTPException(status_code=404, detail="Pekerjaan provisioning tidak ditemukan")
    customer = await db.get(Customer, job.customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Data pelanggan tidak ditemukan")
    return templates.TemplateResponse(request=request, name="provisioning_transit.html", context={
        "job_id": job.id, "customer_code": customer.customer_code or f"Pelanggan #{customer.id}",
    })


@router.get("/api/provisioning-jobs/{job_id}/status")
async def provisioning_job_status(job_id: int, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    job = await db.get(ProvisioningJob, job_id)
    if not job or job.target != "onboarding":
        raise HTTPException(status_code=404, detail="Pekerjaan provisioning tidak ditemukan")
    customer = await db.get(Customer, job.customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Data pelanggan tidak ditemukan")
    events = (await db.execute(select(ProvisioningEvent).where(
        ProvisioningEvent.job_id == job.id,
        ProvisioningEvent.activity_name.is_not(None),
    ).order_by(ProvisioningEvent.id))).scalars().all()
    now = datetime.now(timezone.utc)
    started = job.created_at or job.started_at or now
    if started.tzinfo is None:
        started = started.replace(tzinfo=timezone.utc)
    elapsed = max(0, int((now - started).total_seconds()))
    terminal = job.status in {"completed", "failed", "requires_action"}
    progress = int(job.progress_percent or 0)
    if job.status not in {"completed", "requires_action"}:
        progress = min(progress, 99)
    return {
        "job_id": job.id,
        "status": job.status,
        "progress": progress,
        "current_activity": job.current_activity or "Menunggu worker provisioning",
        "message": job.result_message or "Permintaan diterima.",
        "elapsed_seconds": elapsed,
        "terminal": terminal,
        "customer_code": customer.customer_code or f"Pelanggan #{customer.id}",
        "detail_url": f"/customers/{customer.id}",
        "credentials_url": f"/customers/{customer.id}/credentials/initial",
        "activities": [{
            "name": event.activity_name,
            "status": event.status,
            "progress": event.progress_percent,
            "message": event.message or "",
            "timestamp": event.executed_at.isoformat() if event.executed_at else None,
        } for event in events],
    }


@router.post("/provisioning/{job_id}/retry")
async def retry_failed_provisioning(job_id: int, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    job = await db.get(ProvisioningJob, job_id)
    if not job or job.target != "onboarding":
        raise HTTPException(status_code=404, detail="Pekerjaan provisioning tidak ditemukan")
    if job.status != "failed":
        raise HTTPException(status_code=409, detail="Hanya pekerjaan gagal yang dapat dicoba ulang.")
    active = await db.scalar(select(ProvisioningJob.id).where(
        ProvisioningJob.customer_id == job.customer_id,
        ProvisioningJob.target == "onboarding",
        ProvisioningJob.status.in_(["queued", "running", "waiting"]),
        ProvisioningJob.id != job.id,
    ).limit(1))
    if active:
        raise HTTPException(status_code=409, detail="Masih ada pekerjaan provisioning aktif untuk pelanggan ini.")
    customer = await db.get(Customer, job.customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Data pelanggan tidak ditemukan")
    job.status = "queued"
    job.finished_at = None
    job.last_error = None
    job.current_activity = "Menunggu worker provisioning"
    job.result_message = "Percobaan ulang aman masuk antrean; pekerjaan dan data pelanggan yang sama digunakan."
    job.progress_percent = min(99, max(10, int(job.progress_percent or 0)))
    db.add(ProvisioningEvent(
        customer_id=customer.id, job_id=job.id, target="onboarding_activity",
        status="success", activity_name="Mengantrekan percobaan ulang",
        progress_percent=job.progress_percent, vendor=job.vendor,
        olt_device_id=job.olt_device_id, mikrotik_device_id=job.mikrotik_device_id,
        message=f"Admin {user.username} mengantrekan ulang pekerjaan yang sama setelah perbaikan.",
    ))
    await db.commit()
    return RedirectResponse(url=f"/provisioning/{job.id}/transit", status_code=status.HTTP_303_SEE_OTHER)


@router.get("/customers/{customer_id}/credentials/initial", response_class=HTMLResponse)
async def reveal_initial_pppoe_credential(customer_id: int, request: Request, db: AsyncSession = Depends(get_db), user=Depends(get_current_user)):
    customer = await db.get(Customer, customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if customer.pppoe_secret_revealed_at is not None:
        raise HTTPException(status_code=410, detail="Kredensial awal sudah ditampilkan. Gunakan reset admin bila diperlukan.")
    password = decrypt_pppoe_password(customer.pppoe_password)
    customer.pppoe_secret_revealed_at = datetime.now(timezone.utc)
    db.add(AuditLog(user_id=user.id, action="reveal_initial_pppoe", entity="customer", entity_id=customer.id, detail=customer.customer_code))
    await db.commit()
    return templates.TemplateResponse(request=request, name="credential_notice.html", context={"customer": customer, "password": password, "mode": "Kredensial provisioning awal"})

@router.post("/customers/{customer_id}/credentials/reset", response_class=HTMLResponse)
async def reset_pppoe_credential(
    customer_id: int,
    request: Request,
    new_password: str = Form(""),
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user),
):
    from app.core.device_credentials import decrypt_secret
    from app.core.mikrotik import MikrotikProvisioningError, RealMikrotikAdapter

    customer = await db.get(Customer, customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    password = new_password.strip() or customer.customer_code
    if len(password) < 8 or len(password) > 128:
        raise HTTPException(status_code=422, detail="Password PPPoE harus 8 sampai 128 karakter")

    adapter = None
    old_password = decrypt_pppoe_password(customer.pppoe_password) if customer.pppoe_password else None
    was_enabled = None
    if customer.mikrotik_device_id:
        mikrotik = await db.get(MikrotikDevice, customer.mikrotik_device_id)
        credential = await db.get(DeviceCredential, mikrotik.credential_id) if mikrotik and mikrotik.credential_id else None
        if not mikrotik or not mikrotik.is_active or not credential or not credential.is_active:
            raise HTTPException(status_code=409, detail="MikroTik atau credential tidak aktif; password tidak diubah.")
        adapter = RealMikrotikAdapter(
            host=mikrotik.host,
            username=credential.username,
            password=decrypt_secret(credential.encrypted_secret),
            api_port=mikrotik.api_port or 8728,
        )
        try:
            was_enabled, _ = await asyncio.to_thread(adapter.verify_pppoe, customer.pppoe_username)
            await asyncio.to_thread(
                adapter.upsert_pppoe_secret,
                customer.pppoe_username,
                password,
                customer.service_profile or "default",
            )
            # upsert_pppoe_secret enables a secret, so restore its previous
            # disabled state instead of accidentally reactivating a suspended customer.
            if not was_enabled:
                await asyncio.to_thread(adapter.set_pppoe_secret_enabled, customer.pppoe_username, False)
            enabled_after, _ = await asyncio.to_thread(adapter.verify_pppoe, customer.pppoe_username)
            if enabled_after != was_enabled:
                raise MikrotikProvisioningError("Status secret PPPoE berubah saat reset.")
        except Exception as exc:
            raise HTTPException(status_code=502, detail="Password PPPoE gagal disinkronkan ke MikroTik; database tidak diubah.") from exc

    customer.pppoe_password = encrypt_default_pppoe_password(password)
    customer.pppoe_secret_version = (customer.pppoe_secret_version or 0) + 1
    db.add(AuditLog(user_id=user.id, action="reset_pppoe", entity="customer", entity_id=customer.id, detail=customer.customer_code))
    try:
        await db.commit()
    except Exception as exc:
        await db.rollback()
        # Restore RouterOS if the database transaction failed after the device update.
        if adapter is not None:
            try:
                if old_password:
                    await asyncio.to_thread(
                        adapter.upsert_pppoe_secret,
                        customer.pppoe_username,
                        old_password,
                        customer.service_profile or "default",
                    )
                    if not was_enabled:
                        await asyncio.to_thread(adapter.set_pppoe_secret_enabled, customer.pppoe_username, False)
                else:
                    await asyncio.to_thread(adapter.delete_pppoe_secret, customer.pppoe_username)
            except Exception:
                raise HTTPException(status_code=500, detail="Database gagal menyimpan password dan pemulihan MikroTik gagal; perlu rekonsiliasi manual.") from exc
        raise HTTPException(status_code=500, detail="Password gagal disimpan; perubahan perangkat sudah dipulihkan.") from exc
    return templates.TemplateResponse(
        request=request,
        name="credential_notice.html",
        context={"customer": customer, "password": password, "mode": "Kredensial PPPoE setelah reset"},
    )


@router.get("/customers/{customer_id}", response_class=HTMLResponse)
async def customer_detail(customer_id: int, request: Request, db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Customer).where(Customer.id == customer_id))
    customer = result.scalar_one_or_none()
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    acs_event = await _latest_acs_setup_event(db, customer.id)
    acs_config_status = {"running": "processing", "processing": "processing", "success": "success", "failed": "failed"}.get(acs_event.status if acs_event else "", "not_configured")
    acs_config_labels = {"not_configured": "Belum dikonfigurasi", "processing": "Sedang diproses", "success": "Berhasil", "failed": "Gagal"}
    await refresh_customer_online_status(customer, db)
    device_config = None
    device_config_error = None
    # C-DATA FD1601S-B1 uses the live CLI executor; it does not expose the
    # generic preview adapter used by ZTE. Do not show a preview warning for
    # a model that is provisioned through its dedicated executor.
    if not (customer.olt_vendor == "C-DATA" and customer.olt_model == "FD1601S-B1"):
        try:
            adapter = get_olt_adapter(customer.olt_vendor, customer.olt_model)
            device_config = adapter.generate_config(customer)
        except (ValueError, UnsupportedOLTError) as exc:
            device_config_error = str(exc)
    return templates.TemplateResponse(request=request, name="customer_detail.html", context={"customer": customer, "zte_config": device_config, "zte_config_error": device_config_error, "device_config": device_config, "device_config_error": device_config_error, "acs_config_status": acs_config_status, "acs_config_label": acs_config_labels[acs_config_status], "acs_config_message": acs_event.message if acs_event else "Konfigurasi TR-069 belum dijalankan."})

@router.post("/customers/{customer_id}/provision")
async def provision_customer_route(customer_id: int, db: AsyncSession = Depends(get_db)):
    customer = (await db.execute(select(Customer).where(Customer.id == customer_id))).scalar_one_or_none()
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    await run_onboarding(customer, db)
    return RedirectResponse(url=f"/customers/{customer_id}", status_code=303)


@router.post("/customers/{customer_id}/provision-olt")
async def provision_olt_route(
    customer_id: int,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
):
    """Explicitly register one ONU on a supported C-DATA OLT.

    Technician status changes never call this endpoint. Hardware execution is
    an explicit admin action, guarded by pinned SSH identity and a single
    active job per customer/target.
    """
    from app.core.cdata_executor import CDataExecutionError, provision_cdata_onu

    customer = (await db.execute(select(Customer).where(Customer.id == customer_id))).scalar_one_or_none()
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if customer.olt_adapter_key != "cdata-fd1601s-b1" or customer.olt_vendor != "C-DATA" or customer.olt_model != "FD1601S-B1":
        raise HTTPException(status_code=422, detail="Executor live hanya tersedia untuk C-DATA FD1601S-B1")
    if not customer.olt_device_id or not customer.ont_sn or not customer.olt_port or not customer.onu_id:
        raise HTTPException(status_code=422, detail="Data OLT belum lengkap: SN ONT, port PON, ONU ID, dan OLT wajib tersedia")

    olt = await db.get(OLTDevice, customer.olt_device_id)
    if not olt or not olt.is_active or olt.management_protocol != "ssh" or not olt.credential_id:
        raise HTTPException(status_code=422, detail="OLT SSH aktif dan credential wajib tersedia")
    credential = await db.get(DeviceCredential, olt.credential_id)
    if not credential or not credential.is_active:
        raise HTTPException(status_code=422, detail="Credential OLT tidak aktif")
    pinned_host_key = os.getenv(f"OLT_{olt.id}_SSH_HOST_KEY_SHA256")
    if not pinned_host_key:
        raise HTTPException(status_code=422, detail="Fingerprint host key OLT belum dipin")

    active_job = await db.scalar(select(ProvisioningJob).where(
        ProvisioningJob.customer_id == customer.id,
        ProvisioningJob.target == "olt",
        ProvisioningJob.status.in_(["queued", "running"]),
    ))
    if active_job:
        raise HTTPException(status_code=409, detail="Provisioning OLT sedang berjalan atau sudah masuk antrean")

    payload_summary = json.dumps({
        "vendor": olt.vendor, "model": olt.model, "adapter": customer.olt_adapter_key,
        "olt_device_id": olt.id, "pon_port": customer.olt_port, "onu_id": customer.onu_id,
        "serial_number": customer.ont_sn, "service_vlan": customer.service_vlan,
        "wan_vlan": customer.wan_vlan,
    }, sort_keys=True)
    job = ProvisioningJob(
        customer_id=customer.id, target="olt", status="running", vendor=olt.vendor,
        adapter_key=customer.olt_adapter_key, olt_device_id=olt.id,
        payload_summary=payload_summary, attempts=1,
    )
    db.add(job)
    customer.olt_provisioning_status = "running"
    await db.commit()

    try:
        result = await asyncio.to_thread(
            provision_cdata_onu,
            host=olt.host,
            port=olt.api_port or 22,
            username=credential.username,
            encrypted_secret=credential.encrypted_secret,
            pinned_host_key=pinned_host_key,
            pon_port=customer.olt_port,
            onu_id=customer.onu_id,
            serial_number=customer.ont_sn,
            profile_name=customer.service_profile,
        )
    except CDataExecutionError as exc:
        message = f"Provisioning OLT gagal: {str(exc)[:500]}"
        job.status = "failed"
        job.last_error = message
        customer.olt_provisioning_status = "failed"
        customer.provisioning_message = message
        db.add(ProvisioningEvent(customer_id=customer.id, target="olt", status="failed",
            vendor=olt.vendor, olt_device_id=olt.id, adapter_key=customer.olt_adapter_key,
            payload_summary=payload_summary, message=message))
        await db.commit()
        raise HTTPException(status_code=502, detail=message)
    except Exception:
        message = "Provisioning OLT gagal karena kesalahan internal. Detail disimpan di audit."
        job.status = "failed"
        job.last_error = message
        customer.olt_provisioning_status = "failed"
        customer.provisioning_message = message
        db.add(ProvisioningEvent(customer_id=customer.id, target="olt", status="failed",
            vendor=olt.vendor, olt_device_id=olt.id, adapter_key=customer.olt_adapter_key,
            payload_summary=payload_summary, message=message))
        await db.commit()
        raise HTTPException(status_code=502, detail=message)

    job.status = "completed"
    job.executed_at = datetime.now(timezone.utc)
    job.last_error = None
    customer.olt_provisioning_status = "provisioned"
    customer.provisioning_message = result.message
    if customer.mikrotik_provisioning_status == "provisioned":
        customer.provisioning_status = "provisioned"
    else:
        customer.provisioning_status = "partially_provisioned"
    db.add(ProvisioningEvent(customer_id=customer.id, target="olt", status="completed",
        vendor=olt.vendor, olt_device_id=olt.id, adapter_key=customer.olt_adapter_key,
        payload_summary=payload_summary, message=result.message))
    await db.commit()
    return RedirectResponse(url=f"/customers/{customer_id}", status_code=303)


@router.post("/customers/{customer_id}/resume-mikrotik")
async def provision_mikrotik_route(
    customer_id: int,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
):
    """Explicitly create/update one PPPoE secret on the assigned MikroTik."""
    from app.core.mikrotik import MikrotikProvisioningError, RealMikrotikAdapter
    from app.core.device_credentials import decrypt_secret
    from app.core.customer_identity import decrypt_pppoe_password

    customer = (await db.execute(select(Customer).where(Customer.id == customer_id))).scalar_one_or_none()
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if customer.service_mode == "hotspot" or customer.type == "hotspot_voucher":
        raise HTTPException(status_code=422, detail="Aksi ini khusus pemulihan PPPoE pelanggan rumahan")
    if customer.olt_provisioning_status != "provisioned":
        raise HTTPException(status_code=409, detail="Tahap OLT belum terverifikasi. Provisioning MikroTik ditahan agar status perangkat tidak makin berbeda.")
    if not customer.mikrotik_device_id or not customer.pppoe_username or not customer.pppoe_password:
        raise HTTPException(status_code=422, detail="Data MikroTik belum lengkap: device, username, dan password PPPoE wajib tersedia")

    mikrotik = await db.get(MikrotikDevice, customer.mikrotik_device_id)
    if not mikrotik or not mikrotik.is_active or not mikrotik.credential_id:
        raise HTTPException(status_code=422, detail="Device MikroTik aktif dan credential wajib tersedia")
    credential = await db.get(DeviceCredential, mikrotik.credential_id)
    if not credential or not credential.is_active:
        raise HTTPException(status_code=422, detail="Credential MikroTik tidak aktif")

    active_job = await db.scalar(select(ProvisioningJob).where(
        ProvisioningJob.customer_id == customer.id,
        ProvisioningJob.target == "mikrotik",
        ProvisioningJob.status.in_(["queued", "running"]),
    ))
    if active_job:
        raise HTTPException(status_code=409, detail="Provisioning MikroTik sedang berjalan atau sudah masuk antrean")

    payload_summary = json.dumps({
        "vendor": "MikroTik", "device_id": mikrotik.id, "username": customer.pppoe_username,
        "profile": customer.service_profile or "default", "service": "pppoe",
    }, sort_keys=True)
    job = ProvisioningJob(
        customer_id=customer.id, target="mikrotik", status="running", vendor="MikroTik",
        adapter_key="routeros-pppoe-secret", mikrotik_device_id=mikrotik.id,
        payload_summary=payload_summary, attempts=1,
    )
    db.add(job)
    customer.mikrotik_provisioning_status = "running"
    await db.commit()

    try:
        device_password = decrypt_secret(credential.encrypted_secret)
        customer_password = decrypt_pppoe_password(customer.pppoe_password)
        adapter = RealMikrotikAdapter(
            host=mikrotik.host,
            username=credential.username,
            password=device_password,
            api_port=mikrotik.api_port or 8728,
        )
        effective_profile, used_default_profile = await asyncio.to_thread(
            adapter.resolve_profile,
            customer.service_profile,
        )
        await asyncio.to_thread(
            adapter.upsert_pppoe_secret,
            customer.pppoe_username,
            customer_password,
            effective_profile,
        )
        secret_enabled, pppoe_active, internet_reachable = await asyncio.to_thread(
            adapter.verify_pppoe_internet, customer.pppoe_username
        )
        if not secret_enabled:
            raise MikrotikProvisioningError("Secret PPPoE belum terverifikasi aktif setelah dibuat/diperbarui.")
    except MikrotikProvisioningError as exc:
        message = f"Provisioning MikroTik gagal: {str(exc)[:500]}"
        job.status = "failed"
        job.last_error = message
        customer.mikrotik_provisioning_status = "failed"
        customer.provisioning_status = "failed"
        customer.status = "failed"
        customer.provisioning_message = message
        db.add(ProvisioningEvent(customer_id=customer.id, target="mikrotik", status="failed",
            vendor="MikroTik", mikrotik_device_id=mikrotik.id, adapter_key="routeros-pppoe-secret",
            payload_summary=payload_summary, message=message))
        await db.commit()
        raise HTTPException(status_code=502, detail=message)
    except Exception:
        message = "Provisioning MikroTik gagal karena kesalahan internal. Detail disimpan di audit."
        job.status = "failed"
        job.last_error = message
        customer.mikrotik_provisioning_status = "failed"
        customer.provisioning_status = "failed"
        customer.status = "failed"
        customer.provisioning_message = message
        db.add(ProvisioningEvent(customer_id=customer.id, target="mikrotik", status="failed",
            vendor="MikroTik", mikrotik_device_id=mikrotik.id, adapter_key="routeros-pppoe-secret",
            payload_summary=payload_summary, message=message))
        await db.commit()
        raise HTTPException(status_code=502, detail=message)

    job.status = "completed"
    job.executed_at = datetime.now(timezone.utc)
    job.last_error = None
    if not pppoe_active:
        mk_status = "waiting_session"
        message = f"Secret PPPoE aktif pada {mikrotik.name}, tetapi sesi untuk username ini belum terdeteksi. Akses internet pelanggan belum dapat disimpulkan dari pemeriksaan ini."
    elif not internet_reachable:
        mk_status = "waiting_internet"
        message = f"Sesi PPPoE aktif pada {mikrotik.name}, tetapi trafik dua arah pelanggan atau upstream Internet belum terverifikasi. BestWeb akan melanjutkan pemeriksaan otomatis."
    else:
        mk_status = "provisioned"
        message = f"Sesi PPPoE pelanggan dan konektivitas Internet terverifikasi pada {mikrotik.name}."
    if used_default_profile:
        message += f" Profile {customer.service_profile} tidak tersedia; MikroTik memakai profile default."
    customer.mikrotik_provisioning_status = mk_status
    customer.provisioning_message = message
    if customer.olt_provisioning_status == "provisioned" and mk_status == "provisioned":
        customer.provisioning_status = "provisioned"
        customer.status = "active"
    else:
        customer.provisioning_status = mk_status
        if mk_status == "waiting_internet" and customer.status == "active":
            customer.status = "active"
        else:
            customer.status = mk_status
    db.add(ProvisioningEvent(customer_id=customer.id, target="mikrotik", status=mk_status,
        vendor="MikroTik", mikrotik_device_id=mikrotik.id, adapter_key="routeros-pppoe-secret",
        payload_summary=payload_summary, message=message))
    await db.commit()
    return RedirectResponse(url=f"/customers/{customer_id}", status_code=303)


@router.post("/customers/{customer_id}/provision-olt-pppoe")
async def provision_olt_pppoe_route(customer_id: int, db: AsyncSession = Depends(get_db), current_user=Depends(get_current_user)):
    """Apply the verified C-DATA WAN PPPoE sequence from Billing."""
    from app.core.cdata_executor import CDataExecutionError, provision_cdata_pppoe
    from app.core.customer_identity import decrypt_pppoe_password
    customer = (await db.execute(select(Customer).where(Customer.id == customer_id))).scalar_one_or_none()
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if customer.olt_vendor != "C-DATA" or customer.olt_model != "FD1601S-B1":
        raise HTTPException(status_code=422, detail="Executor WAN PPPoE hanya tersedia untuk C-DATA FD1601S-B1")
    if not all((customer.olt_device_id, customer.ont_sn, customer.olt_port, customer.onu_id, customer.pppoe_username, customer.pppoe_password)):
        raise HTTPException(status_code=422, detail="Data ONU/WAN PPPoE belum lengkap")
    olt = await db.get(OLTDevice, customer.olt_device_id)
    if not olt or not olt.is_active or olt.management_protocol != "ssh" or not olt.credential_id:
        raise HTTPException(status_code=422, detail="OLT SSH aktif dan credential wajib tersedia")
    credential = await db.get(DeviceCredential, olt.credential_id)
    pinned = os.getenv(f"OLT_{olt.id}_SSH_HOST_KEY_SHA256")
    if not credential or not credential.is_active or not pinned:
        raise HTTPException(status_code=422, detail="Credential atau host-key OLT belum siap")
    active = await db.scalar(select(ProvisioningJob).where(ProvisioningJob.customer_id == customer.id, ProvisioningJob.target == "olt-wan", ProvisioningJob.status.in_(["queued", "running"])))
    if active:
        raise HTTPException(status_code=409, detail="Provisioning WAN OLT sedang berjalan")
    payload = json.dumps({"vendor": olt.vendor, "model": olt.model, "pon_port": customer.olt_port, "onu_id": customer.onu_id, "vlan": customer.service_vlan or 100, "line_profile": "pppoe-100", "service_profile": "2p"}, sort_keys=True)
    job = ProvisioningJob(customer_id=customer.id, target="olt-wan", status="running", vendor=olt.vendor, adapter_key="cdata-wan-pppoe", olt_device_id=olt.id, payload_summary=payload, attempts=1)
    db.add(job); await db.commit()
    try:
        result = await asyncio.to_thread(provision_cdata_pppoe, host=olt.host, port=olt.api_port or 22, username=credential.username, encrypted_secret=credential.encrypted_secret, pinned_host_key=pinned, pon_port=customer.olt_port, onu_id=customer.onu_id, serial_number=customer.ont_sn, pppoe_username=customer.pppoe_username, pppoe_password=decrypt_pppoe_password(customer.pppoe_password), vlan=customer.service_vlan or 100)
    except CDataExecutionError as exc:
        msg = f"WAN PPPoE OLT gagal: {str(exc)[:400]}"; job.status="failed"; job.last_error=msg; customer.olt_provisioning_status="failed"; customer.provisioning_message=msg
        db.add(ProvisioningEvent(customer_id=customer.id, target="olt-wan", status="failed", vendor=olt.vendor, olt_device_id=olt.id, adapter_key="cdata-wan-pppoe", payload_summary=payload, message=msg)); await db.commit(); raise HTTPException(status_code=502, detail=msg)
    job.status="completed"; job.executed_at=datetime.now(timezone.utc); customer.olt_provisioning_status="provisioned"; customer.provisioning_message=result.message
    db.add(ProvisioningEvent(customer_id=customer.id, target="olt-wan", status="completed", vendor=olt.vendor, olt_device_id=olt.id, adapter_key="cdata-wan-pppoe", payload_summary=payload, message=result.message)); await db.commit()
    return RedirectResponse(url=f"/customers/{customer_id}", status_code=303)


@router.post("/customers/{customer_id}/reboot")
async def reboot_customer_ont(
    customer_id: int,
    db: AsyncSession = Depends(get_db),
    current_user=Depends(get_current_user),
):
    """Reboot only a fully identified C-DATA FD1601S-B1 ONU."""
    from app.core.cdata_executor import CDataExecutionError, reboot_cdata_onu

    customer = await db.get(Customer, customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if (customer.olt_vendor != "C-DATA" or customer.olt_model != "FD1601S-B1"
            or not all((customer.olt_device_id, customer.olt_port, customer.onu_id))):
        raise HTTPException(status_code=422, detail="Reboot tersedia untuk C-DATA FD1601S-B1 dengan data ONU lengkap.")

    olt = await db.get(OLTDevice, customer.olt_device_id)
    if not olt or not olt.is_active or olt.management_protocol != "ssh" or not olt.credential_id:
        raise HTTPException(status_code=422, detail="OLT SSH aktif dan credential wajib tersedia.")
    credential = await db.get(DeviceCredential, olt.credential_id)
    pinned = os.getenv(f"OLT_{olt.id}_SSH_HOST_KEY_SHA256")
    if not credential or not credential.is_active or not pinned:
        raise HTTPException(status_code=422, detail="Credential atau fingerprint host-key OLT belum siap.")

    active_job = await db.scalar(select(ProvisioningJob).where(
        ProvisioningJob.customer_id == customer.id,
        ProvisioningJob.target == "olt-reboot",
        ProvisioningJob.status.in_(("queued", "running")),
    ))
    if active_job:
        raise HTTPException(status_code=409, detail="Perintah reboot ONT sedang berjalan.")

    payload = json.dumps({
        "olt_device_id": olt.id, "pon_port": customer.olt_port,
        "onu_id": customer.onu_id, "operation": "reboot",
    }, sort_keys=True)
    job = ProvisioningJob(
        customer_id=customer.id, target="olt-reboot", status="running",
        vendor=olt.vendor, adapter_key="cdata-fd1601s-b1-reboot",
        olt_device_id=olt.id, payload_summary=payload, attempts=1,
    )
    db.add(job)
    await db.commit()

    try:
        result = await asyncio.to_thread(
            reboot_cdata_onu,
            host=olt.host, port=olt.api_port or 22, username=credential.username,
            encrypted_secret=credential.encrypted_secret, pinned_host_key=pinned,
            pon_port=customer.olt_port, onu_id=customer.onu_id,
        )
    except Exception as exc:
        message = f"Reboot ONT gagal: {str(exc)[:300]}"
        job.status = "failed"
        job.last_error = message
        db.add(ProvisioningEvent(
            customer_id=customer.id, target="olt-reboot", status="failed",
            vendor=olt.vendor, olt_device_id=olt.id,
            adapter_key="cdata-fd1601s-b1-reboot",
            payload_summary=payload, message=message,
        ))
        await db.commit()
        raise HTTPException(status_code=502, detail=message) from exc

    job.status = "completed"
    job.executed_at = datetime.now(timezone.utc)
    job.last_error = None
    db.add(ProvisioningEvent(
        customer_id=customer.id, target="olt-reboot", status="completed",
        vendor=olt.vendor, olt_device_id=olt.id,
        adapter_key="cdata-fd1601s-b1-reboot",
        payload_summary=payload, message=result.message,
    ))
    await db.commit()
    return {"status": "accepted", "message": result.message}


@router.delete("/customers/{customer_id}")
async def delete_customer(
    customer_id: int,
    db: AsyncSession = Depends(get_db),
    user=Depends(require_roles("admin_cs")),
):
    """Delete only after supported device cleanup succeeds; never hide a failure."""
    from app.core.cdata_executor import CDataExecutionError, deprovision_cdata_onu
    from app.core.mikrotik import MikrotikProvisioningError, RealMikrotikAdapter
    from app.core.device_credentials import decrypt_secret

    customer = await db.get(Customer, customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")

    # Validate all device targets before changing either device.
    olt = None
    olt_credential = None
    olt_pinned = None
    if customer.olt_device_id and customer.onu_id and customer.olt_port:
        if (customer.olt_vendor or "").strip().upper() != "C-DATA" or (customer.olt_model or "").strip().upper() not in {"FD1601S-B1", "FD1602S-B1"}:
            raise HTTPException(status_code=409, detail="Deprovision OLT belum tersedia untuk model ini; data pelanggan dipertahankan.")
        olt = await db.get(OLTDevice, customer.olt_device_id)
        olt_credential = await db.get(DeviceCredential, olt.credential_id) if olt and olt.credential_id else None
        olt_pinned = os.getenv(f"OLT_{olt.id}_SSH_HOST_KEY_SHA256") if olt else None
        if not olt or not olt.is_active or olt.management_protocol != "ssh" or not olt_credential or not olt_credential.is_active or not olt_pinned:
            raise HTTPException(status_code=409, detail="OLT, credential SSH, atau host-key belum siap; data pelanggan dipertahankan.")

    # Validate MikroTik target now, but defer deletion until the OLT cleanup succeeds.
    mikrotik = None
    credential = None
    if customer.mikrotik_device_id and customer.pppoe_username:
        mikrotik = await db.get(MikrotikDevice, customer.mikrotik_device_id)
        credential = await db.get(DeviceCredential, mikrotik.credential_id) if mikrotik and mikrotik.credential_id else None
        if not mikrotik or not mikrotik.is_active or not credential or not credential.is_active:
            raise HTTPException(status_code=409, detail="MikroTik atau credential tidak aktif; data pelanggan dipertahankan.")

    if olt is not None and olt_credential is not None:
        try:
            await asyncio.to_thread(
                deprovision_cdata_onu,
                host=olt.host,
                port=olt.api_port or 22,
                username=olt_credential.username,
                encrypted_secret=olt_credential.encrypted_secret,
                pinned_host_key=olt_pinned,
                pon_port=customer.olt_port,
                onu_id=customer.onu_id,
                serial_number=customer.ont_sn,
            )
        except Exception as exc:
            reason = str(exc).strip()
            raise HTTPException(status_code=502, detail=f"Gagal deprovision ONU di OLT: {reason[:300] or type(exc).__name__}; data pelanggan dipertahankan.") from exc

    if mikrotik is not None and credential is not None:
        try:
            adapter = RealMikrotikAdapter(
                host=mikrotik.host,
                username=credential.username,
                password=decrypt_secret(credential.encrypted_secret),
                api_port=mikrotik.api_port or 8728,
            )
            await asyncio.to_thread(adapter.delete_pppoe_secret, customer.pppoe_username)
        except Exception as exc:
            raise HTTPException(status_code=502, detail="ONU sudah dihapus dari OLT, tetapi secret PPPoE gagal dihapus dari MikroTik. Data pelanggan dipertahankan agar bisa direkonsiliasi.") from exc

    await db.delete(customer)
    await db.commit()
    return {"status": "deleted", "message": "Pelanggan dan konfigurasi perangkat berhasil dihapus"}

