import traceback
from mpi4py import MPI
from typing import Optional
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter


def nc2rline(input_file: str, geometry: str, index_column: Optional[str] = None,
             weight_column: Optional[str] = None, weight_file: Optional[str] = None,
             var_list: Optional[list[str]] = None):
    """
    Placeholder function for converting a NetCDF file to RLINE format.

    Parameters
    ----------
    input_file : str
        Path to the NetCDF file to transform.
    geometry : str
        Path to the geometry file (e.g., GeoJSON or Shapefile) with line features.
    index_column : str, optional
        Name of the column to use as index. If not provided, order will be used.
    weight_column : str, optional
        Name of the column in the geometry to use as weight.
    weight_file : str, optional
        Path to the weight file. If exists, it will be read; otherwise, it will be written.
    var_list : list of str, optional
        List of NetCDF variables to include. If not provided, all variables will be used.
    """
    print(f"[INFO] input_file: {input_file}")
    print(f"[INFO] geometry: {geometry}")
    print(f"[INFO] index_column: {index_column}")
    print(f"[INFO] weight_column: {weight_column}")
    print(f"[INFO] weight_file: {weight_file}")
    print(f"[INFO] var_list: {var_list}")
    print("[INFO] Functionality not yet implemented.")


def main():
    parser = ArgumentParser(
        description="Convert NetCDF to RLINE format using geometry lines.",
        formatter_class=ArgumentDefaultsHelpFormatter
    )

    parser.add_argument("input_file", help="NetCDF file to transform to RLINE format.")
    parser.add_argument("geometry", help="Geometry file (e.g., GeoJSON or Shapefile) with roads.")
    parser.add_argument("--index_column", help="Column name in the geometry to use as index.", default=None)
    parser.add_argument("--weight_column", help="Column name in the geometry to use as weight.", default=None)
    parser.add_argument("--weight_file", help="Auxiliary weight file (read if exists, write otherwise).", default=None)
    parser.add_argument("--var_list", nargs='+', help="List of NetCDF variables to include. If not provided, all variables will be used.", default=None)

    args = parser.parse_args()

    nc2rline(
        input_file=args.input_file,
        geometry=args.geometry,
        index_column=args.index_column,
        weight_column=args.weight_column,
        weight_file=args.weight_file,
        var_list=args.var_list
    )


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"Process {MPI.COMM_WORLD.Get_rank()}: NES critical error detected {e}, aborting MPI.", flush=True)
        print(f"Process {MPI.COMM_WORLD.Get_rank()}: Traceback:\n{traceback.format_exc()}", flush=True)

        MPI.COMM_WORLD.Abort(1)
