from __future__ import annotations

from enum import Enum
from typing import Any, Dict, Optional

import aiohttp

# 明道云开放接口：基础配置
MDY_BASE_URL = "https://api.mingdao.com"
MDY_ENDPOINT_GET_FILTER_ROWS = "/v2/open/worksheet/getFilterRows"

# NOTE:
# - 目前项目里 appKey/sign 仍是硬编码（与现有同步代码保持一致）
# - 后续如果要做多环境/更安全配置，建议迁移到环境变量或 Django settings
MDY_APP_KEY = "208e55fea5cea59f"
MDY_SIGN = "MWU0YmViYjkwZmM1ZDIzYzRiN2U3ZGQ4MmE4ZGNkMjc0MWM1ZmQ2ZjkwMjljODE4YmNkZTBhMzA0OTU2YzE2NA=="


class HTTPMethod(Enum):
    """HTTP 请求方法枚举"""

    GET = "GET"
    POST = "POST"


class MingDaoYunClient:
    """明道云 API 客户端（异步）"""

    def __init__(self, app_key: str, sign: str, base_url: str = MDY_BASE_URL):
        self.app_key = app_key
        self.sign = sign
        self.base_url = base_url

    async def request(
        self,
        method: HTTPMethod,
        endpoint: str,
        data: Optional[Dict[str, Any]] = None,
        params: Optional[Dict[str, Any]] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> Any:
        """通用异步请求函数"""

        url = f"{self.base_url}{endpoint}"

        default_headers: Dict[str, str] = {
            "Content-Type": "application/json",
        }
        if headers:
            default_headers.update(headers)

        # 添加认证参数
        auth_params = {
            "appKey": self.app_key,
            "sign": self.sign,
        }

        async with aiohttp.ClientSession(headers=default_headers) as session:
            if method == HTTPMethod.GET:
                async with session.get(url, params=params, json=auth_params) as response:
                    response.raise_for_status()
                    return await response.json()

            if method == HTTPMethod.POST:
                payload: Dict[str, Any] = dict(data or {})
                payload.update(auth_params)
                async with session.post(url, json=payload) as response:
                    response.raise_for_status()
                    return await response.json()

            raise ValueError(f"Unsupported HTTP method: {method}")

    async def get(
        self,
        endpoint: str,
        params: Optional[Dict[str, Any]] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> Any:
        """发送 GET 请求"""

        return await self.request(
            method=HTTPMethod.GET,
            endpoint=endpoint,
            params=params,
            headers=headers,
        )

    async def post(
        self,
        endpoint: str,
        data: Optional[Dict[str, Any]] = None,
        params: Optional[Dict[str, Any]] = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> Any:
        """发送 POST 请求"""

        return await self.request(
            method=HTTPMethod.POST,
            endpoint=endpoint,
            data=data,
            params=params,
            headers=headers,
        )


def get_default_mingdaoyun_client(base_url: str = MDY_BASE_URL) -> MingDaoYunClient:
    """获取默认配置的明道云客户端（复用项目现有 appKey/sign）"""

    return MingDaoYunClient(app_key=MDY_APP_KEY, sign=MDY_SIGN, base_url=base_url)
