"""
Main entry point for the MARTe Autodoc project"

Author: Martino Ferrari
Email: martinogiordano.ferrari@iter.org
"""

import logging
import os
import sys
from argparse import ArgumentParser

import autodoc

__version__ = "0.0.0"


def __args__():
    """Parse arguments."""
    parser = ArgumentParser(
        prog="autodoc",
        description="MARTe configuration auto documentation tool",
    )
    parser.add_argument("filename", help="Configuration file to document", type=str)
    parser.add_argument(
        "--type",
        choices=["json", "marte"],
        default="marte",
        help="Configuration file type (default: `marte`)",
    )
    parser.add_argument(
        "--loglevel",
        choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
        default="ERROR",
        help="Logging level (default: `ERROR`)",
    )
    parser.add_argument("--build", help="build output flag", default=True)
    parser.add_argument("--version", action="version", version=__version__)
    parser.add_argument(
        "-d", "--destination", help="Destination folder", type=str, default="."
    )
    return parser.parse_args()


def main():
    """Main function."""
    args = __args__()
    logging.basicConfig(level=args.loglevel)
    logging.info(f"AutoDoc v{__version__}")
    if not os.path.exists(args.filename):
        logging.error(f"Specified file `{args.filename}` does not exists")
        sys.exit(1)
    config = {}
    if args.type == "marte":
        from MARTe.StandardParser import ParseException, StandardParser

        parser = StandardParser()
        try:
            config = parser.parse_file(args.filename)
        except ParseException as e:
            logging.error(
                f"Impossible to parse file `{args.filename}` at position ({e.line},{e.col}): {e.msg}`"
            )
            sys.exit(1)
        except Exception:
            logging.error(f"Sometihng went wrong with file `{args.filename}`")
            sys.exit(1)
    else:
        import json

        with open(args.filename, "r") as file:
            config = json.load(file)
    if not config:
        logging.error(f"Impossible to load configuration `{args.filename}`")
        sys.exit(1)
    filename = os.path.splitext(os.path.basename(args.filename))[0]
    autodoc.document(filename, args, config)


if __name__ == "__main__":
    main()
