"""ZTE C320 command generation for supported BestWeb service profiles."""


def _get(data, key, default=None):
    return data.get(key, default) if isinstance(data, dict) else getattr(data, key, default)


def generate_zte_c320_config(data) -> str:
    olt_port = _get(data, "olt_port")
    onu_id = _get(data, "onu_id")
    ont_sn = _get(data, "ont_sn")
    if not olt_port or onu_id is None or not ont_sn:
        raise ValueError("OLT port, ONU ID, dan SN ONT wajib diisi")

    mode = _get(data, "provisioning_mode", "private_pppoe")
    if mode not in {"private_pppoe", "hotspot"}:
        raise ValueError("Mode provisioning ZTE tidak valid")
    service_vlan = int(_get(data, "service_vlan", _get(data, "vlan_id", 175)))
    wan_vlan = int(_get(data, "wan_vlan", 175))
    iptv_vlan = int(_get(data, "iptv_vlan", 15))
    vlan_profile = _get(data, "olt_vlan_profile", "bnbv1009")
    pppoe_user = _get(data, "pppoe_username") or ""
    pppoe_password = _get(data, "pppoe_password") or ""
    interface = f"{olt_port}:{onu_id}"

    if mode == "private_pppoe" and (not pppoe_user or not pppoe_password):
        raise ValueError("Username dan password PPPoE wajib untuk mode private_pppoe")

    if mode == "private_pppoe":
        wan_line = (f"  wan-ip 1 mode pppoe username {pppoe_user} password "
                    f"{pppoe_password} vlan-profile {vlan_profile} host 1")
    else:
        wan_line = f"  wan-ip 1 mode dhcp vlan-profile {vlan_profile} host 1"

    return f"""conf t
interface gpon-olt_{olt_port}
onu {onu_id} type ALL sn {ont_sn}
exit
interface gpon-onu_{interface}
  tcont 1 profile default
  gemport 1 tcont 1
  service-port 1 vport 1 user-vlan {service_vlan} vlan {service_vlan}
  gemport 3 tcont 1
  service-port 3 vport 3 user-vlan {iptv_vlan} vlan {iptv_vlan}
exit
pon-onu-mng gpon-onu_{interface}
  service 1 gemport 1 vlan {service_vlan}
{wan_line}
  security-mgmt 212 state enable mode forward protocol web
  vlan port wifi_0/2 mode tag vlan {iptv_vlan}
  vlan port wifi_0/3 mode tag vlan {iptv_vlan}
  vlan port wifi_0/4 mode tag vlan {iptv_vlan}
  vlan port eth_0/1 mode tag vlan {iptv_vlan}
  vlan port eth_0/2 mode tag vlan {iptv_vlan}
  vlan port eth_0/3 mode tag vlan {iptv_vlan}
  vlan port eth_0/4 mode tag vlan {iptv_vlan}
  service iptv gemport 3 vlan {iptv_vlan}
  dhcp-ip ethuni eth_0/1 from-internet
  mvlan {iptv_vlan}
  mvlan tag eth_0/1 strip
exit
igmp mvlan {iptv_vlan} receive-port gpon-onu_{interface} vport 3
end"""
