defmodule Towerops.Snmp.Profiles.Vendors.Omnitron do
  @moduledoc """
  SNMP profile for Omnitron devices.

  Supports Omnitron iConverter media converters and related products.

  Enterprise OID: 1.3.6.1.4.1.7342
  """

  @behaviour Towerops.Snmp.Profiles.Vendors.Vendor

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

  @impl true
  def profile_names, do: ["omnitron-iconverter"]

  @impl true
  def detect_hardware(client_opts) do
    case Client.get(client_opts, "1.3.6.1.2.1.1.1.0") do
      {:ok, descr} when is_binary(descr) ->
        parse_hardware_from_descr(descr)

      _ ->
        nil
    end
  end

  defp parse_hardware_from_descr(descr) do
    # sysDescr format: "Omnitron iConverter <model> v<version> s/n <serial>"
    # Extract model name (everything after "iConverter " and before " v")
    case Regex.run(~r/Omnitron iConverter (.+) v(\S+) s\/n (\S+)/, descr) do
      [_full, hardware, _version, _serial] ->
        "iConverter #{hardware}"

      _ ->
        # Fallback: return first line truncated to 64 chars
        descr
        |> String.split(~r/[\r\n]/)
        |> List.first()
        |> case do
          nil -> nil
          line -> String.slice(line, 0, 64)
        end
    end
  end

  @impl true
  def wireless_oid_defs do
    [
      # CPU Temperature
      %{
        oid: "1.3.6.1.4.1.7342.2.1.3.1.38.1",
        sensor_descr: "CPU Ambient Temperature",
        sensor_type: "temperature",
        sensor_unit: "°C",
        sensor_divisor: 1
      },
      # Module Internal Temperature
      %{
        oid: "1.3.6.1.4.1.7342.2.1.11.1.9.1",
        sensor_descr: "Module Internal Ambient Temperature",
        sensor_type: "temperature",
        sensor_unit: "°C",
        sensor_divisor: 1
      },
      # CPU Input Voltage
      %{
        oid: "1.3.6.1.4.1.7342.2.1.3.1.36.1",
        sensor_descr: "CPU Input Voltage",
        sensor_type: "voltage",
        sensor_unit: "V",
        sensor_divisor: 1000
      },
      # CPU Output Voltage
      %{
        oid: "1.3.6.1.4.1.7342.2.1.3.1.37.1",
        sensor_descr: "CPU Output Voltage",
        sensor_type: "voltage",
        sensor_unit: "V",
        sensor_divisor: 1000
      }
    ]
  end

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