import os
import json
import httpx
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

DIFY_LOG_APP_API_KEY = os.getenv("DIFY_LOG_APP_API_KEY")
DIFY_REPORT_APP_API_KEY = os.getenv("DIFY_REPORT_APP_API_KEY")

TARGET_URL = "http://192.168.1.88/v1/completion-messages"

def test_dify_endpoint(api_key: str, app_name: str, payload: dict):
    if not api_key:
        print(f"[{app_name}] Error: API Key not found in .env file.")
        return

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    print(f"\n--- Testing App: {app_name} ---")
    print(f"[{app_name}] Request Payload: {json.dumps(payload, ensure_ascii=False)}")
    
    with httpx.Client(timeout=30.0) as client:
        # 这里严禁 try-except 包含网络响应错误（只让它如果是网络断开直接崩就行），但能抓取到 400 等状态码
        response = client.post(TARGET_URL, headers=headers, json=payload)
        
        print(f"[{app_name}] HTTP Status Code: {response.status_code}")
        print(f"[{app_name}] Raw Response Body: {response.text}")

if __name__ == "__main__":
    # 测试用例 1: 日志分析应用
    log_payload = {
        "inputs": {"log_content": "今天拜访了张总，他对价格很敏感。"},
        "response_mode": "blocking",
        "user": "debug_script"
    }
    test_dify_endpoint(DIFY_LOG_APP_API_KEY, "Log Analysis App", log_payload)

    # 测试用例 2: 月度报告应用
    report_payload = {
        "inputs": {"metrics_data": "测试指标数据", "report_period": "2026年02月"},
        "response_mode": "blocking",
        "user": "debug_script"
    }
    test_dify_endpoint(DIFY_REPORT_APP_API_KEY, "Monthly Report App", report_payload)
