""".. title:: IEM RIDGE Current Metadata

Return to `API Services </api/#json>`_

Documentation for /json/ridge_current.py
----------------------------------------

The IEM processes a number of NWS Level III products into a geo-referenced
PNG format.  This service provides a metadata overview of the most recent
images for a given product.

Changelog
---------

- 2026-03-03: Root attribute `generation_time_utc` was renamed `generated_at`
  so to match a common IEM nomenclature.

Example Usage
-------------

Provide the most recent N0B product metadata:

https://mesonet.agron.iastate.edu/json/ridge_current.py?product=N0B

"""

import glob
import json
from typing import Annotated

from pydantic import Field
from pyiem.util import LOG
from pyiem.webutil import CGIModel, iemapp

from iemweb.fields import CALLBACK_FIELD
from iemweb.util import json_response_dict


class Schema(CGIModel):
    """See how we are called."""

    callback: CALLBACK_FIELD = None
    product: Annotated[
        str, Field(description="Radar product to aggregate", max_length=3)
    ] = "N0B"


def run(product):
    """Actually run for this product"""

    res = json_response_dict(
        {
            "product": product,
            "meta": [],
        }
    )

    for fn in glob.glob(
        f"/mesonet/ldmdata/gis/images/4326/ridge/???/{product}_0.json"
    ):
        try:
            with open(fn, encoding="utf-8") as fh:
                j = json.load(fh)
            res["meta"].append(j["meta"])
        except Exception as exp:
            LOG.info(exp)

    return json.dumps(res)


@iemapp(
    help=__doc__,
    schema=Schema,
    memcachekey=lambda x: f"/json/ridge_current_{x['product']}.json",
    memcacheexpire=30,
)
def application(environ, start_response):
    """Answer request."""
    product = environ["product"].upper()

    res = run(product)
    start_response("200 OK", [("Content-type", "application/json")])
    return res
