#! /usr/bin/python3

import os
import argparse
import subprocess
import re
import shutil
from pathlib import Path
from distutils.dir_util import copy_tree
import fileinput
from dotenv import dotenv_values


def parse_arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", "--name",
                        required=False,
                        type=str,
                        help="Internal repository part to be built")
    parser.add_argument("-v", "--version",
                        required=True,
                        type=str,
                        help="Repository version")
    return parser.parse_args()


def main() -> None:
    args = parse_arguments()
    if args.name is None or args.name == 'amccore':
        front_path = "frontend"
        back_path = "console"

        footer_path = f"{front_path}/src/components/Layout/components/Footer"
        console_base_path = "console/settings/base.py"

        # PUBLIC_URL for react app
        react_env = dotenv_values('deb/react.env')
        os.environ['PUBLIC_URL'] = react_env['PUBLIC_URL']

        # version
        version_found = False

        # change base.py version
        with fileinput.input(files=console_base_path, inplace=True) as fileLines:
            for line in fileLines:

                if re.search('SITE_INFO = {', line) is not None:
                    version_found = True
                if version_found and re.search(' *}', line) is not None:
                    version_found = False

                if version_found:
                    res = re.sub(r"(.*version': )[^,]*", rf"\g<1>'{args.version}'", line)
                else:
                    res = line

                if res is not None:
                    print(res, flush=True, end="")

        # check environment.js for localhost
        with open(f'{front_path}/src/enviroments/enviroments.js', 'r') as file:
            for line in file:
                if re.match(r'.*localhost: *.*localhost.*', line) is not None:
                    print('Error: localhost in enviroments.js')
                    exit(1)

        # -----------------------------build React-------------------------------------
        res = subprocess.Popen(['npm', 'ci'], cwd=front_path)#, env=react_env)
        res.wait()

        if res.returncode != 0:
            print("npm ci failed", flush=True)
            exit(1)
        else:
            print("npm ci successed", flush=True)

        res = subprocess.Popen(['npm', 'run', 'build'], cwd=front_path)#, env=react_env)
        res.wait()

        if res.returncode != 0:
            print("'npm run build' failed", flush=True)
            exit(1)
        else:
            print("'npm run build' successed", flush=True)

        shutil.rmtree(f'{front_path}/node_modules')

        shutil.move(f'{front_path}/build/index.html', f'{back_path}/templates/console/index.html')

        if os.path.exists(f'{back_path}/static/react'):
            shutil.rmtree(f'{back_path}/static/react')

        Path(f'{back_path}/static/react').mkdir(parents=True, exist_ok=True)
        copy_tree(f'{front_path}/build/', f'{back_path}/static/react/')


if __name__ == "__main__":
    main()
