defmodule Microwaveprop.Workers.MrmsFetchWorker do
  @moduledoc """
  Every ~2 minutes, pull the newest NOAA MRMS PrecipRate grid and cache
  the regridded version (0.125° CONUS) in `Microwaveprop.Weather.MrmsCache`.
  `Microwaveprop.Workers.AsosAdjustmentWorker` reads that cache on its
  own tick to overlay real radar rain rates onto the score grid.

  Runs on the `propagation` queue so it shares the scoring node's crontab
  and isn't competing with the heavier HRRR pipeline for slots.
  """
  use Oban.Worker, queue: :propagation, max_attempts: 2

  alias Microwaveprop.Weather.MrmsCache
  alias Microwaveprop.Weather.MrmsClient

  require Logger

  @impl Oban.Worker
  def perform(%Oban.Job{}) do
    case MrmsClient.fetch_latest(MrmsCache.valid_time()) do
      {:ok, valid_time, grid} ->
        MrmsCache.broadcast_put(valid_time, grid)

        Logger.info("MrmsFetch: cached #{map_size(grid)} cells at #{valid_time} (#{count_rainy(grid)} with rain)")

        :ok

      {:up_to_date, valid_time} ->
        Logger.debug("MrmsFetch: cache already has #{valid_time}")
        :ok

      {:error, reason} ->
        Logger.warning("MrmsFetch: skipped — #{inspect(reason)}")
        :ok
    end
  end

  defp count_rainy(grid) do
    Enum.count(grid, fn {_, v} -> v > 0 end)
  end
end
