#!/usr/bin/env python3
"""
最終人臉識別 API 測試
"""

import requests
import json
import sys

# API 配置
BASE_URL = "http://localhost:3002"
API_KEY = "muser_7ff810b88d6440c6ab31094ecae7dc32_1774870448_54b7c8e9"


def test_health():
    """測試健康檢查端點"""
    try:
        response = requests.get(f"{BASE_URL}/health", timeout=5)
        if response.status_code == 200:
            data = response.json()
            print(f"✅ 健康檢查通過: {data}")
            return True
        else:
            print(f"❌ 健康檢查失敗: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 健康檢查錯誤: {e}")
        return False


def test_api_key():
    """測試 API 密鑰認證"""
    try:
        headers = {"Authorization": f"Bearer {API_KEY}"}
        response = requests.get(
            f"{BASE_URL}/api/v1/face/list", headers=headers, timeout=5
        )

        if response.status_code == 200:
            print("✅ API 密鑰認證成功")
            return True
        elif response.status_code == 401:
            print("❌ API 密鑰認證失敗 (401 Unauthorized)")
            print(f"  使用的密鑰: {API_KEY[:20]}...")
            return False
        elif response.status_code == 404:
            print("⚠️  API 端點未找到 (404)")
            print("   可能原因: 1) 路由未註冊 2) 服務器未重新編譯")
            return False
        else:
            print(f"❌ API 請求失敗: {response.status_code}")
            print(f"  響應: {response.text[:100]}")
            return False
    except Exception as e:
        print(f"❌ API 測試錯誤: {e}")
        return False


def test_database_data():
    """測試數據庫中的數據"""
    import psycopg2

    try:
        conn = psycopg2.connect(
            host="localhost",
            port=5432,
            database="momentry",
            user="accusys",
            password="accusys",
        )
        cursor = conn.cursor()

        # 檢查人臉檢測記錄
        cursor.execute("SELECT COUNT(*) FROM face_detections")
        count = cursor.fetchone()[0]
        print(f"✅ 數據庫中有 {count} 個人臉檢測記錄")

        # 檢查視頻信息
        cursor.execute("""
            SELECT video_uuid, COUNT(*) as detections, 
                   MIN(timestamp_secs), MAX(timestamp_secs)
            FROM face_detections 
            GROUP BY video_uuid
        """)
        videos = cursor.fetchall()

        for video in videos:
            print(f"  視頻 UUID: {video[0]}")
            print(f"    檢測數: {video[1]}")
            print(f"    時間範圍: {video[2]:.1f}s - {video[3]:.1f}s")

        cursor.close()
        conn.close()
        return True

    except Exception as e:
        print(f"❌ 數據庫檢查錯誤: {e}")
        return False


def main():
    print("=" * 60)
    print("最終人臉識別系統測試")
    print("=" * 60)

    tests_passed = 0
    total_tests = 3

    # 測試 1: 健康檢查
    print("\n1. 測試服務器健康檢查...")
    if test_health():
        tests_passed += 1

    # 測試 2: API 密鑰認證
    print("\n2. 測試 API 密鑰認證...")
    if test_api_key():
        tests_passed += 1

    # 測試 3: 數據庫數據
    print("\n3. 測試數據庫數據...")
    if test_database_data():
        tests_passed += 1

    print("\n" + "=" * 60)
    print(f"測試結果: {tests_passed}/{total_tests} 通過")

    if tests_passed == total_tests:
        print("✅ 所有測試通過！人臉識別系統正常運行")
    else:
        print("⚠️  部分測試失敗，需要進一步檢查")

        if tests_passed < 2:
            print("\n建議的下一步:")
            print("1. 檢查 API 密鑰是否正確")
            print("2. 重新編譯並重啟 Momentry 服務器")
            print("3. 檢查服務器日誌中的錯誤信息")

    print("=" * 60)


if __name__ == "__main__":
    main()
