# -*- coding: utf-8 -*-
"""
@Time : 2025/7/30 10:46
@Auth : 九月的海
@File : request_wrapper.py.py
@IDE : PyCharm
@Motto : Catch as catch can....
"""
import requests
from urllib.parse import urlparse, urlunparse


class RequestWrapper:
    @staticmethod
    def environment(url, env='prod'):
        """根据环境替换URL的域名部分"""
        # 环境域名映射配置
        env_mapping = {
            'dev': '180.184.59.85',  # 预发环境
            'test': '180.184.58.89',  # 测试环境
            'prod': '180.213.188.227'  # 生产环境
        }
        # 解析原始URL
        parsed = urlparse(url)
        # 获取新域名（默认为原始域名）
        new_domain = env_mapping.get(env, parsed.netloc)
        # 重建URL并返回
        new_parsed = parsed._replace(netloc=new_domain)
        return urlunparse(new_parsed)

    @staticmethod
    def send_request(method, url, **kwargs):
        """发送HTTP请求"""
        try:
            processed_url = RequestWrapper.environment(url, env=kwargs.pop('env', 'prod'))
            response = requests.request(
                method=method.upper(),
                url=processed_url,
                verify=False,
                **kwargs
            )
            return response
        except requests.RequestException as e:
            raise ConnectionError(f"请求失败: {str(e)}")

    @staticmethod
    def formatted_response(response):
        """格式化响应结果"""
        return {
            "status_code": response.status_code,
            "headers": dict(response.headers),
            "body": response.json() if response.content else {}
        }
