defmodule Towerops.Snmp.Profiles.Vendors.Ligoos do
  @moduledoc """
  LigoWave (LigoOS) device-specific SNMP handling.

  Mirrors LibreNMS/OS/Ligoos.php for wireless sensor discovery.

  Supported devices:
  - LigoWave LigoPTP series
  - LigoWave DLB series
  """

  @behaviour Towerops.Snmp.Profiles.Vendors.Vendor

  alias Towerops.Snmp.Client
  alias Towerops.Snmp.Profiles.Vendors.Vendor

  # Table base OID for wireless interface config
  @wl_if_table "1.3.6.1.4.1.32750.3.10.1.2.1.1"

  @impl true
  def profile_names, do: ["ligoos"]

  @impl true
  def detect_hardware(_client_opts) do
    # Hardware detection is handled by YAML profile
    nil
  end

  @impl true
  def discover_wireless_sensors(client_opts) do
    # LigoOS uses table-based discovery for multiple interfaces
    scalar_sensors = Vendor.fetch_sensors(wireless_oid_defs(), client_opts)

    # Also try to walk the wireless interface table for per-interface sensors
    table_sensors = discover_table_sensors(client_opts)

    scalar_sensors ++ table_sensors
  end

  defp discover_table_sensors(client_opts) do
    # Walk the client count column (index 16)
    case Client.walk(client_opts, "#{@wl_if_table}.16") do
      {:ok, results} when is_map(results) and map_size(results) > 0 ->
        Enum.map(results, fn {oid, value} ->
          index = oid |> String.split(".") |> List.last()

          %{
            sensor_type: "clients",
            sensor_index: "ligoos_clients_#{index}",
            sensor_oid: oid,
            sensor_descr: "Wireless Clients (if #{index})",
            sensor_unit: "",
            sensor_divisor: 1,
            last_value: value / 1
          }
        end)

      _ ->
        []
    end
  end

  @impl true
  def wireless_oid_defs do
    [
      # Frequency (first interface)
      %{
        oid: "1.3.6.1.4.1.32750.3.10.1.2.1.1.6.1",
        sensor_type: "frequency",
        sensor_descr: "Frequency",
        sensor_unit: "MHz",
        sensor_divisor: 1
      },
      # Noise Level (first interface)
      %{
        oid: "1.3.6.1.4.1.32750.3.10.1.2.1.1.15.1",
        sensor_type: "noise-floor",
        sensor_descr: "Noise Floor",
        sensor_unit: "dBm",
        sensor_divisor: 1
      },
      # Link Quality (first interface) in %
      %{
        oid: "1.3.6.1.4.1.32750.3.10.1.2.1.1.12.1",
        sensor_type: "quality",
        sensor_descr: "Link Quality",
        sensor_unit: "%",
        sensor_divisor: 1
      },
      # Associated Node Count (first interface)
      %{
        oid: "1.3.6.1.4.1.32750.3.10.1.2.1.1.16.1",
        sensor_type: "clients",
        sensor_descr: "Associated Nodes",
        sensor_unit: "",
        sensor_divisor: 1
      }
    ]
  end
end
