import requests
import json
from typing import Union
from get_baidu_token import GetBaiduToken


def get_baidu_campaign_request(identifier: Union[str, int], body: dict) -> dict:
    """
    向百度API发送请求
    :param identifier: 广告主名称或媒体账户ID
    :param body: 请求体内容
    :return: API响应结果
    """
    # 获取header
    token_getter = GetBaiduToken(identifier)
    header = token_getter.get_header()
    if not header:
        return {"error": "Failed to get valid header"}
    # 构建完整请求负载
    payload = {
        "header": header,
        "body": body
    }
    # API端点
    url = "https://api.baidu.com/json/feed/v1/CampaignFeedService/getCampaignFeed"
    # 请求头
    http_headers = {
        "Accept-Encoding": "gzip, deflate",
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
    try:
        # 发送请求
        response = requests.post(
            url,
            data=json.dumps(payload),
            headers=http_headers
        )

        # 返回JSON响应
        return response.json()
    except Exception as e:
        return {"error": f"API request failed: {str(e)}"}


# 使用示例
if __name__ == "__main__":
    # 定义请求体
    request_body = {
        "campaignFeedFields": [    # 需要查询的字段列表
            "campaignFeedId",
            "campaignFeedName",
            "subject",
            "appinfo",
            "budget",
            "starttime",
            "endtime",
            "schedule",
            "pause",
            "status",
            "bstype",
            "addtime",
            "eshopType",
            "rtaStatus",
            "bid",
            "bidtype",
            "ftypes",
            "ocpc",
            "bmcUserId",
            "catalogId",
            "projectFeedId",
            "productType",
            "appSubType",
            "deliveryType",
            "miniProgramType",
            "bidMode",
            "productIds",
            "saleType"
        ],
        "campaignFeedIds": [1413521619],  # 广告计划ID
        "campaignFeedFilter": {
            "bstype": [1]      # 广告类型  1-普通计划 3-商品计划  7-原生RTA
        }
    }

    # 使用广告主名称查询
    # response = make_baidu_api_request("原生-SLG-乱世-安卓12A20KA00006", request_body)

    # 使用媒体账户ID查询
    response = get_baidu_campaign_request("12466757256", request_body)

    print(json.dumps(response, ensure_ascii=False))
