#!/usr/bin/python3

"""
@file
@copyright
  SPDX-FileCopyrightText: 2020-2025 European Southern Observatory (ESO) @n
  SPDX-License-Identifier: LGPL-3.0-only
"""

from deployment_utils.find_file import find_file
import sys
import os
import shutil
import argparse
import re


def parse_args(arguments):
    """
    Parses the command line arguments passed as a list
    If you pass the command line arguments, it first removes argv[0]
    by passing:
        sys.argv[1:]
    """
    parser = argparse.ArgumentParser(
        description="""
Utility to be used in the definition of the actions
that will take place before starting a nomad task
The only feature of the current implementation is to copy the given nomad template
in the nomad job local filesystem, to be found when the task is started.
The utility assumes that $NOMAD_ALLOC_DIR is set: this is done by nomad.
If -d is NOT passed, the utility assumes that $NOMAD_JOB_NAME is set: this is done automatically by nomad.
If the utility is run outside nomad (for example for testing), the environment variables need to be set.
""",
        formatter_class=argparse.RawTextHelpFormatter
    )

    parser.add_argument(
        "-t",
        "--template",
        required=True,
        type=str,
        help="""
Template name to be copied to nomad job local template directory.
The template is searched by default (i.e. if no -d option is passed) 
by using the following deprecated strategy:
- extract the {project_name} as the first word of the NOMAD_JOB_NAME
- search with find_file(nomad/{project_name}/{template})
otherwise if -d is set, the given template relative path is passed directly to find_file()
"""
    )
    parser.add_argument(
        "-d",
        "--defaultPath",
        action="store_true",
        help="Use just CFGPATH to find_file({template}) without any further name manipulation",
    )
    # This contains the parsed arguments
    args = parser.parse_args(arguments)

    return args


def main(args):
    try:
        nomad_alloc_dir = os.getenv("NOMAD_ALLOC_DIR")
        if nomad_alloc_dir is None:
                raise Exception("NOMAD_ALLOC_DIR environment variable not set")
        nomad_dir = nomad_alloc_dir + "/template"
        print(f"Nomad temporary template dir path {nomad_dir}")

        default_path = args.defaultPath
        template = args.template
        print(f"Template to copy: {template}")

        # Search absolute directory of needed template file
        # just using find_file() if --default_path argument is added
        if default_path:
            file_dir = find_file(template)
        # or using the legacy and deprecated algorithm if no --default_path is given
        else:
            print("WARNING: this is a deprecated search algorithm. Switch to -d")
            nomad_job_name = os.getenv("NOMAD_JOB_NAME")
            if nomad_job_name is None:
                raise Exception(f"NOMAD_JOB_NAME environment variable not set")
            print(f"Nomad job name {nomad_job_name}")

            # We use simple regex to find project name from Nomad job name
            # Because different projects use snake_case, camelCase etc. it will match first word
            project_name = re.findall("^[a-z]+", nomad_job_name)[0]
            print(f"Project name {project_name}")

            file_to_search = f"nomad/{project_name}/{template}"
            print(f"File to search: {file_to_search}")
            file_dir = find_file(file_to_search)

        if file_dir is None:
            raise Exception(f"Template {template} not found")
        print(f"Template absolute path: {file_dir}")

        if not os.path.exists(nomad_dir):
            os.mkdir(nomad_dir)

        # Copy template file to nomad temp alloc directory
        shutil.copy(file_dir, nomad_dir)
        print(f"File successfully copied")
        return 0
    except Exception as ex: 
        print(ex)
        return 1        

if __name__ == "__main__":
    args = parse_args(sys.argv[1:])
    ISOK = main(args)

    sys.exit(ISOK)
