""".. title:: DCP Variables Metadata Service

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

Documentation for /json/dcp_vars.json
-------------------------------------

The IEM attempts a robust processing of HADS/DCP data in SHEF format.  This
SHEF format carries a huge number of potential variable names.  This service
emits the variable names that are currently available
(within the present month) for the provided station identifier.

Changelog
---------

- 2024-08-01: Initial documentation update

Example Requests
----------------

Turn the unique SHEF variables reported by AESI4

https://mesonet.agron.iastate.edu/json/dcp_vars.py?station=AESI4

"""

import json
from typing import Annotated

from pydantic import Field
from pyiem.database import get_sqlalchemy_conn, sql_helper
from pyiem.util import utc
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
    station: Annotated[
        str,
        Field(
            description="Station identifier to look for variables for.",
            max_length=8,
            pattern=r"^[A-Z0-9]+$",
        ),
    ]


@iemapp(
    memcachekey=lambda e: f"/json/dcp_vars|{e['station']}",
    content_type="application/json",
    help=__doc__,
    schema=Schema,
    memcacheexpire=3600,
)
def application(environ: dict, start_response: callable):
    """Answer request."""
    data = json_response_dict(
        {
            "vars": [],
        }
    )
    table = f"raw{utc():%Y_%m}"
    with get_sqlalchemy_conn("hads") as conn:
        res = conn.execute(
            sql_helper(
                "select distinct key from {table} where station = :station",
                table=table,
            ),
            {
                "station": environ["station"],
            },
        )
        for row in res:
            data["vars"].append(
                {
                    "id": row[0],
                }
            )
    payload = json.dumps(data)
    start_response("200 OK", [("Content-type", "application/json")])
    return payload
