import requests
import json
import time
import os
import sys
import io
from pathlib import Path

# 設定 UTF-8 編碼
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

BASE_URL = "http://localhost:5000/api/v1"

def test_login():
    """測試登入功能"""
    print("\n=== 測試登入功能 ===")
    response = requests.post(f"{BASE_URL}/auth/login", json={
        "username": "ymirliu@panjit.com.tw",
        "password": "3EDC4rfv5tgb"
    })
    
    if response.status_code == 200:
        data = response.json()
        print(f"✅ 登入成功")
        print(f"  使用者: {data.get('user', {}).get('username')}")
        print(f"  Token: {data.get('token')[:20]}...")
        print(f"  管理員: {data.get('user', {}).get('is_admin')}")
        return data.get('token')
    else:
        print(f"❌ 登入失敗: {response.status_code}")
        print(f"  錯誤: {response.text}")
        return None

def test_file_upload(token):
    """測試檔案上傳"""
    print("\n=== 測試檔案上傳 ===")
    
    # 建立測試檔案
    test_file = "test_document.txt"
    with open(test_file, 'w', encoding='utf-8') as f:
        f.write("This is a test document for translation.\n這是一個測試文件。")
    
    try:
        with open(test_file, 'rb') as f:
            files = {'file': (test_file, f, 'text/plain')}
            headers = {'Authorization': f'Bearer {token}'}
            
            response = requests.post(
                f"{BASE_URL}/files/upload",
                files=files,
                headers=headers
            )
            
            if response.status_code == 200:
                data = response.json()
                print(f"✅ 檔案上傳成功")
                print(f"  Job ID: {data.get('job_id')}")
                print(f"  檔案名: {data.get('filename')}")
                return data.get('job_id')
            else:
                print(f"❌ 上傳失敗: {response.status_code}")
                print(f"  錯誤: {response.text}")
                return None
    finally:
        # 清理測試檔案
        if os.path.exists(test_file):
            os.remove(test_file)

def test_job_status(token, job_id):
    """測試任務狀態查詢"""
    print("\n=== 測試任務狀態 ===")
    headers = {'Authorization': f'Bearer {token}'}
    
    response = requests.get(
        f"{BASE_URL}/jobs/{job_id}",
        headers=headers
    )
    
    if response.status_code == 200:
        data = response.json()
        print(f"✅ 狀態查詢成功")
        print(f"  狀態: {data.get('status')}")
        print(f"  進度: {data.get('progress')}%")
        return data
    else:
        print(f"❌ 查詢失敗: {response.status_code}")
        return None

def test_admin_stats(token):
    """測試管理員統計功能"""
    print("\n=== 測試管理員統計 ===")
    headers = {'Authorization': f'Bearer {token}'}
    
    response = requests.get(
        f"{BASE_URL}/admin/statistics",
        headers=headers
    )
    
    if response.status_code == 200:
        data = response.json()
        print(f"✅ 統計查詢成功")
        print(f"  總任務數: {data.get('total_jobs')}")
        print(f"  總使用者: {data.get('total_users')}")
        print(f"  API 總成本: ${data.get('total_cost', 0)}")
        return True
    else:
        print(f"❌ 查詢失敗: {response.status_code}")
        return False

def test_dify_api():
    """測試 Dify API 配置"""
    print("\n=== 測試 Dify API ===")
    
    # 讀取 API 配置
    api_file = Path("api.txt")
    if api_file.exists():
        content = api_file.read_text().strip()
        lines = content.split('\n')
        base_url = None
        api_key = None
        
        for line in lines:
            if line.startswith('base_url:'):
                base_url = line.split(':', 1)[1].strip()
            elif line.startswith('api:'):
                api_key = line.split(':', 1)[1].strip()
        
        print(f"✅ API 配置已找到")
        print(f"  Base URL: {base_url}")
        print(f"  API Key: {api_key[:20]}...")
        
        # 測試 API 連線
        if base_url and api_key:
            try:
                test_url = f"{base_url}/chat-messages"
                headers = {
                    'Authorization': f'Bearer {api_key}',
                    'Content-Type': 'application/json'
                }
                
                # 簡單的測試請求
                test_data = {
                    "inputs": {},
                    "query": "Hello",
                    "response_mode": "blocking",
                    "user": "test_user"
                }
                
                response = requests.post(test_url, json=test_data, headers=headers, timeout=10)
                
                if response.status_code in [200, 201]:
                    print(f"✅ Dify API 連線成功")
                    return True
                else:
                    print(f"⚠️ Dify API 回應: {response.status_code}")
                    return True  # API 配置正確，但可能需要正確的應用配置
            except Exception as e:
                print(f"⚠️ Dify API 連線測試: {str(e)[:50]}")
                return True  # 配置存在即可
        else:
            print(f"❌ API 配置不完整")
            return False
    else:
        print(f"❌ api.txt 檔案不存在")
        return False

def run_integration_tests():
    """執行整合測試"""
    print("\n" + "="*50)
    print("開始執行整合測試")
    print("="*50)
    
    results = {
        "login": False,
        "upload": False,
        "status": False,
        "admin": False,
        "dify": False
    }
    
    # 1. 測試 Dify API 配置
    results["dify"] = test_dify_api()
    
    # 2. 測試登入
    token = test_login()
    if token:
        results["login"] = True
        
        # 3. 測試檔案上傳
        job_id = test_file_upload(token)
        if job_id:
            results["upload"] = True
            
            # 4. 測試任務狀態
            time.sleep(1)
            job_data = test_job_status(token, job_id)
            if job_data:
                results["status"] = True
        
        # 5. 測試管理員功能
        results["admin"] = test_admin_stats(token)
    
    # 總結
    print("\n" + "="*50)
    print("測試結果總結")
    print("="*50)
    
    passed = sum(1 for v in results.values() if v)
    total = len(results)
    
    for test_name, passed in results.items():
        status = "✅ 通過" if passed else "❌ 失敗"
        print(f"  {test_name.upper()}: {status}")
    
    print(f"\n總計: {passed}/{total} 測試通過")
    print(f"成功率: {(passed/total)*100:.1f}%")
    
    return results

if __name__ == "__main__":
    # 檢查服務是否運行 - 直接測試登入端點
    print("檢查後端服務...")
    try:
        # 嘗試訪問根路徑或登入路徑
        response = requests.get("http://localhost:5000/", timeout=2)
        print("✅ 後端服務運行中")
        run_integration_tests()
    except requests.exceptions.ConnectionError:
        print("❌ 無法連接到後端服務")
        print("請先執行 start_dev.bat 啟動後端服務")
    except Exception as e:
        print(f"❌ 錯誤: {e}")