from __future__ import annotations

from pathlib import Path

from yera.config.tool_config import ToolConfig
from yera.tools.atlas_tool import AtlasTool
from yera.tools.tool_utils import load_tools_config


class ToolAtlas:
    @staticmethod
    def from_config_map(config_map: dict[str, ToolConfig]) -> ToolAtlas:
        root = ToolAtlas()

        for path, cfg in config_map.items():
            parts = path.split(".")
            current = root
            for part in parts[:-1]:
                if not hasattr(current, part):
                    setattr(current, part, ToolAtlas())
                current = getattr(current, part)

            setattr(current, parts[-1].replace("-", "_"), AtlasTool(cfg))

        return root

    def __getitem__(self, key: str):
        current = self
        for part in key.split("."):
            current = getattr(current, part, None)
            if current is None:
                raise KeyError(key)
        return current

    def list_tools(self):
        attrs = [getattr(self, n) for n in dir(self)]
        attrs = [a for a in attrs if isinstance(a, ToolAtlas | AtlasTool)]

        tools = []
        for attr in attrs:
            if isinstance(attr, ToolAtlas):
                tools += attr.list_tools()
            if isinstance(attr, AtlasTool):
                tools.append(attr)

        return tools


def get_tool_atlas(cfg_path: Path | str | None = None) -> ToolAtlas:
    raw_cfg_map = load_tools_config(cfg_path)
    return ToolAtlas.from_config_map(raw_cfg_map)
