import os
import re


class Config:
    RANGE_NUM: int = 0
    WORK_PATH = ""
    INPUT_PATH = ""

    @staticmethod
    def load_config():
        # 构建 config/index.js 的相对路径
        config_file_path = os.path.join(
            os.path.dirname(__file__), "..", "config", "index.js"
        )
        with open(config_file_path, "r", encoding="utf-8") as file:
            content = file.read()
            # 移除注释行
            uncommented_content = re.sub(r"//.*", "", content)
            input_dir_match = re.search(
                r'inputDir:\s*["\']?(.*?)["\']?\s*,', uncommented_content
            )
            directory_path_match = re.search(
                r'directoryPath:\s*["\']?(.*?)["\']?\s*,', uncommented_content
            )
            range_num_match = re.search(
                r'rangeNum:\s*["\']?(.*?)["\']?\s*,', uncommented_content
            )
            if input_dir_match:
                Config.INPUT_PATH = input_dir_match.group(1)
            if directory_path_match:
                Config.WORK_PATH = directory_path_match.group(1)
            if range_num_match:
                Config.RANGE_NUM = int(range_num_match.group(1))

    @staticmethod
    def get_latest_folder(base_directory):
        if Config.INPUT_PATH:
            return Config.INPUT_PATH
        folders = [
            os.path.join(base_directory, d)
            for d in os.listdir(base_directory)
            if os.path.isdir(os.path.join(base_directory, d))
        ]
        if not folders:
            return None
        latest_folder = max(folders, key=os.path.getctime)  # 获取最新创建的文件夹
        return latest_folder


Config.load_config()
