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

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, Timeout)),
    reraise=True,
)
def _fetch(access_token, filters=None):
    headers = {"access-token": access_token}

    page = 1
    size = 100
    order_status_code = None
    filter_dict = {}

    if filters:
        page = filters.get("page", page)
        size = filters.get("size", size)
        order_status_code = filters.get("orderStatusCode")
        exclude = {"page", "size", "orderStatusCode"}
        filter_dict = {k: v for k, v in filters.items() if k not in exclude}

    params = {
        "orderTimeRangeType": "2",
        "productionType": "2",
        "page": page,
        "size": size,
        "t": int(time.time() * 1000),
    }
    if order_status_code is not None:
        params["orderStatusCode"] = order_status_code
    if filter_dict:
        params.update(filter_dict)

    logger.debug(f"请求参数: {params}")
    resp = requests.get(
        API_URL, headers=headers, params=params, timeout=REQUEST_TIMEOUT
    )
    logger.debug(f"响应状态码: {resp.status_code}")
    resp.raise_for_status()
    data = resp.json()
    logger.info(
        f"获取到 {len(data.get('list', []))} 条订单，总计 {data.get('totalCount', 0)} 条"
    )
    time.sleep(SLEEP)
    return data


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

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

        page_filters = filters.copy() if filters else {}
        page_filters.update({"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,
    }
