import sys
from os import path

from nabu.app.utils import parse_params_values
from nabu.pipeline.config import generate_nabu_configfile as generate_configfile

from .integrator_config import integrator_config

BootstrapConfig = {
    "output": {
        "help": "Output filename",
        "default": "integrator.conf",
    },
    "nocomments": {
        "help": "Remove the comments in the configuration file (default: False)",
        "action": "store_const",
        "const": 1,
    },
    "level": {"help": "Obsolete parameter"},
    "dataset": {
        "help": "Pre-fill the configuration file with the dataset path.",
        "default": "",
    },
}


def parse_sections(sections):
    sections = sections.lower()
    if sections == "all":
        return None
    sections = sections.replace(" ", "").split(",")
    return sections


def bootstrap():
    args = parse_params_values(
        BootstrapConfig,
        parser_description="Initialize a configuration file",
    )
    no_comments = bool(args["nocomments"])

    if path.isfile(args["output"]):
        rep = input("File %s already exists. Overwrite ? [y/N]" % args["output"])
        if rep.lower() != "y":
            print("Stopping")
            sys.exit(0)

    prefilled_values = {}
    if args["dataset"] != "":
        prefilled_values["dataset"] = {}
        user_dataset = args["dataset"]
        if not path.isabs(user_dataset):
            user_dataset = path.abspath(user_dataset)
            print("Warning: using absolute dataset path %s" % user_dataset)
        if not path.exists(user_dataset):
            print("Error: cannot find the file or directory %s" % user_dataset)
            sys.exit(1)
        prefilled_values["dataset"]["location"] = user_dataset

    # Forcing level to "advanced", still not fixed in nabu side
    generate_configfile(
        args["output"],
        integrator_config,
        comments=not (no_comments),
        options_level="advanced",
        prefilled_values=prefilled_values,
    )
