import mikeio
import geopandas as gpd
import os

def mesh2poly(input_fname, output_fname, verbose=True):
    """
    Convert a MIKE mesh file to a GeoDataFrame of polygons.
    Parameters:
    - input_fname: Path to the MIKE mesh file (.mesh).
    - output_fname: Path to save the output GeoDataFrame (.shp).
    - verbose: If True, print progress messages.
    Returns:
    - A GeoDataFrame containing the polygons of the mesh elements.
    """
    # Check if file exists
    if not os.path.exists(input_fname):
        raise FileNotFoundError(f"Input file not found: {input_fname}")
    # Check file extensions
    if not input_fname.endswith(".mesh"):
        raise ValueError("Input file must have a .mesh extension")
    if not output_fname.endswith(".shp"):
        raise ValueError("Output file must have a .shp extension")
    # Make sure output directory exists
    output_dir = os.path.dirname(output_fname)
    if output_dir and not os.path.exists(output_dir):
        if verbose:
            print(f"WARNING: Output directory does not exist. Creating: {output_dir}")
        os.makedirs(output_dir)
    # Load mesh
    mesh = mikeio.Mesh(input_fname)
    geom = mesh.geometry
    projection = geom.projection if geom.projection != "LONG/LAT" else "EPSG:4326"
    z = mesh.element_coordinates[:, 2]
    mpoly = geom.to_shapely()
    polygons = list(mpoly.geoms)
    values = z.flatten()

    gdf = gpd.GeoDataFrame(data={"ID": range(len(polygons)), "Bathymetry": values}, geometry=polygons, crs=projection)
    gdf.to_file(output_fname)
    if verbose:
        print(f"Mesh converted to polygons and saved to: {output_fname}")
