import requests
import time
from tenacity import (
    retry,
    stop_after_attempt,
    wait_exponential,
    retry_if_exception_type
)
from requests.exceptions import RequestException
from sds_mng.util import logger
from sds_mng.exception import UnauthorizedError

API_URL = "https://pod-api.sdspod.com/pod/orders/page"
REQUEST_TIMEOUT = 30
SLEEP = 0.5

@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    retry=retry_if_exception_type(RequestException),  # 仅重试 RequestException（UnauthorizedError 不会重试）
    reraise=True,
)
def _fetch(access_token, filters=None):
    headers = {"access-token": access_token}
    filters = (filters or {}).copy()
    page = filters.pop("page", 1)
    size = filters.pop("size", 100)
    order_status_code = filters.pop("orderStatusCode", None)
    params = {
        "orderTimeRangeType": "2",
        "productionType": "2",
        "page": page,
        "size": size,
        "t": int(time.time() * 1000),
        **filters,
    }
    if order_status_code:
        params["orderStatusCode"] = order_status_code

    logger.debug(f"请求参数: {params}")
    try:
        resp = requests.get(API_URL, headers=headers, params=params, timeout=REQUEST_TIMEOUT)
        logger.debug(f"响应状态码: {resp.status_code}")
        logger.debug(f"响应内容: {resp.text}")
        resp.raise_for_status()
        data = resp.json()
        logger.info(f"获取到 {len(data.get('list', []))} 条订单，总计 {data.get('totalCount', 0)} 条")
        time.sleep(SLEEP)
        return data
    except RequestException as e:
        # 如果响应是"用户未登录"，转换为 UnauthorizedError 避免重试
        if e.response is not None:
            try:
                if e.response.json().get("msg") == "用户未登录":
                    raise UnauthorizedError from e
            except Exception:
                pass
        raise e  # 其他异常会触发重试


def fetch_orders(access_token, filters=None, limit=None):
    page, size, all_orders = 1, 100, []
    total_count = 0

    while True:
        if limit and len(all_orders) >= limit:
            logger.warning(f"已达到获取数量限制: {limit}")
            break

        page_filters = {**(filters or {}), "page": page, "size": size}
        data = _fetch(access_token, page_filters)

        if page == 1:
            total_count = data.get("totalCount", 0)
            logger.info(f"总订单数: {total_count}")

        orders = data.get("list", [])
        if not orders:
            logger.info("没有更多订单了")
            break

        all_orders.extend(orders)
        logger.info(f"已获取第 {page} 页 ({len(orders)} 条)，累计 {len(all_orders)} 条")
        time.sleep(1)

        if len(orders) < size:
            logger.info("当前页数据少于每页数量，获取完成")
            break

        if limit and len(all_orders) >= limit:
            logger.warning(f"已达到获取数量限制: {limit}")
            break

        page += 1
        time.sleep(0.1)

    if limit:
        all_orders = all_orders[:limit]

    return {
        "totalCount": total_count,
        "fetchedCount": len(all_orders),
        "list": all_orders,
    }