# -*- coding: utf-8 -*-
"""
LoD2 CityGML tiles are available for whole Baden-Württemberg, from LGL.

https://opengeodata.lgl-bw.de/#/(sidenav:product/12)

This script downloads the required tiles for given regions
(as WKT strings, Zipcode or Zipcodes), and extracts the region.

Usage:
    python download_files_from_LGL_BW.py StuttgartCenter "POLYGON((9.175287 48.780916, 9.185501 48.777522, 9.181467 48.773704, 9.174429 48.768472, 9.168807 48.773902, 9.175287 48.780916))"
    python download_files_from_LGL_BW.py Freiburg "79098,79102"
    python download_files_from_LGL_BW.py Möhringen "70567" --download-only
    python download_files_from_LGL_BW.py CustomPath "POLYGON(...)" --simstadt-folder "/path/to/SimStadt"

Required:
* Python
* pyproj project (https://pypi.org/project/pyproj/)
* SimStadt installed on the Desktop (for RegionChooser) if extracting regions

Eric Duminil, 2025
"""
import argparse
from pathlib import Path
from math import floor
import subprocess
import re
import urllib.request
import time
import zipfile
import logging

from pyproj import CRS
from pyproj import Transformer

from shapely import wkt
from shapely.ops import transform
from shapely.geometry import Point

from get_coordinates_by_zipcode import get_coordinates_by_zipcode

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(levelname)s - %(message)s',
)
logger = logging.getLogger(__name__)

COORDINATES_REGEX = re.compile(r"(\-?\d+\.\d*) (\-?\d+\.\d*)")

CITYGML_SERVER = "https://opengeodata.lgl-bw.de/data/lod2"
RASTER = 2  # [km]
KILOMETER = 1000  # [m]
BUNDESLAND = 'bw'

# UTM32N, used in BW. https://epsg.io/32632
TO_LOCAL_CRS = Transformer.from_crs(CRS.from_epsg(4326),
                                    CRS.from_epsg(32632),
                                    always_xy=True)

UTM = 32

SCRIPT_DIR = Path(__file__).parent
WAIT_BETWEEN_DOWNLOADS = 5  # [s] Be nice to LGL Server.
GML_GLOB = "LoD2_*/LoD2_*.gml"


def find_simstadt_folder():
    """Find SimStadt installation on desktop"""
    try:
        simstadt_folder = next(x for x in Path.home().glob('Desktop/SimStadt*_0.*/') if x.is_dir())
        logger.info("RegionChooser has been found in %s", simstadt_folder)
        return simstadt_folder
    except StopIteration:
        return None


def coordinates_to_grid(longitude: float, latitude: float) -> tuple[int, int]:
    """Returns (x, y) of the tile on CITYGML_SERVER containing a given point."""
    x, y = TO_LOCAL_CRS.transform(longitude, latitude)
    x = floor(x / KILOMETER) - 1  # Odd x
    y = floor(y / KILOMETER)  # Even y
    x -= x % RASTER
    y -= y % RASTER
    return (x + 1, y)


def wkt_polygon_to_grid_coords(location_name: str, wkt_str: str) -> tuple[int, int, int, int]:
    """Returns (x, y) of lower-left and bottom-right tiles, containing a given region."""
    if 'POLYGON' not in wkt_str:
        raise ValueError(f"wkt for {location_name} should be a WKT POLYGON or MULTIPOLYGON")

    coordinates = re.findall(r'\-?\d+\.\d+', wkt_str)

    lons = [float(lon) for lon in coordinates[::2]]
    lats = [float(lat) for lat in coordinates[1::2]]

    min_lon, max_lon = min(lons), max(lons)
    min_lat, max_lat = min(lats), max(lats)

    logger.info("%s (%.3f°N %.3f°E -> %.3f°N %.3f°E)",
                location_name, max_lat, min_lon, min_lat, max_lon)

    x1, y1 = coordinates_to_grid(min_lon, min_lat)
    x2, y2 = coordinates_to_grid(max_lon, max_lat)

    return (x1, x2, y1, y2)


def download_whole_region(output_dir: Path, wkt_region: str, x1: int, x2: int, y1: int, y2: int) -> None:
    """Downloads every zip of a given region, to output_dir, and extracts CityGML files."""

    wgs84_region = wkt.loads(wkt_region)
    local_region = transform(TO_LOCAL_CRS.transform, wgs84_region)

    for x in range(x1, x2 + 1, RASTER):
        for y in range(y1, y2 + 1, RASTER):
            tile_center = Point((x + 1) * KILOMETER, (y + 1) * KILOMETER)
            if local_region.distance(tile_center) > RASTER * KILOMETER:
                continue
            citygml_zip = f"LoD2_{UTM}_{x}_{y}_{RASTER}_{BUNDESLAND}.zip"
            citygml_url = f"{CITYGML_SERVER}/{citygml_zip}"
            local_zip = output_dir / citygml_zip
            if local_zip.exists():
                logger.info("  %s already in %s/", local_zip.name, output_dir.name)
            else:
                logger.info("  Download %s to %s/", citygml_zip, output_dir.name)
                try:
                    urllib.request.urlretrieve(citygml_url, local_zip)
                    logger.info("✅ Download successful")
                except urllib.error.HTTPError as e:
                    logger.error("❌ %s", e)
                    continue
                finally:
                    time.sleep(WAIT_BETWEEN_DOWNLOADS)

                logger.info("    Extract %s to %s/", citygml_zip, output_dir.name)
                with zipfile.ZipFile(local_zip, "r") as zip_ref:
                    zip_ref.extractall(output_dir)
                logger.info("✅ Extraction successful")


