#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
測試 Dify 客戶端是否正常工作
"""

import sys
import os

# Fix encoding for Windows console
if sys.stdout.encoding != 'utf-8':
    sys.stdout.reconfigure(encoding='utf-8')
if sys.stderr.encoding != 'utf-8':
    sys.stderr.reconfigure(encoding='utf-8')

sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'app'))

from app import create_app
from app.services.dify_client import DifyClient

def test_dify_client():
    """測試 Dify 客戶端"""
    
    app = create_app()
    
    with app.app_context():
        print("=== 測試 Dify 客戶端 ===")
        
        try:
            # 創建 Dify 客戶端
            dify_client = DifyClient()
            print(f"Dify 客戶端已創建")
            print(f"Base URL: {dify_client.base_url}")
            print(f"API Key: {dify_client.api_key[:10]}...{dify_client.api_key[-4:]}")
            
            # 測試簡單翻譯
            test_text = "保证烤箱设备之稳定性及延长其使用寿命"
            print(f"\n測試翻譯文本: {test_text}")
            
            result = dify_client.translate_text(
                text=test_text,
                source_language='auto',
                target_language='en',
                user_id=1,  # 使用重置後的用戶ID
                job_id=None  # 暫時不使用job_id以避免外鍵問題
            )
            
            print(f"翻譯結果: {result}")
            
            if result and 'translated_text' in result:
                print(f"翻譯成功: {result['translated_text']}")
                print(f"Token 使用: {result.get('total_tokens', 'N/A')}")
                print(f"成本: ${result.get('total_cost', 'N/A')}")
            else:
                print("❌ 翻譯結果格式不正確")
        
        except Exception as e:
            print(f"❌ Dify 客戶端測試失敗: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    test_dify_client()