"""
直接测试 Qdrant 过滤功能
"""

import asyncio
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from qdrant_client.models import FieldCondition, Filter, MatchValue

from app.core.config import get_settings
from app.core.qdrant_client import QdrantClient


async def test_qdrant_filter():
    """直接测试 Qdrant 过滤功能"""
    settings = get_settings()
    client = QdrantClient()
    qdrant = await client.get_client()
    
    tenant_id = "szmp@ash@2026"
    kb_id = "75c465fe-277d-455d-a30b-4b168adcc03b"
    
    collection_name = client.get_kb_collection_name(tenant_id, kb_id)
    
    print(f"\n{'='*80}")
    print(f"测试 Qdrant 过滤功能")
    print(f"{'='*80}")
    print(f"Collection: {collection_name}")
    
    # 测试 1: 无过滤
    print(f"\n--- 测试 1: 无过滤 ---")
    results = await qdrant.scroll(
        collection_name=collection_name,
        limit=5,
        with_vectors=False,
    )
    print(f"无过滤结果数: {len(results[0])}")
    for p in results[0][:3]:
        print(f"  grade: {p.payload.get('metadata', {}).get('grade')}")
    
    # 测试 2: 使用 Filter 对象过滤
    print(f"\n--- 测试 2: 使用 Filter 对象过滤 (grade=五年级) ---")
    qdrant_filter = Filter(
        must=[
            FieldCondition(
                key="metadata.grade",
                match=MatchValue(value="五年级"),
            )
        ]
    )
    print(f"Filter: {qdrant_filter}")
    
    results = await qdrant.scroll(
        collection_name=collection_name,
        limit=10,
        with_vectors=False,
        scroll_filter=qdrant_filter,
    )
    print(f"过滤后结果数: {len(results[0])}")
    for p in results[0]:
        print(f"  grade: {p.payload.get('metadata', {}).get('grade')}, text: {p.payload.get('text', '')[:50]}...")
    
    # 测试 3: 使用 query_points 过滤
    print(f"\n--- 测试 3: 使用 query_points 过滤 ---")
    # 先获取一个向量用于测试
    all_points = await qdrant.scroll(
        collection_name=collection_name,
        limit=1,
        with_vectors=True,
    )
    if all_points[0]:
        query_vector = all_points[0][0].vector
        
        results = await qdrant.query_points(
            collection_name=collection_name,
            query=query_vector,
            limit=10,
            query_filter=qdrant_filter,
        )
        print(f"query_points 过滤后结果数: {len(results.points)}")
        for p in results.points:
            print(f"  grade: {p.payload.get('metadata', {}).get('grade')}, score: {p.score:.4f}")


if __name__ == "__main__":
    asyncio.run(test_qdrant_filter())
