
import requests
import json
import sys
import time
from np_log import setup_logging
# 初始化日志配置 - 降低控制台日志级别减少输出
logger = setup_logging('magic_api', console_level="warning", file_level="info")
# 全局变量 - 基础URL
BASE_URL = 'http://192.168.31.125:9999'


class RequestClient():
    def __init__(self, base_url=BASE_URL, timeout=5, retries=2, retry_delay=1):
        """
        初始化请求客户端
        :param base_url: 基础URL
        :param timeout: 请求超时时间（减少到5秒）
        :param retries: 最大重试次数（减少到2次）
        :param retry_delay: 重试延迟时间（秒）（减少到1秒）
        """
        self.base_url = base_url
        self.timeout = timeout
        self.retries = retries
        self.retry_delay = retry_delay
        # 创建会话以复用连接
        self.session = requests.Session()
        logger.info(f"RequestClient初始化完成，基础URL: {base_url}")

    def post(self, endpoint, params=None, data=None, json=None, headers={'Content-Type': 'application/json'}):
        """
        POST请求方法 - 优化版本
        """
        if not endpoint.startswith('/'):
            endpoint = f"/{endpoint}"
        url = f"{self.base_url}{endpoint}"

        logger.debug(f"准备发送POST请求到: {url}")

        for attempt in range(self.retries):
            try:
                response = self.session.post(url, params=params, data=data, json=json,
                                             headers=headers, timeout=self.timeout)
                response.raise_for_status()

                logger.debug(f"POST请求成功，状态码: {response.status_code}")
                return response

            except requests.exceptions.RequestException as err:
                logger.warning(f"第{attempt + 1}次POST请求失败: {err}")
                if attempt < self.retries - 1:
                    time.sleep(self.retry_delay)
                else:
                    logger.error("POST请求最终失败")
                    raise
        return None

    def get(self, endpoint, params=None, headers=None):
        """
        GET请求方法 - 优化版本
        """
        if not endpoint.startswith('/'):
            endpoint = f"/{endpoint}"
        url = f"{self.base_url}{endpoint}"

        logger.debug(f"准备发送GET请求到: {url}")

        for attempt in range(self.retries):
            try:
                response = self.session.get(url, params=params, headers=headers,
                                            timeout=self.timeout)
                response.raise_for_status()

                logger.debug(f"GET请求成功，状态码: {response.status_code}")
                return response

            except Exception as err:
                logger.warning(f"第{attempt + 1}次GET请求失败: {err}")
                if attempt < self.retries - 1:
                    time.sleep(self.retry_delay)
                else:
                    logger.error("GET请求最终失败")
                    raise

    def call_api(self, endpoint, method='get', params=None, json=None):
        """
        通用API调用函数 - 优化版本
        """
        logger.debug(f"调用API - 端点: {endpoint}, 方法: {method.upper()}")

        try:
            if method.lower() == 'get':
                response = self.get(endpoint, params=params)
            elif method.lower() == 'post':
                response = self.post(endpoint, params=params, json=json)
            else:
                logger.error(f"不支持的请求方法: {method}")
                return None

            if response and response.status_code == 200:
                data = response.json().get("data", "")
                return data
            else:
                logger.error(f"API调用失败({endpoint}): 状态码 {getattr(response, 'status_code', '无响应')}")
                return None

        except Exception as e:
            logger.error(f"API调用异常({endpoint}): {str(e)}")
            return None

    # ========== 数据库操作方法的优化版本 ==========

    def select(self, data_base=None, tab_name=None, where_str="1=1", fields="*", sql=None):
        """
        通用数据查询 - 优化版本
        """
        # 参数验证
        if sql is None and (data_base is None or tab_name is None):
            return {"message": "传入的参数错误，data_base或tab_name为None"}

        # 构建SQL语句

        final_sql = sql if sql else f"select {fields} from {data_base}.{tab_name} where {where_str}"

        response = self.get("select", params={"sql": final_sql})
        if not response:
            return {"message": "请求失败"}

        response_data = response.json()
        if response_data.get("message") == "success":
            return response_data.get("data", "")
        else:
            logger.error(f"SELECT查询失败: {response_data}")
            return response_data

    def selectOne(self, data_base=None, tab_name=None, where_str="1=1", fields="*", sql=None):
        """
        单条数据查询 - 优化版本
        """
        # 参数验证
        if sql is None and (data_base is None or tab_name is None):
            return {"message": "传入的参数错误，data_base或tab_name为None"}

        # 构建SQL语句
        final_sql = sql if sql else f"select {fields} from {data_base}.{tab_name} where {where_str}"

        response = self.get("selectOne", params={"sql": final_sql})
        if not response:
            return {"message": "请求失败"}

        response_data = response.json()
        if response_data.get("message") == "success":
            return response_data.get("data", "")
        else:
            logger.error(f"SELECT_ONE查询失败: {response_data}")
            return response_data

    def update(self, data_base, tab_name, where_str: str, set_dict: dict):
        """
        更新数据 - 优化版本
        """
        # 参数处理（兼容旧版本）
        if isinstance(where_str, dict):
            temp = where_str
            where_str = set_dict
            set_dict = temp

        # 构建SET字符串
        try:
            set_dict_str = json.dumps(set_dict)
            set_dict_str = set_dict_str.replace(':', " =").replace("{", "").replace("}", "").replace('"', "")
            sql = f"update {data_base}.{tab_name} set {set_dict_str} where {where_str}"

            response = self.post("update", params={"sql": sql})
            if not response:
                return False

            response_data = response.json()
            if response_data.get("message") == "success":
                return True
            else:
                logger.error(f"UPDATE操作失败: {response_data}")
                return False

        except Exception as e:
            logger.error(f"UPDATE操作异常: {str(e)}")
            return False

    def insert(self, data_base, tab_name, set_str):
        """
        插入数据 - 优化版本
        """
        sql = f"insert into {data_base}.{tab_name} set {set_str}"

        response = self.post("insert", params={"sql": sql})
        if not response:
            return False

        response_data = response.json()
        if response_data.get("message") == "success":
            return True
        else:
            logger.error(f"INSERT操作失败: {response_data}")
            return False

    def magic_api_select(self, data_base, tab_name, where_dict):
        """
        magic_api查询 - 优化版本
        """
        endpoint = f"llm_select_tab_field_data/{data_base}/{tab_name}"
        response = self.get(endpoint, params=where_dict)

        if response and response.json().get("message") == "success":
            return response.json().get("data", "")
        else:
            logger.error(f"magic_api查询失败: {tab_name}")
            return None

    def magic_api_update(self, data_base, tab_name, where_dict, set_dict):
        """
        magic_api更新 - 优化版本
        """
        endpoint = f"llm_update_tab_field_data/{data_base}/{tab_name}"
        response = self.post(endpoint, params=where_dict, json=set_dict)

        if response and response.json().get("message") == "success":
            return True
        else:
            logger.error(f"magic_api更新失败: {tab_name}")
            return False

    def magic_api_insert(self, data_base, tab_name, set_dict):
        """
        magic_api插入 - 优化版本
        """
        endpoint = f"llm_insert_tab_field_data/{data_base}/{tab_name}"
        response = self.post(endpoint, json=set_dict)

        if response and response.json().get("message") == "success":
            return True
        else:
            logger.error(f"magic_api插入失败: {tab_name}")
            return False


