"""公共逻辑方法"""

import os
import json
import hashlib
from typing import Any, Dict, List, Optional
from pathlib import Path

from ..reference import INFO


class PublicScript:
    """公共脚本工具类

    提供文件操作、数据处理等公共方法。
    """

    # ==================== 文件操作 ====================

    @staticmethod
    def read_file(file_path: str, encoding: str = 'utf-8') -> str:
        """读取文件内容

        Args:
            file_path: 文件路径
            encoding: 编码

        Returns:
            str: 文件内容
        """
        with open(file_path, 'r', encoding=encoding) as f:
            return f.read()

    @staticmethod
    def write_file(file_path: str, content: str, encoding: str = 'utf-8') -> None:
        """写入文件

        Args:
            file_path: 文件路径
            content: 内容
            encoding: 编码
        """
        Path(file_path).parent.mkdir(parents=True, exist_ok=True)
        with open(file_path, 'w', encoding=encoding) as f:
            f.write(content)

    @staticmethod
    def append_file(file_path: str, content: str, encoding: str = 'utf-8') -> None:
        """追加写入文件

        Args:
            file_path: 文件路径
            content: 内容
            encoding: 编码
        """
        Path(file_path).parent.mkdir(parents=True, exist_ok=True)
        with open(file_path, 'a', encoding=encoding) as f:
            f.write(content)

    @staticmethod
    def read_json(file_path: str) -> Any:
        """读取 JSON 文件

        Args:
            file_path: 文件路径

        Returns:
            解析后的 JSON 数据
        """
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)

    @staticmethod
    def write_json(file_path: str, data: Any, indent: int = 2) -> None:
        """写入 JSON 文件

        Args:
            file_path: 文件路径
            data: 数据
            indent: 缩进
        """
        Path(file_path).parent.mkdir(parents=True, exist_ok=True)
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=indent, ensure_ascii=False)

    @staticmethod
    def read_yaml(file_path: str) -> Any:
        """读取 YAML 文件

        Args:
            file_path: 文件路径

        Returns:
            解析后的 YAML 数据
        """
        import yaml
        with open(file_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)

    @staticmethod
    def write_yaml(file_path: str, data: Any) -> None:
        """写入 YAML 文件

        Args:
            file_path: 文件路径
            data: 数据
        """
        import yaml
        Path(file_path).parent.mkdir(parents=True, exist_ok=True)
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(data, f, default_flow_style=False, allow_unicode=True)

    @staticmethod
    def file_exists(file_path: str) -> bool:
        """检查文件是否存在

        Args:
            file_path: 文件路径

        Returns:
            bool: 是否存在
        """
        return Path(file_path).exists()

    @staticmethod
    def delete_file(file_path: str) -> bool:
        """删除文件

        Args:
            file_path: 文件路径

        Returns:
            bool: 是否成功
        """
        try:
            Path(file_path).unlink(missing_ok=True)
            return True
        except Exception:
            return False

    @staticmethod
    def list_files(directory: str, pattern: str = '*') -> List[str]:
        """列出目录下的文件

        Args:
            directory: 目录路径
            pattern: 匹配模式

        Returns:
            List[str]: 文件路径列表
        """
        return [str(p) for p in Path(directory).glob(pattern)]

    # ==================== 数据处理 ====================

    @staticmethod
    def dict_get(data: Dict, key_path: str, default: Any = None) -> Any:
        """从嵌套字典获取值

        Args:
            data: 字典
            key_path: 键路径 (用点分隔)
            default: 默认值

        Returns:
            值
        """
        keys = key_path.split('.')
        value = data

        for key in keys:
            if isinstance(value, dict):
                value = value.get(key)
            elif isinstance(value, list) and key.isdigit():
                index = int(key)
                value = value[index] if 0 <= index < len(value) else None
            else:
                return default

            if value is None:
                return default

        return value

    @staticmethod
    def dict_set(data: Dict, key_path: str, value: Any) -> None:
        """设置嵌套字典的值

        Args:
            data: 字典
            key_path: 键路径
            value: 值
        """
        keys = key_path.split('.')

        for key in keys[:-1]:
            if key not in data:
                data[key] = {}
            data = data[key]

        data[keys[-1]] = value

    @staticmethod
    def merge_dicts(*dicts: Dict) -> Dict:
        """合并多个字典

        Args:
            *dicts: 要合并的字典

        Returns:
            Dict: 合并后的字典
        """
        result = {}
        for d in dicts:
            result.update(d)
        return result

    @staticmethod
    def list_to_dict(data: List[Dict], key: str) -> Dict:
        """将列表转换为字典

        Args:
            data: 字典列表
            key: 作为键的字段名

        Returns:
            Dict: 转换后的字典
        """
        return {item[key]: item for item in data if key in item}

    # ==================== 加密工具 ====================

    @staticmethod
    def md5(text: str) -> str:
        """MD5 加密

        Args:
            text: 原文

        Returns:
            str: MD5 值
        """
        return hashlib.md5(text.encode()).hexdigest()

    @staticmethod
    def sha256(text: str) -> str:
        """SHA256 加密

        Args:
            text: 原文

        Returns:
            str: SHA256 值
        """
        return hashlib.sha256(text.encode()).hexdigest()

    @staticmethod
    def base64_encode(text: str) -> str:
        """Base64 编码

        Args:
            text: 原文

        Returns:
            str: 编码后的字符串
        """
        import base64
        return base64.b64encode(text.encode()).decode()

    @staticmethod
    def base64_decode(text: str) -> str:
        """Base64 解码

        Args:
            text: 编码字符串

        Returns:
            str: 解码后的字符串
        """
        import base64
        return base64.b64decode(text.encode()).decode()

    # ==================== 环境变量 ====================

    @staticmethod
    def get_env(name: str, default: str = '') -> str:
        """获取环境变量

        Args:
            name: 变量名
            default: 默认值

        Returns:
            str: 环境变量值
        """
        return os.environ.get(name, default)

    @staticmethod
    def set_env(name: str, value: str) -> None:
        """设置环境变量

        Args:
            name: 变量名
            value: 值
        """
        os.environ[name] = value

    # ==================== 验证工具 ====================

    @staticmethod
    def is_email(text: str) -> bool:
        """验证邮箱格式

        Args:
            text: 文本

        Returns:
            bool: 是否有效
        """
        import re
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        return bool(re.match(pattern, text))

    @staticmethod
    def is_phone(text: str) -> bool:
        """验证手机号格式

        Args:
            text: 文本

        Returns:
            bool: 是否有效
        """
        import re
        pattern = r'^1[3-9]\d{9}$'
        return bool(re.match(pattern, text))

    @staticmethod
    def is_url(text: str) -> bool:
        """验证 URL 格式

        Args:
            text: 文本

        Returns:
            bool: 是否有效
        """
        import re
        pattern = r'^https?://[^\s/$.?#].[^\s]*$'
        return bool(re.match(pattern, text, re.IGNORECASE))

    @staticmethod
    def is_json(text: str) -> bool:
        """验证 JSON 格式

        Args:
            text: 文本

        Returns:
            bool: 是否有效
        """
        try:
            json.loads(text)
            return True
        except (json.JSONDecodeError, TypeError):
            return False
