import os
import re
from pathlib import Path
from typing import List

from pilot.job.impl.base_job import BaseJob

class MergeCopyFileBaseJob(BaseJob):
    expanded_lines = List[str]
    replace_info_list = List[str]

    PATTERN_COPY = re.compile(
            r'^\s*COPY\s+([A-Z0-9\-_]+)'  # COPY名
            r'(?:\s+REPLACING\s+==([^=]+)==\s+BY\s+==([^=]+)==)?'  # 可能的REPLACING old,new
            r'\.?\s*$', re.IGNORECASE)

    def expand_copy_in_file(self, cbl_lines, copy_dir_list):
        expanded_lines = []
        replace_info_list = []

        for idx, line in enumerate(cbl_lines, 1):
            m = self.PATTERN_COPY.match(line)
            if m:
                copy_name = m.group(1)
                replacing_old = m.group(2)
                replacing_new = m.group(3)
                copy_file = ''
                for copy_dir in copy_dir_list:
                    copy_file = os.path.join(str(copy_dir), copy_name, copy_name + '.rec')  # 根据实际路径及后缀修改
                    if os.path.exists(copy_file):
                        break

                if not os.path.exists(copy_file):
                    print(f'{copy_name} is not found.')
                    continue

                if os.path.isfile(copy_file):
                    copy_file_encoding = 'utf-8'
                    with open(copy_file, 'r', encoding=copy_file_encoding) as cf:
                        copy_content = cf.readlines()
                    # 处理 REPLACING
                    if replacing_old is not None and replacing_new is not None:
                        replaced_content = [l.replace(replacing_old, replacing_new) for l in copy_content]
                        expanded_lines.extend(replaced_content)
                        if replacing_new not in replace_info_list:
                            replace_info_list.append(replacing_new)
                    else:
                        expanded_lines.extend(copy_content)
                else:
                    expanded_lines.append(line)
            else:
                expanded_lines.append(line)
        return expanded_lines, replace_info_list

    def run(self):
        try:
            step_root = self.get_current_step_relative_path()

            copy_folder_path_list = []
            if 'COPY' in self.file_path.upper():
                copy_folder_path = Path(self.get_current_step_relative_path()).parent
                copy_folder_path_list.append(copy_folder_path)
            else:
                copy_folder_path_list = self.find_copy_dirs_pathlib(step_root)

            cbl_lines = self.get_file_content_list()

            _expanded_lines, _replace_info_list = self.expand_copy_in_file(cbl_lines, copy_folder_path_list)

            self.expanded_lines = _expanded_lines
            self.replace_info_list = _replace_info_list

        except Exception as e:
            self.logger.error(f"{self.file_path}異常終了. {e}")
            return
        super().run()

    def get_file_content_list(self):

        with open(self._file_path, 'r', encoding='utf-8') as f:
            content_lines = f.readlines()

        return content_lines

    def find_copy_dirs_pathlib(self, root_dir: str | Path) -> List[Path]:
        """
        使用 pathlib 实现同样的功能。
        返回值是 pathlib.Path 对象列表，使用更方便（支持 / 操作符拼接等）。
        """
        root = Path(root_dir)
        if not root.is_dir():
            raise ValueError(f"{root!r} 不是有效的目录")

        copy_dirs: List[Path] = []

        # rglob("*") 会递归遍历所有子路径（文件+目录），我们只关心目录
        for p in root.rglob("*"):
            if p.is_dir() and "copy" in p.name.lower():
                copy_dirs.append(p)

        return copy_dirs