def magic_api(base_url=BASE_URL, endpoint=None, method='get', params=None, json_data=None):
    """
    快速调用API的便捷函数 - 优化版本
    """
    client = RequestClient(base_url)
    return client.call_api(endpoint, method, params=params, json=json_data)


# ========== 优化的测试方法 ==========
def quick_select_test():
    """快速SELECT查询测试"""
    print("开始快速SELECT测试...")

    client = RequestClient()
    database = "chat_bot"
    tab_name = "wxauto_qa"
    sql = f"SELECT * FROM {database}.{tab_name}"
    # result = client.select(sql=sql)

    try:
        # 快速测试：只测试最基本的功能
        print("1. 测试SELECT...")
        result1 = client.select(data_base=database, tab_name=tab_name, where_str="1=1 LIMIT 1")
        print(f"   SELECT结果: {'成功' if result1 and not result1 else '失败'}")

        print("2. 测试SELECT_ONE...")
        result2 = client.selectOne(data_base=database, tab_name=tab_name, where_str="1=1 LIMIT 1")
        print(f"   SELECT_ONE结果: {'成功' if result2 and not result2.get('message') else '失败'}")

        print("快速SELECT测试完成!")
        return True

    except Exception as e:
        print(f"测试发生异常: {e}")
        return False


def quick_update_test():
    """快速UPDATE测试"""
    print("开始快速UPDATE测试...")

    client = RequestClient()
    database = "chat_bot"
    tab_name = "wxauto_qa"

    try:
        # 先查询一条记录
        test_record = client.selectOne(data_base=database, tab_name=tab_name, where_str="1=1 LIMIT 1")
        if not test_record or isinstance(test_record, dict) and test_record.get('message'):
            print("  跳过UPDATE测试: 未找到测试数据")
            return True

        record_id = test_record.get('id') if isinstance(test_record, dict) else test_record[0].get('id')

        if record_id:
            set_dict = {"update_time": "NOW()"}
            result = client.update(database, tab_name, f"id = {record_id}", set_dict)
            print(f"  UPDATE结果: {'成功' if result else '失败'}")
        else:
            print("  跳过UPDATE测试: 未找到有效ID")

        print("快速UPDATE测试完成!")
        return True

    except Exception as e:
        print(f"测试发生异常: {e}")
        return False


def quick_insert_test():
    """快速INSERT测试"""
    print("开始快速INSERT测试...")

    client = RequestClient()
    database = "chat_bot"
    tab_name = "wxauto_qa"

    try:
        # 使用不会冲突的数据进行测试
        import random
        timestamp = int(time.time())
        random_suffix = random.randint(1000, 9999)

        set_str = f"question='测试问题_{timestamp}_{random_suffix}', answer='测试答案_{timestamp}', create_time=NOW()"

        result = client.insert(database, tab_name, set_str)
        print(f"  INSERT结果: {'成功' if result else '失败'}")

        print("快速INSERT测试完成!")
        return True

    except Exception as e:
        print(f"测试发生异常: {e}")
        return False


def run_quick_tests():
    """运行快速测试套件"""
    print("\n" + "=" * 40)
    print("开始快速测试套件")
    print("=" * 40)

    start_time = time.time()

    tests = [
        quick_select_test,
        quick_update_test,
        quick_insert_test
    ]

    passed = 0
    for test in tests:
        if test():
            passed += 1

    end_time = time.time()

    print("\n" + "=" * 40)
    print(f"测试完成! 通过: {passed}/{len(tests)}")
    print(f"总耗时: {end_time - start_time:.2f}秒")
    print("=" * 40)


if __name__ == "__main__":
    # 运行快速测试
    run_quick_tests()