defmodule Microwaveprop.Weather.GefsProfile do
  @moduledoc """
  Grid-point atmospheric profile sourced from NCEP GEFS ensemble-mean
  (`geavg`) pgrb2a 0.5° output. Mirrors the shape of
  `Microwaveprop.Weather.HrrrProfile` so the existing scorer can run
  over rows from either source for a given `valid_time`.

  GEFS publishes relative humidity rather than dewpoint, so
  `surface_dewpoint_c` on these rows is derived by
  `Microwaveprop.Weather.GefsClient.dewpoint_from_rh/2` at ingest time.
  HPBL is not in the pgrb2a product; that column intentionally doesn't
  exist here.
  """

  use Ecto.Schema

  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "gefs_profiles" do
    field :valid_time, :utc_datetime
    field :lat, :float
    field :lon, :float
    field :run_time, :utc_datetime
    field :forecast_hour, :integer
    field :profile, {:array, :map}
    field :pwat_mm, :float
    field :surface_temp_c, :float
    field :surface_dewpoint_c, :float
    field :surface_pressure_mb, :float
    field :surface_refractivity, :float
    field :min_refractivity_gradient, :float
    field :ducting_detected, :boolean, default: false
    field :duct_characteristics, {:array, :map}
    field :wind_u_mps, :float
    field :wind_v_mps, :float
    field :cloud_cover_pct, :float
    field :precip_mm, :float

    timestamps(type: :utc_datetime)
  end

  @type t :: %__MODULE__{}

  @required_fields ~w(valid_time lat lon)a
  @optional_fields ~w(run_time forecast_hour profile pwat_mm surface_temp_c surface_dewpoint_c
                      surface_pressure_mb surface_refractivity min_refractivity_gradient
                      ducting_detected duct_characteristics wind_u_mps wind_v_mps
                      cloud_cover_pct precip_mm)a

  @spec changeset(t() | Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
  def changeset(gefs_profile, attrs) do
    gefs_profile
    |> cast(attrs, @required_fields ++ @optional_fields)
    |> validate_required(@required_fields)
    |> unique_constraint([:lat, :lon, :valid_time])
  end
end
