""".. title:: Storm Based Warning County Intersection

Return to `API Services </api/#json>`_. This service drives some of the
presentation of the `VTEC Browser </vtec/>`_.

This service provides a GeoJSON for the intersection of the polygon border and
any county/parish borders.  This is meant to describe the amount of the polygon
border that was influenced by the county border.

Changelog
---------

- 2026-04-27: The VTEC eventid name was rectified to `etn` to match other
  IEM services.
- 2024-08-16: Initial documentation update

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

Show the intersection of the polygon border for Des Moines Tornado Warning 49
from 2024 with county borders.

https://mesonet.agron.iastate.edu/geojson/sbw_county_intersect.py\
?wfo=KDMX&year=2024&phenomena=TO&significance=W&eventid=49

"""

import geopandas as gpd
from pyiem.database import get_sqlalchemy_conn, sql_helper
from pyiem.webutil import CGIModel, iemapp

from iemweb.fields import (
    CALLBACK_FIELD,
    VTEC_ETN_FIELD,
    VTEC_PH_FIELD,
    VTEC_SIG_FIELD,
    VTEC_YEAR_FIELD,
    WFO3_FIELD,
)


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

    callback: CALLBACK_FIELD = None
    wfo: WFO3_FIELD = "MPX"
    year: VTEC_YEAR_FIELD = 2015
    phenomena: VTEC_PH_FIELD = "SV"
    significance: VTEC_SIG_FIELD = "W"
    etn: VTEC_ETN_FIELD = 1


def run(query: Schema) -> str:
    """Do great things"""
    with get_sqlalchemy_conn("postgis") as conn:
        borderdf = gpd.read_postgis(
            sql_helper("""
            WITH stormbased as (
                SELECT geom from sbw where vtec_year = :year and wfo = :wfo
                and eventid = :eventid and significance = :significance
                and phenomena = :phenomena and status = 'NEW' limit 1),
            countybased as (
                SELECT ST_Union(u.geom) as geom from
                warnings w JOIN ugcs u on (u.gid = w.gid)
                WHERE w.vtec_year = :year and w.wfo = :wfo and
                eventid = :eventid and significance = :significance
                and phenomena = :phenomena),
            foo as (
                 SELECT ST_SetSRID(ST_intersection(
          ST_buffer(ST_exteriorring(ST_geometryn(ST_multi(c.geom),1)),0.02),
          ST_exteriorring(ST_geometryn(ST_multi(s.geom),1))
            ), 4326) as geom from stormbased s, countybased c)

            SELECT geom, ST_Length(ST_transform(geom,9311)) as sz from foo
        """),
            conn,
            params=dict(
                year=query.year,
                wfo=query.wfo,
                phenomena=query.phenomena,
                significance=query.significance,
                eventid=query.etn,
            ),
            geom_col="geom",
        )  # type: ignore
    return borderdf.to_json()


def get_mckey(environ: dict) -> str:
    """Return the key."""
    return (
        f"/geojson/sbw_county_intersect/{environ['wfo']}/{environ['year']}/"
        f"{environ['phenomena']}/{environ['significance']}/"
        f"{environ['etn']}"
    )


@iemapp(
    schema=Schema,
    help=__doc__,
    content_type="application/vnd.geo+json",
    memcacheexpire=3600,
    memcachekey=get_mckey,
)
def application(environ, start_response):
    """Main()"""
    query: Schema = environ["_cgimodel_schema"]
    res = run(query).encode("ascii")

    start_response("200 OK", [("Content-Type", "application/vnd.geo+json")])
    return res
