"""参数初始化模块"""

from typing import Dict, Any, Optional
from pathlib import Path

from ..reference import GSDSTORE, MODULEDATA, INFO


class InitData:
    """参数初始化类

    负责初始化测试所需的各类数据。
    """

    def __init__(self, work_path: str = None):
        """初始化

        Args:
            work_path: 工作目录路径
        """
        self._work_path = Path(work_path) if work_path else Path.cwd()
        self._element_data: Dict[str, Any] = {}
        self._custom_params: Dict[str, Any] = {}

    def load_element_data(self, file_path: str = None) -> Dict[str, Any]:
        """加载元素数据

        Args:
            file_path: elementData.yaml 文件路径

        Returns:
            Dict: 元素数据
        """
        if not file_path:
            # 默认路径
            file_path = self._work_path / 'data' / 'elementData' / 'elementData.yaml'

        path = Path(file_path)
        if not path.exists():
            INFO(f"元素数据文件不存在: {file_path}", "WARNING")
            return {}

        try:
            import yaml
            with open(path, 'r', encoding='utf-8') as f:
                self._element_data = yaml.safe_load(f) or {}

            MODULEDATA['elementData'] = self._element_data
            INFO(f"加载元素数据: {len(self._element_data)} 个模块")

        except ImportError:
            INFO("PyYAML 未安装，无法加载元素数据", "WARNING")
        except Exception as e:
            INFO(f"加载元素数据失败: {e}", "ERROR")

        return self._element_data

    def load_custom_params(self, params: Dict[str, Any] = None) -> Dict[str, Any]:
        """加载自定义参数

        Args:
            params: 自定义参数字典

        Returns:
            Dict: 自定义参数
        """
        if params:
            self._custom_params.update(params)
            GSDSTORE['START']['selfDefinedParameter'] = self._custom_params
            INFO(f"加载自定义参数: {list(params.keys())}")

        return self._custom_params

    def setup_work_path(self) -> None:
        """设置工作路径"""
        GSDSTORE['WORKPATH'] = {
            'root': str(self._work_path),
            'data': str(self._work_path / 'data'),
            'result': str(self._work_path / 'result'),
            'plugins': str(self._work_path / 'plugins'),
        }

        # 确保目录存在
        (self._work_path / 'result' / 'report').mkdir(parents=True, exist_ok=True)
        (self._work_path / 'result' / 'log').mkdir(parents=True, exist_ok=True)
        (self._work_path / 'result' / 'screenshot').mkdir(parents=True, exist_ok=True)
        (self._work_path / 'result' / 'trace').mkdir(parents=True, exist_ok=True)
        (self._work_path / 'result' / 'video').mkdir(parents=True, exist_ok=True)

        INFO(f"工作目录: {self._work_path}")

    @property
    def element_data(self) -> Dict[str, Any]:
        """获取元素数据"""
        return self._element_data

    @property
    def custom_params(self) -> Dict[str, Any]:
        """获取自定义参数"""
        return self._custom_params

    @property
    def work_path(self) -> Path:
        """获取工作路径"""
        return self._work_path
