""".. title:: Legacy Network Metadata Service

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

Changelog
---------

- 2024-07-26: Initial documentation release

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

Return metadata for the SCAN network:

https://mesonet.agron.iastate.edu/json/network.py?network=SCAN

"""

import json

from pyiem.database import get_sqlalchemy_conn, sql_helper
from pyiem.webutil import CGIModel, iemapp

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


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

    callback: CALLBACK_FIELD = None
    network: NETWORK_FIELD = "IA_ASOS"


def get_mckey(environ):
    """Return the memcache key for this request."""
    return f"json_network_{environ['network']}"


@iemapp(
    memcachekey=get_mckey,
    content_type="application/json",
    help=__doc__,
    schema=Schema,
    memcacheexpire=3600,
)
def application(environ, start_response):
    """Answer request."""
    data = json_response_dict({"stations": []})
    with get_sqlalchemy_conn("mesosite") as conn:
        res = conn.execute(
            sql_helper(
                """
            select id, name, ST_x(geom) as lon, ST_y(geom) as lat
            from stations where network = :network order by id asc
        """
            ),
            {
                "network": environ["network"],
            },
        )
        for row in res.mappings():
            data["stations"].append(
                {
                    "id": row["id"],
                    "combo": f"[{row['id']}] {row['name']}",
                    "name": row["name"],
                    "lon": row["lon"],
                    "lat": row["lat"],
                }
            )
    payload = json.dumps(data)
    start_response("200 OK", [("Content-type", "application/json")])
    return payload
