""".. title:: IEM Networks GeoJSON

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

This service provides a GeoJSON representation of the IEM Networks.

Changelog
---------

- 2026-02-24: For IEM consistency, the `generation_time` root attribute was
  renamed `generated_at`.
- 2024-08-20: Initial documentation update

Example Usage
~~~~~~~~~~~~~

Request the GeoJSON representation of the IEM Networks:

https://mesonet.agron.iastate.edu/geojson/networks.py

"""

import json

from pyiem.database import sql_helper, with_sqlalchemy_conn
from pyiem.webutil import CGIModel, iemapp
from sqlalchemy.engine import Connection

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


@with_sqlalchemy_conn("mesosite")
def run(conn: Connection = None):
    """Actually do the hard work of getting the current SBW in geojson"""
    res = conn.execute(
        sql_helper(
            "SELECT ST_asGeoJson(extent) as geojson, id, name "
            "from networks WHERE extent is not null ORDER by id ASC"
        )
    )

    data = json_response_dict(
        {
            "type": "FeatureCollection",
            "features": [],
        }
    )
    for row in res.mappings():
        data["features"].append(
            dict(
                type="Feature",
                id=row["id"],
                properties=dict(name=row["name"]),
                geometry=json.loads(row["geojson"]),
            )
        )
    data["count"] = len(data["features"])
    return json.dumps(data)


@iemapp(
    memcacheexpire=86400,
    memcachekey="/geojson/network.geojson",
    content_type="application/vnd.geo+json",
    help=__doc__,
    schema=Schema,
)
def application(_environ, start_response):
    """Do Something"""
    res = run()
    start_response("200 OK", [("Content-type", "application/vnd.geo+json")])
    return res.encode("ascii")
