# -*- coding: utf-8 -*-
import pytest
import json
import allure
from pathlib import Path
from api_auto_framework.core.request_wrapper import RequestWrapper
from api_auto_framework.utils.data_loader import load_test_data
from api_auto_framework.utils.assertion_tools import cookie
from api_auto_framework.utils.handle_path import testData_path


class TestBaiduCommonBaiduRequest:
    # 文件路径
    TEST_DATA = Path(testData_path) / "test_Baidu_Common_baiduRequest.yaml"

    @allure.feature("百度")
    @allure.story("广告搭建")
    @allure.title("百度检测低质封面")
    @pytest.mark.generated
    def test_baidu_common_baidu_request(self):
        """Automatically generated test case: 百度检测低质封面"""
        # 加载测试数据
        test_data = load_test_data(self.TEST_DATA)[0]
        # 准备请求参数
        request_kwargs = {
            "method": test_data['method'],
            "url": test_data['url'],
            "headers": test_data.get('headers'),
            "cookies": cookie()  # 新增cookies参数
        }
        # 智能选择请求体处理方式
        body = test_data.get('body')
        if body is not None:
            if isinstance(body, (dict, list)):
                request_kwargs["json"] = body
            else:
                request_kwargs["data"] = body
        with allure.step("准备请求数据"):
            print(f"请求参数: {request_kwargs['json']}")
            allure.attach(f"URL: https://cli1.mobgi.com/Baidu/Common/baiduRequest", "请求URL")
            allure.attach(json.dumps(body), "请求体", allure.attachment_type.JSON)
        # 发送请求并获取响应
        with allure.step(f"发送请求:test_baidu_common_baidu_request"):
            response = RequestWrapper.send_request(**request_kwargs)
            if response.status_code != 200:
                error_msg = f"请求失败，状态码: {response.status_code}"
                allure.attach(error_msg, "请求错误", allure.attachment_type.TEXT)
                pytest.fail(error_msg)
        with allure.step("处理请求"):
            try:
                result = RequestWrapper.formatted_response(response)
            except Exception as e:
                error_msg = f"响应处理失败: {str(e)}"
                allure.attach(error_msg, "响应处理错误", allure.attachment_type.TEXT)
                allure.attach(response.text, "原始响应内容", allure.attachment_type.TEXT)
                pytest.fail(error_msg)
        with allure.step("响应结果"):
            allure.attach(str(response.status_code), "响应状态", allure.attachment_type.TEXT)
            if result and "body" in result and "code" in result["body"]:
                allure.attach(str(result["body"]["code"]), "响应状态码", allure.attachment_type.TEXT)
            if result and "headers" in result:
                allure.attach(json.dumps(result["headers"], indent=2),
                              "响应头", allure.attachment_type.JSON)
            if result and "body" in result:
                body_content = result["body"]
                if isinstance(body_content, dict):
                    body_str = json.dumps(body_content, indent=2, ensure_ascii=False)
                else:
                    body_str = str(body_content)
                allure.attach(body_str, "响应内容", allure.attachment_type.JSON)

        # 基础状态码断言
        try:
            assert result["status_code"] == test_data["expected"]["status_code"], f"状态码不匹配: {result['status_code']} ≠ {test_data['expected']['status_code']}"
            assert result["body"]["code"] == 0, f"业务码非零: {result['body']['code']}"
            assert result["body"]["message"] == "成功", f"消息不符: {result['body']['message']}"
        except AssertionError as e:
            allure.attach(str(e), "断言失败详情", allure.attachment_type.TEXT)
            raise
        except KeyError as e:
            error_msg = f"响应体中缺少关键字段: {str(e)}"
            allure.attach(error_msg, "响应体结构错误", allure.attachment_type.TEXT)
            pytest.fail(error_msg)
