#!/usr/bin/env python3
"""
最終人臉識別系統驗證
測試所有核心功能
"""

import sys
import os
import subprocess
import time


def run_test(script_name, description):
    """運行測試腳本並返回結果"""
    print(f"\n{description}")
    print("-" * 40)

    try:
        result = subprocess.run(
            ["python3", script_name],
            capture_output=True,
            text=True,
            cwd="/Users/accusys/momentry_core_0.1",
        )

        if result.returncode == 0:
            print("✅ 測試通過")
            # 提取關鍵信息
            for line in result.stdout.split("\n"):
                if any(keyword in line for keyword in ["✅", "檢測到", "成功", "通過"]):
                    print(f"  {line.strip()}")
            return True
        else:
            print("❌ 測試失敗")
            print(f"錯誤輸出:\n{result.stderr[:500]}")  # 限制輸出長度
            return False

    except Exception as e:
        print(f"❌ 測試異常: {e}")
        return False


def check_server_status():
    """檢查服務器狀態"""
    print("\n檢查服務器狀態")
    print("-" * 40)

    try:
        import requests

        response = requests.get("http://localhost:3002/health", timeout=5)
        if response.status_code == 200:
            print(f"✅ 生產服務器運行正常 (端口 3002)")
            return True
        else:
            print(f"❌ 生產服務器異常: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 無法連接到生產服務器: {e}")

    try:
        import requests

        response = requests.get("http://localhost:3003/health", timeout=5)
        if response.status_code == 200:
            print(f"✅ 開發服務器運行正常 (端口 3003)")
            return True
        else:
            print(f"❌ 開發服務器異常: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 無法連接到開發服務器: {e}")
        return False


def check_database():
    """檢查數據庫連接"""
    print("\n檢查數據庫連接")
    print("-" * 40)

    try:
        import psycopg2

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

        # 檢查人臉相關表
        cursor.execute("""
            SELECT table_name 
            FROM information_schema.tables 
            WHERE table_schema = 'public' 
            AND table_name LIKE 'face_%'
            ORDER BY table_name
        """)

        tables = cursor.fetchall()
        print(f"✅ 數據庫連接正常")
        print(f"✅ 找到 {len(tables)} 個人臉相關表:")
        for table in tables:
            print(f"  - {table[0]}")

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

    except Exception as e:
        print(f"❌ 數據庫連接失敗: {e}")
        return False


def check_python_dependencies():
    """檢查 Python 依賴"""
    print("\n檢查 Python 依賴")
    print("-" * 40)

    dependencies = [
        "insightface",
        "onnxruntime",
        "psycopg2",
        "numpy",
        "opencv-python",
        "requests",
    ]

    all_ok = True
    for dep in dependencies:
        try:
            __import__(dep.replace("-", "_"))
            print(f"✅ {dep}")
        except ImportError:
            print(f"❌ {dep} (未安裝)")
            all_ok = False

    return all_ok


def main():
    """主驗證函數"""
    print("=" * 60)
    print("人臉識別系統最終驗證")
    print("=" * 60)

    # 基本檢查
    basic_checks = [
        ("服務器狀態", check_server_status),
        ("數據庫連接", check_database),
        ("Python 依賴", check_python_dependencies),
    ]

    # 功能測試
    functional_tests = [
        ("scripts/test_with_real_image.py", "人臉檢測功能測試"),
        ("scripts/test_face_direct.py", "直接人臉識別測試"),
        ("scripts/test_end_to_end.py", "端到端系統測試"),
        ("scripts/test_face_api.py", "API 接口測試"),
    ]

    print("\n基本系統檢查:")
    print("=" * 40)

    basic_results = []
    for check_name, check_func in basic_checks:
        success = check_func()
        basic_results.append((check_name, success))

    print("\n功能測試:")
    print("=" * 40)

    functional_results = []
    for script_path, description in functional_tests:
        full_path = os.path.join("/Users/accusys/momentry_core_0.1", script_path)
        if os.path.exists(full_path):
            success = run_test(script_path, description)
            functional_results.append((description, success))
        else:
            print(f"\n{description}")
            print("-" * 40)
            print(f"❌ 測試腳本不存在: {script_path}")
            functional_results.append((description, False))

    # 顯示結果摘要
    print("\n" + "=" * 60)
    print("驗證結果摘要")
    print("=" * 60)

    print("\n基本系統檢查:")
    basic_passed = sum(1 for _, success in basic_results if success)
    for check_name, success in basic_results:
        status = "✅ 通過" if success else "❌ 失敗"
        print(f"  {check_name}: {status}")

    print(f"\n  ✅ {basic_passed}/{len(basic_results)} 個基本檢查通過")

    print("\n功能測試:")
    functional_passed = sum(1 for _, success in functional_results if success)
    for test_name, success in functional_results:
        status = "✅ 通過" if success else "❌ 失敗"
        print(f"  {test_name}: {status}")

    print(f"\n  ✅ {functional_passed}/{len(functional_tests)} 個功能測試通過")

    total_passed = basic_passed + functional_passed
    total_tests = len(basic_results) + len(functional_tests)

    print(f"\n總計: {total_passed}/{total_tests} 個測試通過")

    if total_passed == total_tests:
        print("\n🎉 所有測試通過！人臉識別系統完全可用。")
        print("\n系統功能驗證完成:")
        print("  ✅ 人臉檢測和特徵提取")
        print("  ✅ 數據庫存儲和查詢")
        print("  ✅ 向量相似度搜索")
        print("  ✅ 系統集成完整性")
        print("  ✅ API 接口功能")
        print("  ✅ MPS 加速支援")

        print("\n下一步操作:")
        print("  1. 使用真實視頻進行人臉識別測試")
        print("  2. 部署到生產環境")
        print("  3. 配置監控和警報")
        print("  4. 性能優化和測試")

        return True
    else:
        print(f"\n⚠️  有 {total_tests - total_passed} 個測試失敗")
        print("\n建議:")
        print("  1. 檢查失敗的測試詳細信息")
        print("  2. 確保所有依賴已正確安裝")
        print("  3. 驗證數據庫連接和表結構")
        print("  4. 檢查服務器日誌獲取更多信息")

        return False


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
