# SPDX-FileCopyrightText: 2024 UL Research Institutes
# SPDX-License-Identifier: MIT

import copy
import logging
import re
import sys
from importlib import import_module
from io import StringIO
from pathlib import Path

from termcolor import colored

from ..constants import CONFIG_DIR_NAME, DEFAULT_PROVIDER


def get_bundle_name(text):
    return re.sub(r"[-_ ]+", "-", text.casefold())


def get_bundle_content(provider, bundle):
    content = StringIO()
    content.write(f"#\n")
    content.write(
        f"# This file is generated by cici-tools with the following command:\n"
    )
    content.write(f"#\n")
    content.write(f"#     {' '.join([Path(sys.argv[0]).name, *sys.argv[1:]])}\n")
    content.write(f"#\n")
    provider.dump(bundle, content)
    return content.getvalue()


def bundle_command(parser, args):
    logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s")

    provider = import_module(f".{DEFAULT_PROVIDER}", "cici.providers")

    ci_file_path = args.config_path / provider.CI_FILE

    if not Path(ci_file_path).exists():
        parser.error(f"file not found: {ci_file_path}")

    file = provider.load(ci_file_path)

    args.output_path = Path(args.output_path)

    for job_name, job in file.jobs.items():
        if job_name.startswith("."):
            continue

        bundle = copy.deepcopy(file)
        bundle.jobs = {}
        bundle.jobs[job_name] = job

        bundle_filename = args.output_path / f"{get_bundle_name(job_name)}.yml"

        content = get_bundle_content(provider, bundle)

        if bundle_filename.exists() and bundle_filename.is_file():
            old_content = open(bundle_filename).read()
            if old_content == content:
                print("  ", colored(bundle_filename.name, "grey"))
                continue

        with open(bundle_filename, "w") as stream:
            stream.write(content)
        print(colored("⚡", "yellow"), bundle_filename.name)


def bundle_parser(subparsers):
    parser = subparsers.add_parser(
        "bundle", help="bundle CI jobs with dependencies into standalone distributions"
    )
    parser.add_argument(
        "config_path",
        metavar="DIR",
        nargs="?",
        type=Path,
        default=(Path.cwd() / CONFIG_DIR_NAME).absolute(),
    )
    parser.add_argument("-g", "--groups", help="job group patterns")
    parser.add_argument(
        "-o",
        "--output",
        metavar="DIR",
        dest="output_path",
        type=Path,
        default=Path.cwd().absolute(),
    )
    parser.set_defaults(func=bundle_command)
    return parser
