defmodule Towerops.Snmp.Profiles.Vendors.AlliedTelesis do
  @moduledoc """
  Allied Telesis device-specific SNMP handling.

  Supports Allied Telesis switches and routers.

  Supported devices:
  - AlliedWare Plus switches (x-series, SBx series)
  - AlliedWare switches (AT-8000 series)
  - Allied Telesis managed switches

  Enterprise OID: 1.3.6.1.4.1.207
  """

  @behaviour Towerops.Snmp.Profiles.Vendors.Vendor

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

  # Allied Telesis sysDescr
  @sysdescr_oid "1.3.6.1.2.1.1.1.0"

  @impl true
  def profile_names, do: ["allied", "awplus", "allied-tq", "radlan"]

  @impl true
  def detect_hardware(client_opts) do
    # Model often in sysDescr
    case Client.get(client_opts, @sysdescr_oid) do
      {:ok, descr} when is_binary(descr) ->
        cond do
          match = Regex.run(~r/(AT-\S+|x\d+\S*)/i, descr) -> List.first(tl(match))
          String.contains?(descr, "AlliedWare Plus") -> "AlliedWare Plus"
          String.contains?(descr, "AlliedWare") -> "AlliedWare"
          true -> nil
        end

      _ ->
        nil
    end
  end

  @impl true
  def discover_wireless_sensors(client_opts) do
    Vendor.fetch_sensors(wireless_oid_defs(), client_opts)
  end

  @impl true
  def wireless_oid_defs do
    [
      # CPU Utilization 5-minute Average (AT-SYSINFO-MIB)
      %{
        oid: "1.3.6.1.4.1.207.8.4.4.3.3.7.0",
        sensor_type: "load",
        sensor_descr: "CPU 5min Average",
        sensor_unit: "%",
        sensor_divisor: 1
      },
      # Free Memory (AT-SYSINFO-MIB)
      %{
        oid: "1.3.6.1.4.1.207.8.4.4.3.7.1.0",
        sensor_type: "count",
        sensor_descr: "Free Memory",
        sensor_unit: "KB",
        sensor_divisor: 1
      },
      # Temperature Current (AT-ENVMONv2-MIB, index 1)
      %{
        oid: "1.3.6.1.4.1.207.8.4.4.3.12.3.1.5.1",
        sensor_type: "temperature",
        sensor_descr: "Temperature",
        sensor_unit: "°C",
        sensor_divisor: 1
      },
      # Fan Speed (AT-ENVMONv2-MIB, index 1)
      %{
        oid: "1.3.6.1.4.1.207.8.4.4.3.12.1.1.5.1",
        sensor_type: "fanspeed",
        sensor_descr: "Fan Speed",
        sensor_unit: "RPM",
        sensor_divisor: 1
      },
      # System Uptime
      %{
        oid: "1.3.6.1.2.1.1.3.0",
        sensor_type: "count",
        sensor_descr: "System Uptime",
        sensor_unit: "ticks",
        sensor_divisor: 1
      }
    ]
  end
end
