"""Mapa rozlivu v Krnově 2024. Python 3, Pillow, pyshp, Shapely a pyproj.

Spuštění: python rozliv.py --output .
Soubory lze předem stáhnout a předat jako --rozliv cesta.zip --podklad cesta.png.
Rozliv: VÚV TGM a ČHMÚ, CC BY 4.0. Podklad: © ČÚZK, CC BY 4.0.
https://creativecommons.org/licenses/by/4.0/
Úpravy Klimatologie.eu: výřez, potlačení barev podkladu, překryv a popisky.
"""

import argparse
from io import BytesIO
import json
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import urlopen
from zipfile import ZipFile

from PIL import Image, ImageDraw, ImageFont, ImageOps
from pyproj import Transformer
import shapefile
from shapely.geometry import box, mapping, shape
from shapely.ops import transform, unary_union


EXTENT = (-513700, -1071800, -506500, -1067000)  # S-JTSK / Krovak East North (EPSG:5514), metry
WIDTH, HEIGHT = 1800, 1200
FLOOD_URL = "https://heis.vuv.cz/data/webmap/datovesady/db/RozlivPovodne2024/vymezeni_rozlivu_povodne_09_24_SJTSK.zip"
BASE_URL = "https://ags.cuzk.gov.cz/arcgis1/rest/services/ZTM/ZTM10/MapServer/export?" + urlencode({
    "bbox": ",".join(map(str, EXTENT)), "bboxSR": 5514, "imageSR": 5514,
    "size": f"{WIDTH},{HEIGHT}", "format": "png24", "f": "image",
})
# Evidenční listy ČHMÚ č. 272 a 271, poloha v pořadí východní délka, severní šířka.
GAUGES = [("Opavice", 17.6822066, 50.1005009), ("Opava", 17.7083594, 50.0886547)]


def read_bytes(path, url):
    if path:
        return path.read_bytes()
    with urlopen(url, timeout=90) as response:
        return response.read()


def flood_geometry(archive):
    window = box(*EXTENT)
    with ZipFile(BytesIO(archive)) as bundle:
        name = next(s[:-4] for s in bundle.namelist() if s.endswith(".shp"))
        with shapefile.Reader(**{
            ext: BytesIO(bundle.read(name + "." + ext)) for ext in ("shp", "shx", "dbf")
        }) as features:
            polygons = []
            for entry in features.iterShapeRecords(bbox=EXTENT):
                geom = shape(entry.shape.__geo_interface__).intersection(window)
                if geom.area:
                    if entry.record["Kategorie"] != 1:
                        raise ValueError("Ve výřezu je další kategorie přesnosti. Zkontrolujte legendu.")
                    polygons.append(geom)
    if not polygons:
        raise ValueError("Ve výřezu nebyl nalezen žádný rozliv.")
    return unary_union(polygons)


def pixel(x, y):
    west, south, east, north = EXTENT
    return (WIDTH * (x - west) / (east - west), HEIGHT * (north - y) / (north - south))


def label_font(size):
    for font in ("DejaVuSans-Bold.ttf", "arialbd.ttf"):
        try:
            return ImageFont.truetype(font, size)
        except OSError:
            continue
    return ImageFont.load_default(size=size)


def draw_map(base, flooded):
    with Image.open(BytesIO(base)) as source:
        if source.size != (WIDTH, HEIGHT):
            raise ValueError("Podklad má jiné rozměry než zvolený výřez.")
        gray = ImageOps.grayscale(source)
    background = ImageOps.colorize(gray, "#404a50", "#fcfbf7").convert("RGBA")
    mask = Image.new("L", (WIDTH, HEIGHT))
    fill = ImageDraw.Draw(mask)
    outline = Image.new("RGBA", (WIDTH, HEIGHT))
    pen = ImageDraw.Draw(outline)
    parts = [flooded] if flooded.geom_type == "Polygon" else flooded.geoms
    for polygon in parts:
        for index, ring in enumerate([polygon.exterior, *polygon.interiors]):
            points = [pixel(x, y) for x, y in ring.coords]
            fill.polygon(points, fill=125 if index == 0 else 0)
            pen.line(points, fill="#196582", width=4)
    layer = Image.new("RGBA", (WIDTH, HEIGHT), "#258fbc")
    layer.putalpha(mask)
    result = Image.alpha_composite(Image.alpha_composite(background, layer), outline)
    draw = ImageDraw.Draw(result)
    project = Transformer.from_crs(4326, 5514, always_xy=True)
    font = label_font(59)
    for name, lon, lat in GAUGES:
        x, y = pixel(*project.transform(lon, lat))
        tx, ty = x + 47, y - 64
        bounds = draw.textbbox((tx, ty), name, font=font, anchor="lm")
        draw.line([(x, y), (tx, ty)], fill="#26353e", width=6)
        draw.rounded_rectangle((bounds[0]-13, bounds[1]-10, bounds[2]+13, bounds[3]+10),
                               radius=12, fill="#fffdf8", outline="#26353e", width=3)
        draw.text((tx, ty), name, font=font, fill="#1e303b", anchor="lm")
        draw.ellipse((x-19, y-19, x+19, y+19), fill="#a83718", outline="white", width=6)
    x, y = 55, HEIGHT - 44
    length = round(WIDTH * 1000 / (EXTENT[2] - EXTENT[0]))
    draw.rounded_rectangle((x-25, y-90, x+length+25, y+18), radius=10, fill="#fffdf8")
    draw.text((x+length/2, y-20), "1 km", anchor="mb", font=label_font(48), fill="#26353e")
    draw.line([(x, y-16), (x, y), (x+length, y), (x+length, y-16)], fill="#26353e", width=8)
    return result.convert("RGB").quantize(colors=200)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--rozliv", type=Path)
    parser.add_argument("--podklad", type=Path)
    parser.add_argument("--output", type=Path, default=Path("."))
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=True)
    flooded = flood_geometry(read_bytes(args.rozliv, FLOOD_URL))
    draw_map(read_bytes(args.podklad, BASE_URL), flooded).save(args.output / "rozliv.png", optimize=True)
    to_wgs84 = Transformer.from_crs(5514, 4326, always_xy=True)
    geojson = {
        "type": "Feature",
        "properties": {"udalost": "Září 2024", "kategorie": 1,
                       "zdroj": "VÚV TGM a ČHMÚ, CC BY 4.0", "uprava": "Výřez z původní vrstvy"},
        "geometry": mapping(transform(to_wgs84.transform, flooded)),
    }
    (args.output / "rozliv.geojson").write_text(json.dumps(geojson, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
    print(f"Plocha rozlivu uvnitř výřezu: {flooded.area / 1e6:.4f} km²")


if __name__ == "__main__":
    main()
