import json

from mower.solvers.fight import FightSolver
from mower.utils import config
from mower.utils.path import get_path


class Oper:
    def __init__(self, name, skill=1):
        self.name = name
        self.skill = skill

    # 定义哈希函数，以便在 set 中去重
    def __hash__(self):
        return hash((self.name, self.skill))

    # 定义相等性判断
    def __eq__(self, other):
        if isinstance(other, Oper):
            return self.name == other.name and self.skill == other.skill
        return False


class CopyWorksSolver:
    def run(self):
        self.auto_choose = True
        # if config.conf.work.try_select_all:
        #    self.init_all_opers_and_groups()
        while len(config.conf.work.works):
            # if config.conf.work.try_select_all and not self.auto_choose:

            work = config.conf.work.works[0]
            work_path = get_path(f"@app/works/{work["stage"]}.json")
            with work_path.open("r", encoding="utf-8") as f:
                work_data = json.load(f)
            if not FightSolver().run(
                work["stage"],
                work_data["opers"],
                work_data["actions"],
                work_data["groups"],
                self.auto_choose,
                work["support_oper"],
                work["retry_times"],
            ):
                return
            config.conf.work.works.pop(0)

    def init_all_opers_and_groups(self):
        all_opers = set()
        all_groups = set()
        for work in config.conf.work.works:
            work_path = get_path(f"@app/works/{work["stage"]}.json")
            with work_path.open("r", encoding="utf-8") as f:
                work_data = json.load(f)
                for oper in work_data["opers"]:
                    name = oper["name"]
                    skill = oper.get("skill", 1)
                    all_opers.add(Oper(name, skill))
                for group in work_data["groups"]:
                    all_groups.add(group)
        self.all_groups = [
            group
            for group in all_groups
            if not any(
                Oper(op["name"], op.get("skill", 1)) in all_opers
                for op in group["opers"]
            )
        ]
        self.all_opers = list({"name": op.name, "skill": op.skill} for op in all_opers)
        if len(all_opers) + len(all_groups) <= 12:
            self.auto_choose = False
