import requests, ast
# from load_dataset import load_doi
import json
import os
from datetime import datetime
from datasets import load_dataset
import pandas as pd

API_KEY = 'app-by3ojQS5XYEFjRgPWjsKsT4t'
API_URL = 'http://localhost/v1/workflows/run'  # 按实际端口和路径填写

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

def load_travel_dataset():
    travel_dataset = []
    file_path = 'templates/dataset/travel/china_departure_travel_input_100.json'
    with open(file_path, 'r', encoding='utf-8') as f:
        travel_dataset = json.load(f)
    return travel_dataset

def load_travel_dataset_2():
    ds = load_dataset("osunlp/TravelPlanner", "validation")  # 不需要第二个参数
    validation_ds = ds['validation']           # 获取 validation split
    travel_dataset = []
    for i in range(len(validation_ds)):
        item = validation_ds[i]
        date_list = ast.literal_eval(item['date'])
        travel_dataset.append({
            'departure_city': item['org'],
            'destination_city': item['dest'],
            'departure_date': date_list[0],
            'budget': '$' + str(item['budget']),
            'traveler_count': item['people_number'],
            'destination_country': 'America',
            'return_date': date_list[-1],
            'query': item['query']
        })
    return travel_dataset

def run_travel():
    travel_dataset = load_travel_dataset_2()
    for i in range(len(travel_dataset)):
        item = travel_dataset[i]
        departure_city = item['departure_city']
        destination_city = item['destination_city']
        depature_date = item['departure_date']
        budget = item['budget']
        traveler_count = item['traveler_count']
        destination_country = item['destination_country']
        return_date = item['return_date']
        query = item['query']
        inputs = {
            "departure_city": departure_city,
            "destination_city": destination_city,
            "departure_date": depature_date,
            "budget": budget,
            "traveler_count": traveler_count,
            "destination_country": destination_country,
            "return_date": return_date
        }

        payload = {
            "inputs": inputs,
            "query": query,
            "response_mode": "blocking",  # 或 "streaming"
            "user": "abc-123",            # 可选，用户ID
            "conversation_id": ""        # 可选，首次对话留空，后续对话填前一次返回的 conversation_id
        }
        try:
            response = requests.post(API_URL, headers=headers, json=payload)

            print(response.text)
            if response.status_code == 200:
                print("运行成功，原始返回内容如下：")
                print(response.text)  # 先打印原始内容
                
                data = json.loads(response.text)
                answer = data['data']['outputs']['result']

                # 确保输出目录存在
                output_dir = 'output/travel_3'
                if not os.path.exists(output_dir):
                    os.makedirs(output_dir)
                    
                # 生成输出文件名
                # timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                output_file = os.path.join(output_dir, f'travel_log_{i}.json')
                result = inputs
                result['id'] = i
                result['answer'] = answer
                # 将结果写入json文件
                with open(output_file, 'w', encoding='utf-8') as f:
                    json.dump(result, f, ensure_ascii=False, indent=2)
                print("运行成功，结果已写入JSON文件：", output_file)
        except Exception as e:
            print(f"运行失败，错误信息：{e}")


run_travel()