def extract_region(output_dir: Path, location_name: str, wkt_str: str, simstadt_folder: Path) -> None:
    """Uses RegionChooser to extract a given region from all the CityGML files found in subfolder."""
    output_file = output_dir / (location_name + '.gml')
    if output_file.exists():
        logger.info("  %s already exists. Not extracting.", output_file)
        return

    region_chooser_libs = simstadt_folder / 'lib/*'
    gml_inputs = list(output_dir.glob(GML_GLOB))
    if len(gml_inputs) == 0:
        logger.error(
            "Error: No CityGML found. At least part of the region should be in Baden-Württemberg!")
        return

    params_path = output_dir / 'params.txt'
    wkt_path = output_dir / 'region.wkt'

    local_wkt = convert_wkt_to_local(wkt_str)

    logger.info("  Extracting %s.", output_file)
    with open(wkt_path, 'w') as f:
        f.write(local_wkt)

    with open(params_path, 'w') as f:
        f.write("--input\n")
        f.write(','.join(f"{gml.as_posix()}" for gml in gml_inputs))
        f.write("\n")
        f.write("--output\n")
        f.write(f'"{output_file.as_posix()}"\n')
        f.write('--local\n')
        f.write("--wkt\n")
        f.write(f'"{wkt_path.as_posix()}"\n')

    result = subprocess.run(['java', '-classpath', f'{region_chooser_libs}',
                             'eu.simstadt.regionchooser.RegionChooserCLI',
                             f'@{params_path}'
                             ],
                            text=True,
                            capture_output=True,
                            check=False
                            )
    if result.stderr:
        logger.error("%s", result.stderr)
    if result.returncode != 0:
        raise ValueError(f"RegionChooser failed with code {result.returncode}")
    logger.info("  DONE!")


def get_wkt(wkt_or_zipcode: str) -> str:
    """Returns WKT string for a given region, either specified as a POLYGON, or Zipcode(s).
    "POLYGON((...))"
    "MULTIPOLYGON(((...)))"
    "70567"
    "70567,70569"
    """
    if 'POLYGON' in wkt_or_zipcode:
        return wkt_or_zipcode

    return get_coordinates_by_zipcode(wkt_or_zipcode.split(','))


def convert_coordinates(match):
    """Convert WGS84 coordinates to UTM32N"""
    longitude, latitude = match.groups()
    x, y = TO_LOCAL_CRS.transform(longitude, latitude)
    return f"{x} {y}"


def convert_wkt_to_local(wkt_str):
    """Convert WKT from WGS84 to UTM32N"""
    return COORDINATES_REGEX.sub(convert_coordinates, wkt_str)


def parse_arguments():
    """Parse command line arguments"""
    parser = argparse.ArgumentParser(
        description="Download LoD2 CityGML tiles from LGL Baden-Württemberg and extract specific regions",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python download_files_from_LGL_BW.py StuttgartCenter "POLYGON((9.175287 48.780916, 9.185501 48.777522, 9.181467 48.773704, 9.174429 48.768472, 9.168807 48.773902, 9.175287 48.780916))"
  python download_files_from_LGL_BW.py Freiburg "79098,79102"
  python download_files_from_LGL_BW.py Möhringen "70567" --download-only
"""
    )

    parser.add_argument('name', type=str,
                        help='Name of the region (no spaces allowed). Output files will use this name.')

    parser.add_argument('region', type=str,
                        help='Region specification as WKT POLYGON/MULTIPOLYGON string or zipcode(s) (comma-separated).')

    parser.add_argument('--download-only', action='store_true',
                        help='Only download files without extracting the region (default: False).')

    parser.add_argument('--simstadt-folder', type=Path, default=None,
                        help='Path to SimStadt installation folder. By default, tries to find it on the Desktop.')

    return parser.parse_args()


def main(location_name: str, wkt_or_zipcode: str, download_only: bool = False, simstadt_folder: Path | None = None):
    """Main function to process arguments and run the download/extraction"""

    # Validate location name
    if ' ' in location_name:
        raise ValueError("Location name should not contain spaces: 'Some City' -> 'SomeCity'")

    # Create output directory
    output_dir = SCRIPT_DIR / (location_name + '.proj')
    output_dir.mkdir(parents=True, exist_ok=True)

    # Get WKT string
    wkt_str = get_wkt(wkt_or_zipcode)

    # Get grid coordinates
    x1, x2, y1, y2 = wkt_polygon_to_grid_coords(location_name, wkt_str)

    # Download region
    download_whole_region(output_dir, wkt_str, x1, x2, y1, y2)

    # Extract region if not download-only
    if not download_only:
        simstadt_folder = simstadt_folder or find_simstadt_folder()
        if not simstadt_folder:
            logger.error(
                "No SimStadt installation found! Please provide --simstadt-folder or use --download-only.")
            return

        extract_region(output_dir, location_name, wkt_str, simstadt_folder)
    else:
        logger.info("Download-only mode: Skipping region extraction.")

    logger.info("Processing of %s complete!", location_name)


if __name__ == '__main__':
    args = parse_arguments()
    main(args.name, args.region, args.download_only, args.simstadt_folder)
