import argparse
from meshgen.mesh import Mesh
from meshgen.version import __version__
from pathlib import Path

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
)


def cli():
    """Entry point for the CLI."""
    parser = argparse.ArgumentParser(
        prog="meshgen",
        description="convert between comsol, jcmsuite, and gmsh meshes",
    )
    parser.add_argument("input", help="with extension jcm, mphtxt, or msh")
    parser.add_argument("output", help="with extension jcm, mphtxt, or msh")
    parser.add_argument(
        "-m",
        "--mode",
        help="writing mode (binary only possible for .jcm files)",
        choices=["a", "w", "x", "ab", "wb", "xb"],
        default="x",
    )
    parser.add_argument(
        "-s",
        "--skip_1d",
        help="skip writing 1D elements in 2D COMSOL meshes",
        action="store_true",
    )

    parser.add_argument("--version", action="version", version=__version__)
    args = parser.parse_args()
    meshes = Mesh.read(args.input)

    if len(meshes) == 1:
        meshes[0].write(args.output, mode=args.mode, skip_1d=args.skip_1d)
        return 0

    outfile = Path(args.output)
    for i, mesh in enumerate(meshes):
        mesh.write(
            outfile.with_name(f"{outfile.stem}_{i+1}{outfile.suffix}"),
            mode=args.mode,
            skip_1d=args.skip_1d,
        )
    return 0
