"""
Utility script to classify a pointclound, in a "quick" and dirty way.
To use it, you'll need to install geopandas and laspy via pip.
"""

import argparse
import logging
import pathlib

try:
    # Optional dependency, displays a nice progress bar
    from tqdm import tqdm
except ModuleNotFoundError:
    tqdm = lambda i: i  # noqa E731 - that's OK

logger = logging.getLogger(__name__)


def classify(
    footprint_path: pathlib.Path, las_path: pathlib.Path, output_path: pathlib.Path
) -> None:
    import geopandas
    import laspy
    from shapely import contains_xy

    try:
        las_file = laspy.read(las_path)
    except Exception as e:
        raise RuntimeError("Could not read pointcloud") from e

    try:
        footprint_file = geopandas.read_file(footprint_path)
    except Exception as e:
        raise RuntimeError("Could not read footprint") from e

    merged_polygon = footprint_file.geometry.union_all()
    for i in tqdm(range(0, len(las_file))):
        if contains_xy(merged_polygon, las_file.x[i], las_file.y[i]):
            las_file.classification[i] = 6  # Building
        else:
            las_file.classification[i] = 2  # Ground

    try:
        las_file.write(output_path)
    except Exception as e:
        raise RuntimeError("Could not write output file") from e


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=("Classifies a pointcloud based on footprint")
    )
    parser.add_argument(
        "footprint", help="path to the input footprint file", type=pathlib.Path
    )
    parser.add_argument(
        "pointcloud", help="path to the input pointcloud file", type=pathlib.Path
    )
    parser.add_argument(
        "output",
        help="path to the output classified pointcloud file",
        type=pathlib.Path,
    )
    args = parser.parse_args()

    try:
        classify(
            args.footprint,
            args.pointcloud,
            args.output,
        )
    except ModuleNotFoundError:
        logger.error(
            "This script requires geopandas and laspy packages. "
            "Try installing them, via `pip install -r requirements/utils.txt`."
        )
        exit(-1)
