defmodule Microwaveprop.Weather.MrmsClientTest do
  use ExUnit.Case, async: true

  alias Microwaveprop.Weather.MrmsClient

  describe "parse_listing/1" do
    test "extracts all unique filenames from a listing fragment" do
      html = """
      <html><body>
      <a href="MRMS_PrecipRate_00.00_20260412-192400.grib2.gz">...</a>
      <a href="MRMS_PrecipRate_00.00_20260412-192600.grib2.gz">...</a>
      <a href="MRMS_PrecipRate_00.00_20260412-192800.grib2.gz">...</a>
      </body></html>
      """

      entries =
        html
        |> MrmsClient.parse_listing()
        |> Enum.sort_by(& &1.valid_time, DateTime)

      assert [
               %{valid_time: ~U[2026-04-12 19:24:00Z]},
               %{valid_time: ~U[2026-04-12 19:26:00Z]},
               %{valid_time: ~U[2026-04-12 19:28:00Z]}
             ] = entries
    end

    test "drops filenames with malformed timestamps" do
      html = """
      <a href="MRMS_PrecipRate_00.00_bogusstamp.grib2.gz">...</a>
      <a href="MRMS_PrecipRate_00.00_20260412-193000.grib2.gz">...</a>
      """

      assert [%{valid_time: ~U[2026-04-12 19:30:00Z]}] = MrmsClient.parse_listing(html)
    end

    test "deduplicates identical filenames (directory indexes often list twice)" do
      html = """
      <a href="MRMS_PrecipRate_00.00_20260412-193000.grib2.gz">file</a>
      <a href="MRMS_PrecipRate_00.00_20260412-193000.grib2.gz">file</a>
      """

      assert [%{}] = MrmsClient.parse_listing(html)
    end
  end

  describe "flatten_rain_grid/1" do
    test "keeps positive rain rates keyed by lat/lon" do
      cells = %{
        {32.0, -97.0} => %{"PrecipRate:0 m above mean sea level" => 5.4},
        {32.125, -97.0} => %{"PrecipRate:0 m above mean sea level" => 0.0}
      }

      assert MrmsClient.flatten_rain_grid(cells) ==
               %{{32.0, -97.0} => 5.4, {32.125, -97.0} => 0.0}
    end

    test "drops missing-value sentinels (-3 or less)" do
      cells = %{
        {32.0, -97.0} => %{"PrecipRate:0 m above mean sea level" => -3.0},
        {32.125, -97.0} => %{"PrecipRate:0 m above mean sea level" => 12.5}
      }

      assert MrmsClient.flatten_rain_grid(cells) == %{{32.125, -97.0} => 12.5}
    end

    test "drops entries with no PrecipRate field at all" do
      cells = %{{32.0, -97.0} => %{"OTHER:sfc" => 1.0}}
      assert MrmsClient.flatten_rain_grid(cells) == %{}
    end
  end
end
