import requests
import json

# ====== 配置区 ======
API_KEY = "app-BDMvpOVNv9nvceXTuwGI1FqD"  # Dify 应用API Key
WORKFLOW_RUN_URL = "http://localhost/v1/workflows/run"  # workflow运行接口
# FILE_UPLOAD_URL = "http://localhost/v1/files/upload"    # 文件上传接口
# LOCAL_FILE_PATH = "/Users/maxuyan/Documents/paper/LLM/AgentVerse.pdf"  # 本地文件路径
LOCAL_FILE_PATH = "paper_sharing.txt"
VARIABLE_NAME = "file"  # workflow中定义的变量名，需与Dify流程设计一致
USER_ID = "test-user-001"
# ====================

headers = {
    "Authorization": f"Bearer {API_KEY}"
}


def upload_file(file_path, user):
    upload_url = "http://localhost/v1/files/upload"
    try:
        print("上传文件中...")
        with open(file_path, 'rb') as file:
            files = {
                'file': (file_path, file, 'text/plain')  # 确保文件以适当的MIME类型上传
            }
            print(files)
            data = {
                "user": user,
                "type": "TXT"  # 设置文件类型为TXT
            }
            
            response = requests.post(upload_url, headers=headers, files=files)
            if response.status_code == 201:  # 201 表示创建成功
                print("文件上传成功")
                return response.json().get("id")  # 获取上传的文件 ID
            else:
                print(f"文件上传失败，状态码: {response.text}")
                return None
    except Exception as e:
        print(f"发生错误: {str(e)}")
        return None



# # 1. 上传本地文件，获取 upload_file_id
# with open(LOCAL_FILE_PATH, "rb") as f:
#     files = {"file": f}
#     upload_resp = requests.post(FILE_UPLOAD_URL, headers=headers, files=files)

# if upload_resp.status_code != 200:
#     print("❌ 文件上传失败:", upload_resp.status_code, upload_resp.text)
#     exit(1)

file_id = upload_file(LOCAL_FILE_PATH, USER_ID)
print("✅ 文件上传成功，file_id:", file_id)


def run_workflow(file_id, user, response_mode="blocking"):
    workflow_url = WORKFLOW_RUN_URL
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    data = {
        "inputs": {
            "document": {
                "transfer_method": "local_file",
                "upload_file_id": file_id,
                "type": "TXT"
            }
        },
        "response_mode": response_mode,
        "user": user
    }

    try:
        print("运行工作流...")
        response = requests.post(workflow_url, headers=headers, json=data)
        print(data)
        if response.status_code == 200:
            print("工作流执行成功")
            return response.json()
        else:
            print(f"工作流执行失败，状态码: {response.status_code}")
            return {"status": "error", "message": f"Failed to execute workflow, status code: {response.status_code}"}
    except Exception as e:
        print(f"发生错误: {str(e)}")
        return {"status": "error", "message": str(e)}

if file_id:
    # 文件上传成功，继续运行工作流
    result = run_workflow(file_id, USER_ID)
    print(result)
else:
    print("文件上传失败，无法执行工作流")





# # 2. 构造 workflow 调用 payload（严格按API文档格式）
# payload = {
#     "inputs": {
#         VARIABLE_NAME: [
#             {
#                 "transfer_method": "local_file",
#                 "upload_file_id": upload_file_id,
#                 "type": "document"
#             }
#         ]
#     },
#     "response_mode": "blocking",
#     "user": USER_ID
# }

# headers_with_json = headers.copy()
# headers_with_json["Content-Type"] = "application/json"

# # 3. 调用 workflow
# run_resp = requests.post(WORKFLOW_RUN_URL, headers=headers_with_json, json=payload)

# if run_resp.status_code != 200:
#     print("❌ 工作流调用失败:", run_resp.status_code, run_resp.text)
# else:
#     try:
#         result = run_resp.json()
#         print("🎯 工作流输出结果:")
#         print(json.dumps(result, indent=2, ensure_ascii=False))
#     except Exception as e:
#         print("⚠️ 无法解析结果:", e)
#         print("原始响应：", run_resp.text)
