#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
將 (method_name → sub_method_name) 的關係轉成一棵樹，
然後把所有節點依「深度」分組：
    depth = 0   → 完全沒有子節點的葉子
    depth = 1   → 子節點全部是 depth=0 的節點
    …
最深的 depth 為 root（可能有多個）。
"""

import json
import os
import shutil
from collections import defaultdict, deque
from pathlib import Path
from typing import Dict, List, Set, Tuple

from pilot.base.file_operation import read_json_file_lines, write_file_line, read_file_lines, write_json_file
from pilot.job.impl.base_job import BaseJob


class CodeMergeBaseJob(BaseJob):

    target_file_path =''
    skip_method_list = []
    def run(self):

        order_file_list = read_file_lines(self.file_path)
        target_folder_path = Path(self.file_path).parent / 'work'
        moto_folder_path = Path(self.file_path).parent
        if os.path.isdir(str(target_folder_path)):
            shutil.rmtree(str(target_folder_path))

        os.makedirs(str(target_folder_path), exist_ok=False)
        end_file_name = ''

        for file_name in order_file_list:
            end_file_name = file_name.strip()
            cobol_file_name = file_name.strip() + '.cob.json'
            cobol_content_path = target_folder_path / cobol_file_name
            if not os.path.exists(cobol_content_path):
                cobol_content_path_moto = moto_folder_path  / cobol_file_name
                shutil.copy(cobol_content_path_moto, target_folder_path)

            cobol_lines = read_json_file_lines(cobol_content_path)

            procedure_relation_file_name = file_name.strip() + '.sub_method.json'
            procedure_relation_file_path = target_folder_path / procedure_relation_file_name
            if not os.path.exists(procedure_relation_file_path):
                procedure_relation_file_path_moto = moto_folder_path  / procedure_relation_file_name
                shutil.copy(procedure_relation_file_path_moto, target_folder_path)

            procedure_relation_lines = read_json_file_lines(procedure_relation_file_path)
            edit_cobol_lines = []

            for cobol_info in cobol_lines:
                cobol_content = cobol_info.get('code').strip()
                edited_cobol_content_list = cobol_content.split('\n')

                relation_flg = False
                for procedure_relation_info in procedure_relation_lines:
                    sub_method_name = procedure_relation_info.get('sub_method_name').strip()
                    if sub_method_name and sub_method_name not in self.skip_method_list:
                        for edited_cobol_content in edited_cobol_content_list:
                            add_space_edited_cobol_content = edited_cobol_content + ' '
                            if ' ' + sub_method_name + ' ' in add_space_edited_cobol_content or ' ' + sub_method_name + '.' in add_space_edited_cobol_content:
                                leading_spaces = len(edited_cobol_content) - len(edited_cobol_content.lstrip(" "))
                                relation_flg = True
                                sub_method_file_name = sub_method_name + '.cob.json'
                                sub_method_file_path = target_folder_path / sub_method_file_name
                                if not os.path.exists(sub_method_file_path):
                                    sub_method_file_path_moto = moto_folder_path / sub_method_file_name
                                    shutil.copy(sub_method_file_path_moto, target_folder_path)
                                sub_method_lines = read_json_file_lines(sub_method_file_path)
                                for sub_method_info in sub_method_lines:
                                    if 'SECTION.' not in sub_method_info.get('code'):
                                        edited_method_info = {
                                            'comment': sub_method_info.get('comment'),
                                            'code':  (" " * leading_spaces) + sub_method_info.get('code')
                                        }
                                        edit_cobol_lines.append(edited_method_info)

                if not relation_flg:
                    edit_cobol_lines.append(cobol_info)

            write_json_file(edit_cobol_lines, cobol_content_path)

        _end_file_name = end_file_name + '.cob.json'
        _target_file_name = Path(self.file_path).name.split('_')[0] + '.cob.json'
        shutil.copy2(target_folder_path / _end_file_name , moto_folder_path / _target_file_name)

        self.target_file_path = str(moto_folder_path / _target_file_name)

        super().run()


