import requests
import pandas as pd
import os,json

def get_QA_data():

    # 定义CSV文件路径
    json_path = 'templates/dataset/QA/workflow_test_inputs.json'
    
    # 检查文件是否存在
    if not os.path.exists(json_path):
        print(f"文件 {json_path} 不存在")
        return []
    
    try:
        QA_data = json.load(open(json_path,'r',encoding='utf-8'))
        
        return QA_data
        
    except Exception as e:
        print(f"读取CSV文件时出错: {str(e)}")
        return []
API_KEY = 'app-EIvjQOzaG35FRhb6RayiChWL'
API_URL = 'http://localhost/v1/chat-messages'  # 云端请替换为实际地址

headers = {
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json'
}


def run_QA():
    QA_data = get_QA_data()
    print(f"样本数量: {len(QA_data)}")
    for i in range(0,len(QA_data)):
        item = QA_data[i]
        print(f"\n样本 {i+1}:")
        print(f"user_query: {item}")
        print("-" * 50)

        inputs = {
        }

        query = item

        payload = {
            "inputs": inputs,
            "query": query,
            "response_mode": "blocking",  # 或 "streaming"            
            "user": "abc-123",            # 可选，用户ID
            "conversation_id": ""        # 可选，首次对话留空，后续对话填前一次返回的 conversation_id
        }

        response = requests.post(API_URL, headers=headers, json=payload)
        print(response.text)

        if response.status_code == 200:
            # 确保输出目录存在
            output_dir = 'output/QA'
            if not os.path.exists(output_dir):
                os.makedirs(output_dir)
            
            answer = json.loads(response.text)['answer']
            # 将结果写入json文件
            result = {
                "user_query": item,
                "answer": answer
            }
            
            # 修改文件扩展名为.json
            output_file = os.path.join(output_dir, f'QA_log_{i}.json')
            
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(result, f, ensure_ascii=False, indent=2)
            print("运行成功，结果已写入JSON文件：", output_file)

run_QA()