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

"""
extract_cobol_vars_of.py

从 COBOL 程序中提取业务变量，关键字来源于 XML。
当出现 “FIELD OF RECORD” 结构时，把整个字符串作为一个变量返回。
"""
from pathlib import Path
from typing import List
from pilot.job.impl.base_job import BaseJob

from pilot.job.base.program.cobol.tool_base.ToolBase import load_cobol_keywords_set, extract_variables
from pilot.db.sql_service import insert_sql_info, delete_sql_info       


class GetFieldInfoByProcedureBase(BaseJob):
    keyword_file_path : str
    field_list : List[str]

    def run(self):
        # 1. キーワードXMLのパス設定と読み込み
        keywords = load_cobol_keywords_set()

        # 2. COBOLソースファイルの読み込み
        # BaseJob の仕様に基づき self.file_path をソースパスとして使用
        cobol_path = Path(self.file_path)
        procedure_name = Path(self.file_path).name.split('.')[0]
        cobol_name = Path(self.file_path).parent.parent.name

        if cobol_path and cobol_path.is_file():
            cobol_code = cobol_path.read_text(encoding="utf-8")

            # 3. 変数の抽出とソート
            vars_set = extract_variables(cobol_code, keywords)

            delete_params_info = {
                'cobol_name': cobol_name,
                'procedure_name':procedure_name
            }
            # delete_sql_info('delete_procedure_parameter_info', delete_params_info)

            for var_info in vars_set:

                parameter_name = var_info.strip()
                parameter_parent = ''

                if ' OF ' in var_info.upper():
                    parameter_name = var_info.upper().split(' OF ')[0]
                    parameter_parent = var_info.upper().split(' OF ')[1]

                if '-' in parameter_name:
                    parameter_key_name = parameter_name.split('-')[0]
                else:
                    parameter_key_name = parameter_name

                insert_params_info = {
                    'cobol_name': cobol_name,
                    'procedure_name': procedure_name,
                    'parameter_key_name': parameter_key_name,
                    'parameter_name': parameter_name,
                    'parameter_parent':parameter_parent
                }

                # insert_sql_info('insert_procedure_parameter_info', insert_params_info)

            self.field_list = sorted(vars_set)

        # 基底クラスの run を呼び出して終了処理
        super().run()
