#! /usr/bin/env python
# _*_ coding: utf-8 _*_
"""
author:     Chen XuHui
date:       2024/9/2
file:       engine.py
version:
doc:        引擎独有参数的设置.
"""
import argparse
import json
import os
import sys
from typing import List

from corekit.utils.annotations import Deprecated


@Deprecated(
    old='corekit.config.engine.EngineConfig',
    new='corekit.config.base.BaseTaskConfig',
    help='旧API只能适用于ray.tune.run训练任务, 新API可对接其他任务',
    error=True
)
class EngineConfig:
    """引擎独有参数的设置"""

    @classmethod
    def get_default_config(cls) -> dict:
        """获取引擎独有参数的默认值"""
        return {}

    @classmethod
    def get_frontend_args(cls, fronted_path: str = None) -> dict:
        """从web前端获得用户的设置"""
        if 'win' in sys.platform:  # windows本地运行, 无前端参数
            return {}

        from corekit.hikframe.rl.layout import layout_config, get_pretrain_model_path, get_engine_hosts

        # 获取前端配置字典
        if fronted_path is not None:
            fronted_path = fronted_path or os.path.join(os.getenv('work_dir'), 'hiklayout', 'conf.json')
            with open(fronted_path, 'r', encoding='utf-8') as fp:
                frontend_config = json.load(fp)
        else:
            frontend_config = layout_config.copy()

        # 前端配置的训练参数
        frontend_args: dict = frontend_config.get('args', {})
        frontend_args['framework']: str = 'torch' if frontend_args.get('torch') is True else 'tf'
        frontend_args['engine']: str = frontend_config.get('data', {}).get('scenario', {}).get('engine', 'zl')
        frontend_args['pretrained_path']: str = get_pretrain_model_path() or ''
        frontend_args['engine_hosts']: List[str] = get_engine_hosts()

        frontend_args.update(cls.deal_frontend_args(frontend_config))
        return frontend_args

    @classmethod
    def deal_frontend_args(cls, frontend_config: dict = None) -> dict:
        """处理前端设置"""
        if frontend_config is None:
            return {}

        return {}

    @classmethod
    def add_command_args(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
        """添加引擎独有参数的命令行设置"""
        return parser

    @classmethod
    def update_engine_config(cls, args: dict) -> dict:
        """接口, 更新引擎训练相关的设置"""
        args.update(cls.get_space_config(args))
        args.update(cls.get_callback_config(args))
        args.update(cls.get_multiagent_config(args))
        return args

    @classmethod
    def get_space_config(cls, args: dict) -> dict:
        """获得引擎所需的动作/状态空间设置

        不同引擎在使用不同训练算法时所需的动作/状态空间不同, 只能由引擎自己设置
        """
        return {}

    @classmethod
    def get_callback_config(cls, args: dict) -> dict:
        """获得引擎的回调器设置"""
        return {}

    @classmethod
    def get_multiagent_config(cls, args: dict) -> dict:
        """获得引擎的多智能体设置"""
        return {}
