import os
from concurrent.futures import ThreadPoolExecutor
import time

from pilot.unit.unit_interface import UnitInterface
from pilot.job.impl.base_job import BaseJob
from pilot.config.config_reader import ConfigReader, ConfigDTO  # 追加

class BaseUnit(UnitInterface):
    config_dto: ConfigDTO = None  # 型アノテーションを追加
    joblist = []

    def __init__(self):
        pass


    def _init_job(self,step):
        return BaseJob()

    def run(self):
        steps = self.config_dto.steps
        skipsteps = self.config_dto.skipsteps

        runsteps = self.config_dto.runsteps

        def run_step(index):
            if index >= len(steps):
                return
            step = steps[index]
            if step in skipsteps:
                run_step(index + 1)
                return

            if len(runsteps)  == 0 :
                pass
            elif len(runsteps) != 0 and step not in runsteps:
                run_step(index + 1)
                return

            current_step_dir = self.config_dto.work_space + "/" + step

            max_workers = self.config_dto.threads
            unit_multisteps = self.config_dto.multisteps
            if step in unit_multisteps:
                max_workers = self.config_dto.threads
            else:
                max_workers = 1
            def step_worker():
                self._run_jobs_in_step_dir(current_step_dir, step, index)

            with ThreadPoolExecutor(max_workers=max_workers) as executor:
                future = executor.submit(step_worker)
                future.result()
                # STEP完了後、次のSTEPを実行
                run_step(index + 1)

        run_step(0)

    def _run_jobs_in_step_dir(self, current_step_dir, step, index):
        for dirpath, _, filenames in os.walk(current_step_dir):
            for filename in filenames:
                file_path = os.path.join(dirpath, filename)
                job = self._init_job(step)
                job.config_dto = self.config_dto
                job.current_step = step
                job.step_index = index
                job.file_path = file_path
                if self.job_need_run(job, filename, index):
                    job.run()


    def job_need_run(self, job:BaseJob,filename: str,index):
        return True