import argparse
import importlib
import json
import os
from typing import Optional

default_dir = os.getenv('work_dir', os.path.abspath(os.path.join(__file__, '..', '..', '..', '..')))
work_dir = os.getenv("code_dir") or default_dir
LAYOUT_ROOT = os.path.join(work_dir, "hiklayout")
# LAYOUT_CONFIG_PATH = r'{work_dir}/hiklayout/conf.json'
LAYOUT_CONFIG_PATH = os.path.join(LAYOUT_ROOT, "conf.json")

if not os.path.exists(LAYOUT_CONFIG_PATH):
    raise FileNotFoundError("layout config not found" + LAYOUT_CONFIG_PATH)

with open(LAYOUT_CONFIG_PATH, "r", encoding='utf-8') as f:
    layout_config = json.load(f)


def get_args():
    layout_args = layout_config.get("args", {})
    args = argparse.Namespace(**layout_args)
    return args


def get_agents(layout_groups=None):
    """获得前端下发的智能体设置"""
    agents = []
    layout_groups = layout_groups or layout_config.get("groups", [])  # list[dict]
    for group in layout_groups:
        if group.get("connected") is False:
            continue
        group_side: str = group["side"]
        if group_side == "红方":
            group_side = "RED"
        elif group_side == "蓝方":
            group_side = "BLUE"

        group_agents = group["agents"]  # list[dict]
        for agent in group_agents:
            agent_id = agent["id"]
            agent_path: str = agent["file_path"]  # py文件的绝对路径
            # agent_dir
            # if agent_path not in sys.path:
            #     sys.path.append(agent_path)
            # agent_name = os.path.basename(agent_path)
            # agent_module = "hiklayout.{}".format(agent_id)
            # if agent["agent_type"] in ["强化学习"]:
            agent_obj = importlib.import_module(agent_path).Agent(agent_id, group_side)
            agents.append(agent_obj)

    return agents


def get_pretrain_model_path() -> Optional[str]:
    """获得预训练模型路径"""
    restore_model_path = os.getenv('restore_model_path')
    if not restore_model_path:
        return None
    pretrain_model_path = os.path.join(restore_model_path, 'model')
    return pretrain_model_path


def get_scenario_path():
    """
    解析前端配置, 返回其中的场景路径
    :return: scenario_path, str, 场景路径
    """
    layout_data = layout_config.get("data", {})
    scenario_path = layout_data.get("scenario_path", "user_config/kz_config/scene_train.json")
    return scenario_path


def get_engine_hosts():
    """获取引擎host列表"""
    parallelism = int(os.getenv("parallelism", 1))
    engine_service = os.getenv("engine_service")
    # return [f"{engine_service}-{index}.{engine_service}" for index in range(parallelism)]
    return ["{service}-{index}.{service}".format(service=engine_service, index=index) for index in range(parallelism)]
