"""
测试元数据过滤逻辑（不依赖向量检索）
"""
import json


def apply_metadata_filter(hits, metadata_filter):
    """应用元数据过滤条件"""
    filtered = []
    for hit in hits:
        payload = hit.get("payload", {})
        hit_metadata = payload.get("metadata", {})
        
        match = True
        for field_key, condition in metadata_filter.items():
            hit_value = hit_metadata.get(field_key)
            
            if isinstance(condition, dict):
                if "$eq" in condition:
                    if hit_value != condition["$eq"]:
                        match = False
                        break
                elif "$in" in condition:
                    if hit_value not in condition["$in"]:
                        match = False
                        break
            else:
                if hit_value != condition:
                    match = False
                    break
        
        if match:
            filtered.append(hit)
    
    return filtered


# 模拟 Qdrant 返回的 hits（带 metadata）
test_hits = [
    {
        "id": "1",
        "score": 0.85,
        "payload": {
            "text": "初二数学学习困难：几何证明题难以理解",
            "metadata": {
                "grade": "初二",
                "subject": "数学",
                "kb_scene": "痛点"
            }
        }
    },
    {
        "id": "2",
        "score": 0.82,
        "payload": {
            "text": "初二英语学习：词汇量不足导致阅读理解困难",
            "metadata": {
                "grade": "初二",
                "subject": "英语",
                "kb_scene": "痛点"
            }
        }
    },
    {
        "id": "3",
        "score": 0.78,
        "payload": {
            "text": "初一数学基础：有理数运算不熟练",
            "metadata": {
                "grade": "初一",
                "subject": "数学",
                "kb_scene": "痛点"
            }
        }
    },
    {
        "id": "4",
        "score": 0.75,
        "payload": {
            "text": "初二数学学习方案：建立错题本",
            "metadata": {
                "grade": "初二",
                "subject": "数学",
                "kb_scene": "学习方案"
            }
        }
    },
]


print("=" * 60)
print("元数据过滤逻辑测试")
print("=" * 60)
print(f"\n测试数据: {len(test_hits)} 条文档")
for hit in test_hits:
    meta = hit["payload"]["metadata"]
    print(f"  [{hit['id']}] {meta['grade']} {meta['subject']} {meta['kb_scene']}: {hit['payload']['text'][:30]}...")


# 测试1: 过滤初二数学痛点
print("\n" + "=" * 60)
print("测试1: 过滤 '初二数学痛点'")
print("=" * 60)
filter1 = {
    "grade": {"$eq": "初二"},
    "subject": {"$eq": "数学"},
    "kb_scene": {"$eq": "痛点"}
}
print(f"过滤器: {json.dumps(filter1, ensure_ascii=False)}")
result1 = apply_metadata_filter(test_hits, filter1)
print(f"结果: {len(result1)} 条命中")
for hit in result1:
    print(f"  - {hit['payload']['text']}")


# 测试2: 过滤所有初二文档
print("\n" + "=" * 60)
print("测试2: 过滤 '初二' (所有学科)")
print("=" * 60)
filter2 = {
    "grade": {"$eq": "初二"}
}
print(f"过滤器: {json.dumps(filter2, ensure_ascii=False)}")
result2 = apply_metadata_filter(test_hits, filter2)
print(f"结果: {len(result2)} 条命中")
for hit in result2:
    meta = hit["payload"]["metadata"]
    print(f"  - [{meta['subject']}] {hit['payload']['text'][:40]}...")


# 测试3: 过滤所有痛点
print("\n" + "=" * 60)
print("测试3: 过滤 '痛点' (所有年级学科)")
print("=" * 60)
filter3 = {
    "kb_scene": {"$eq": "痛点"}
}
print(f"过滤器: {json.dumps(filter3, ensure_ascii=False)}")
result3 = apply_metadata_filter(test_hits, filter3)
print(f"结果: {len(result3)} 条命中")
for hit in result3:
    meta = hit["payload"]["metadata"]
    print(f"  - [{meta['grade']} {meta['subject']}] {hit['payload']['text'][:40]}...")


# 测试4: 空过滤器（不过滤）
print("\n" + "=" * 60)
print("测试4: 空过滤器（返回所有）")
print("=" * 60)
filter4 = {}
print(f"过滤器: {json.dumps(filter4, ensure_ascii=False)}")
result4 = apply_metadata_filter(test_hits, filter4)
print(f"结果: {len(result4)} 条命中")


# 测试5: 严格过滤（无匹配）
print("\n" + "=" * 60)
print("测试5: 严格过滤 '初三物理痛点'（无匹配）")
print("=" * 60)
filter5 = {
    "grade": {"$eq": "初三"},
    "subject": {"$eq": "物理"},
    "kb_scene": {"$eq": "痛点"}
}
print(f"过滤器: {json.dumps(filter5, ensure_ascii=False)}")
result5 = apply_metadata_filter(test_hits, filter5)
print(f"结果: {len(result5)} 条命中")


print("\n" + "=" * 60)
print("测试完成！元数据过滤逻辑工作正常。")
print("=" * 60)
