import yaml
import json
import shutil
from pathlib import Path
from ..flow import Flow


class Evaluator:
    def __init__(self,config,class_map):
        self.config = config.copy()
        self.class_map = class_map

        self.evaluator_config = self.config["evaluator"]
        max_version = self.evaluator_config.get("max_version",3)
        resume = self.evaluator_config.get("resume",False)
        work_path = Path(self.config["flow"]["work_path"])
        new_work_path = self.version_manager(work_path,resume,max_version)
        self.config["flow"]["work_path"] = str(new_work_path)

        self.flow = Flow.from_config(self.config,class_map)
        self.flow.logger.debug("Config:\n%s", json.dumps(config, indent=4, ensure_ascii=False))

    @classmethod
    def from_yaml(cls,config_path,class_map):
        with open(config_path,"r") as f:
            config = yaml.safe_load(f)
        return cls(config,class_map)

    def version_manager(self,path,resume,max_version):
        version_folder_list = list(path.glob("version_*"))
        version_list = [{"index": int(x.stem.split("_")[1]), "folder": x} for x in version_folder_list]
        version_list.sort(key=lambda x: x["index"])
        excess = len(version_list) - (max_version - 1)
        if excess > 0:
            for version in version_list[:excess]:
                shutil.rmtree(version["folder"])

        if len(version_list) > 0:
            if resume:
                version = version_list[-1]["index"] + 1
            else:
                version = version_list[-1]["index"]
        else:
            version = 0
        return path / f"version_{version}"

    def run(self):
        run_config = self.config["run"]
        self.flow.run(**run_config)

    def summary(self):
        summarizer_config = self.config["summarizer"]
        self.flow.logger.info("Start summarizing...")
        summarizer = self.class_map[summarizer_config["cls"]](self.flow,**summarizer_config["init_input"])
        summarizer.summary()
        self.flow.logger.info("Summarizing done.")


        

