from pathlib import Path
from typing import List

from pilot.job.impl.base_job import BaseJob

# 置換後の文字（空白）
REPLACEMENT_CHAR = " "

# コメント行の開始文字
COMMENT_LEAD_CHAR = "*"

class removeCommentLinesBase(BaseJob):

    def main(self, lines: List[str]) -> List[str]:
        file_name = Path(self.file_path).name
        if file_name.endswith('.ipo'):
            leading_chars_count = 0
        else:
            leading_chars_count = 6
        result = []
        for line in lines:
            # 空行処理
            if not line.strip():
                result.append(line)
                continue

            # 文字未満 → そのまま出力
            if len(line) < leading_chars_count:
                result.append(line)
                continue

            # 置換処理
            replaced_line = self._replace_leading_chars_with_spaces(line, leading_chars_count)

            if replaced_line.lstrip().startswith(COMMENT_LEAD_CHAR):
                continue
            result.append(replaced_line)

        return result

    def _replace_leading_chars_with_spaces(self, line: str, leading_chars_count: int ) -> str:
        # 文字を ' ' に置き換え
        return f"{REPLACEMENT_CHAR * leading_chars_count}{line[leading_chars_count:]}"

    def run(self):
        file_content_lines = self.get_file_content_lines()
        result_content = self.main(file_content_lines)

        src_path = Path(self.file_path)

        tmp_path = src_path.parent / (src_path.name + '.tmp')
        with open(tmp_path, 'w', encoding='utf-8', newline='') as wf:
            wf.writelines(result_content)

        tmp_path.replace(src_path)

        next_step_file = self.copy_input_file_to_next_step(self.file_path)
        self.create_next_step_todo_trg_file_from_input(next_step_file)

        super().run()

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

        return file_content_lines

