#!/usr/bin/env python3
"""
測試數據庫修復後的視頻人臉分析
"""

import sys
import os
import json
import psycopg2
from datetime import datetime

# 添加項目根目錄到路徑
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 數據庫連接配置
DB_CONFIG = {
    "host": "localhost",
    "port": 5432,
    "database": "momentry",
    "user": "accusys",
    "password": "accusys",
}


def test_database_connection():
    """測試數據庫連接"""
    try:
        conn = psycopg2.connect(**DB_CONFIG)
        cursor = conn.cursor()

        # 檢查表是否存在
        cursor.execute("""
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_name = 'face_detections'
            )
        """)
        table_exists = cursor.fetchone()[0]

        if not table_exists:
            print("❌ face_detections 表不存在")
            return False

        # 檢查列結構
        cursor.execute("""
            SELECT column_name, data_type, is_nullable 
            FROM information_schema.columns 
            WHERE table_name = 'face_detections' 
            ORDER BY ordinal_position
        """)

        columns = cursor.fetchall()
        print("✅ face_detections 表結構:")
        for col in columns:
            print(
                f"  - {col[0]}: {col[1]} ({'NULL' if col[2] == 'YES' else 'NOT NULL'})"
            )

        # 檢查是否有 frame_number 列
        column_names = [col[0] for col in columns]
        if "frame_number" not in column_names:
            print("❌ 缺少 frame_number 列")
            return False

        if "timestamp_secs" not in column_names:
            print("❌ 缺少 timestamp_secs 列")
            return False

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

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


def test_insert_detection():
    """測試插入人臉檢測記錄"""
    try:
        conn = psycopg2.connect(**DB_CONFIG)
        cursor = conn.cursor()

        # 創建測試數據
        test_detection = {
            "video_uuid": "test_uuid_123",
            "frame_idx": 100,
            "timestamp": 5.0,
            "x": 100,
            "y": 150,
            "width": 50,
            "height": 60,
            "confidence": 0.95,
            "embedding": [0.1] * 512,  # 512維嵌入向量
            "attributes": {"age": 30, "gender": "male"},
            "detected_at": datetime.now(),
        }

        # 插入測試記錄
        cursor.execute(
            """
            INSERT INTO face_detections (
                video_uuid, frame_number, timestamp_secs,
                x, y, width, height, confidence,
                embedding, attributes, created_at
            ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            RETURNING id
        """,
            (
                test_detection["video_uuid"],
                test_detection["frame_idx"],
                test_detection["timestamp"],
                test_detection["x"],
                test_detection["y"],
                test_detection["width"],
                test_detection["height"],
                test_detection["confidence"],
                json.dumps(test_detection["embedding"]),
                json.dumps(test_detection["attributes"]),
                test_detection["detected_at"],
            ),
        )

        record_id = cursor.fetchone()[0]
        conn.commit()

        print(f"✅ 成功插入測試記錄，ID: {record_id}")

        # 驗證記錄
        cursor.execute(
            "SELECT COUNT(*) FROM face_detections WHERE id = %s", (record_id,)
        )
        count = cursor.fetchone()[0]

        if count == 1:
            print("✅ 記錄驗證成功")
        else:
            print("❌ 記錄驗證失敗")

        # 清理測試數據
        cursor.execute("DELETE FROM face_detections WHERE id = %s", (record_id,))
        conn.commit()

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

    except Exception as e:
        print(f"❌ 插入測試記錄失敗: {e}")
        return False


def main():
    print("=" * 60)
    print("測試數據庫修復")
    print("=" * 60)

    # 測試數據庫連接
    print("\n1. 測試數據庫連接...")
    if not test_database_connection():
        print("❌ 數據庫連接測試失敗")
        return

    # 測試插入功能
    print("\n2. 測試插入人臉檢測記錄...")
    if not test_insert_detection():
        print("❌ 插入測試失敗")
        return

    print("\n" + "=" * 60)
    print("✅ 所有測試通過！數據庫修復成功")
    print("=" * 60)


if __name__ == "__main__":
    main()
