# --- package ---
# --- custom_module ---
import sys

# 20260507 tak will be check
#sys.path.append('C:/Users/Administrator/PycharmProjects/pythonProject/20230426/cmd/build_scripter')

# --- custom ---
from custom_lib import Custom_Lib as custom

# --- common ---
import os
from datetime import datetime
from pathlib import Path
import shutil

def check_path(config_path):
    try:
        check_exit_flag = False
        config_exit_flag = False

        if os.path.isfile(f'{config_path}/user.config'):
            while not check_exit_flag:
                print(f'User config file already exists.\nDo you want to change the config (Yes/no)?')

                check_config = input('> ')

                if check_config.lower() == 'no' or check_config.lower() == 'exit':
                    check_exit_flag = True
                    config_exit_flag = True
                    break

                elif check_config.lower() == 'yes':
                    break

                else:
                    log.error(f'Option verification failed, please try again.')

        elif not os.path.isfile(f'{config_path}/user.config'):
            a = custom.my_file_config.save_config()

            custom.my_file_config.write_config(a, config_path, f'{config_path}/user.config')

        while not config_exit_flag:
            print('Input PycharmProjects Path')

            write_config = input('> ')

            if write_config.lower() == 'exit':
                config_exit_flag = True
                break

            elif os.path.exists(write_config):
                a = custom.my_file_config.save_config()

                a['pycharmprojects'] = {}
                a['pycharmprojects']['path'] = write_config

                custom.my_file_config.write_config(a, config_path, f'{config_path}/user.config')
                config_exit_flag = True
                break

            else:
                log.error(f'Path verification failed, please try again.')

    except Exception as e:
        log.error(e)

def main(config_path):
    print(f'{company_name} {prm_title} v{prm_ver}\n'
          f'(c) {company_name}. All rights reserved.\n'
          f'System information as of {sys_date}\n')

    exit_flag = False

    a = custom.my_file_config.read_config(f'{config_path}/user.config')
    pythonproject_path = (a['pycharmprojects']['path'])

    while not exit_flag:
        print(f'\n[Exec]\n'
              f'[1] {typ1}\n'
              f'[2] {typ2}')

        try:
            input_exec = input('> ')

            if input_exec == 'exit':
                exit_flag = True

            elif input_exec == '1':
                while not exit_flag:
                    print(f'[{typ1}]\n[1] uuid1\n[4] uuid4\n[9] back')

                    input_exec1_1 = input('> ')

                    if input_exec1_1 == 'exit':
                        exit_flag = True
                        break

                    elif input_exec1_1 == '1' or input_exec1_1 == '4':
                        while not exit_flag:
                            print(f'[{typ1}]\nInput Program name\n[9] back')

                            input_exec1_2 = input('> ')

                            if input_exec1_2 == 'exit':
                                exit_flag = True
                                break

                            elif input_exec1_2 != 'exit' and input_exec1_2 != '9':
                                prm_uuid = custom.my_uuid.create_uuid(input_exec1_1)
                                log.info(f"{input_exec1_2}-{prm_uuid}")

                            elif input_exec1_2 == '9':
                                break

                            else:
                                log.error(f'Option verification failed, please try again.')

                    elif input_exec1_1 == '9':
                        break

                    else:
                        log.error(f'Option verification failed, please try again.')

            elif input_exec == '2':
                while not exit_flag:
                    print(f'[{typ2}]\nInput Build Script\n[9] back')

                    input_exec2_1 = input('> ')

                    if input_exec2_1 == 'exit':
                        exit_flag = True
                        break

                    elif '.py' in input_exec2_1 and input_exec2_1 != 'exit' and input_exec2_1 != '9':
                        build_scripts = input_exec2_1.split(' ')

                        for build_script in build_scripts:
                            if build_script.endswith('.py'):
                                source_name = os.path.splitext(os.path.basename(build_script))[0]
                                pythonproject_path_list = build_script.split("\\")[:int(len(pythonproject_path.split('\\'))+1)]
                                pjt_path = "\\".join(pythonproject_path_list)

                        for build_script in build_scripts:
                            if 'specpath=' in build_script:
                                spec_file = f'{pjt_path}{build_script.split("=")[1].replace(".", "")}{source_name}.spec'
                                if os.path.isfile(spec_file):
                                    os.remove(spec_file)

                            elif 'distpath=' in build_script:
                                dist_path = f'{pjt_path}{build_script.split("=")[1].replace(".", "")}'
                                if os.path.isdir(f'{dist_path}{source_name}'):
                                    shutil.rmtree(f'{dist_path}{source_name}')

                            elif 'workpath=' in build_script:
                                work_path = f'{pjt_path}{build_script.split("=")[1].replace(".", "")}'
                                if os.path.isdir(f'{work_path}{source_name}'):
                                    shutil.rmtree(f'{work_path}{source_name}')

                        os.system(f'{pjt_path}\\venv\\Scripts\\activate.bat && cd {pjt_path} && {input_exec2_1}')

                        break

                    elif input_exec2_1 == '9':
                        break

                    else:
                        log.error(f'Build script verification failed, please try again.')

            else:
                log.error(f'Option verification failed, please try again.')

        except Exception as e:
            log.error(e)

# --- prm_info_variables ---
company_name = 'ATEC IoT'
prm_title = Path(os.path.basename(sys.argv[0])).stem.replace('_', ' ')

prm_renew_ver = 1
prm_modify_ver = 0
prm_bug_ver = 0
prm_ver = f'{prm_renew_ver}.{prm_modify_ver}.{prm_bug_ver}'

prm_uuid = 'a0dfdd50-dcbc-11ed-8864-0456e5df0ac9'

# --- type_variables ---
typ1 = 'Create UUID'
typ2 = 'Execute Build'

# --- path_variables ---
loc_path = os.getcwd()

home_dir = os.path.expanduser('~')
appdata_dir = os.path.join(home_dir, 'AppData', 'Local')
new_dir = f'{company_name.replace(" ", "")}/{prm_title}/{prm_ver}'
new_dir_path = os.path.join(appdata_dir, new_dir)

path_list = [new_dir_path]

# --- common_variables ---
datetime = datetime.now()
sys_date = datetime.strftime('%Y.%m.%d %H:%M:%S')

''' build command'''
# pyinstaller --specpath=.\20230426\app\spec\ --distpath=.\20230426\app\dist\ --workpath=.\20230426\app\build\ --name=Build_Scripter -c -F C:\Users\Administrator\PycharmProjects\pythonProject\20230426\cmd\build_scripter\Build_Scripter.py --hidden-import=configparser --hidden-import=uuid --hidden-import=logging
# pyinstaller --distpath=.\20230426\app\dist\ --workpath=.\20230426\app\build\ --onedir=C:\Users\Administrator\PycharmProjects\pythonProject\20230426\app\spec\Build_Scripter.spec

if __name__ == '__main__':
    custom.init()

    if prm_uuid != None:
        log = custom.my_logger.logger()

        try:
            for file_path in path_list:
                if not os.path.isdir(file_path):
                    os.makedirs(file_path)

            check_path(new_dir_path)
            main(new_dir_path)

        except Exception as e:
            log.error(e)