""".. title:: Winter Road Conditions GeoJSON

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

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

Get the current winter road conditions:

https://mesonet.agron.iastate.edu/geojson/winter_roads.geojson

"""

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("postgis")
def run(conn: Connection | None = None) -> str:
    """Actually do the hard work of getting the current SBW in geojson"""

    res = conn.execute(
        sql_helper("""
        SELECT ST_asGeoJson(ST_Transform(simple_geom, 4326)) as geojson,
        cond_code, c.segid from
        roads_current c JOIN roads_base b on (c.segid = b.segid)
        WHERE c.valid > now() - '1000 hours'::interval
        and cond_code is not null
    """)
    )

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


@iemapp(
    help=__doc__,
    schema=Schema,
    memcachekey="/geojson/winter_roads.geojson",
    memcacheexpire=120,
    content_type="application/vnd.geo+json",
)
def application(_environ, start_response):
    """Main Workflow"""
    res = run()
    start_response("200 OK", [("Content-type", "application/vnd.geo+json")])
    return res
