""".. title:: Website Products for IEM Time Machine

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

Documentation for /json/products.py
-----------------------------------

This service emits a JSON response that drives the
`IEM Time Machine <https://mesonet.agron.iastate.edu/timemachine/>`_.

Changelog
---------

- 2024-07-24: Initital documentation release.

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

Nothing much to see here.

https://mesonet.agron.iastate.edu/json/products.py

"""

import json

from pyiem.database import get_sqlalchemy_conn, sql_helper
from pyiem.webutil import CGIModel, iemapp
from sqlalchemy 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


def add_webcam(conn: Connection, data):
    """Append."""
    res = conn.execute(
        sql_helper(
            "SELECT * from webcams WHERE network != 'IDOT' "
            "and sts is not null ORDER by network, name"
        )
    )
    for row in res.mappings():
        tpl = (
            "https://mesonet.agron.iastate.edu/archive/data/%Y/%m/%d/"
            f"camera/{row['id']}/{row['id']}_%Y%m%d%H%i.jpg"
        )
        data["products"].append(
            {
                "id": row["id"],
                "template": tpl,
                "name": row["name"],
                "groupname": f"{row['network']} Webcams",
                "interval": 5,
                "time_offset": 0,
                "avail_lag": 0,
                "sts": row["sts"].strftime("%Y-%m-%d"),
            }
        )


def add_archive_products(conn: Connection, data):
    """Append."""
    res = conn.execute(
        sql_helper(
            "SELECT * from archive_products WHERE sts is not null "
            "ORDER by groupname, name"
        )
    )
    for row in res.mappings():
        data["products"].append(
            {
                "id": row["id"],
                "template": row["template"],
                "name": row["name"],
                "groupname": row["groupname"],
                "interval": row["interval"],
                "time_offset": row["time_offset"],
                "avail_lag": row["avail_lag"],
                "sts": row["sts"].strftime("%Y-%m-%d"),
            }
        )


@iemapp(
    memcachekey="/json/products",
    content_type="application/json",
    help=__doc__,
    schema=Schema,
    memcacheexpire=3600,
)
def application(_environ: dict, start_response: callable):
    """Answer request."""
    data = json_response_dict({"products": []})
    with get_sqlalchemy_conn("mesosite") as conn:
        add_archive_products(conn, data)
        add_webcam(conn, data)
    payload = json.dumps(data)
    start_response("200 OK", [("Content-type", "application/json")])
    return payload
