#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
测试脚本：验证 Phase 2 评分体系归一化

测试项：
1. 精确匹配 vs 包含匹配 - 精确匹配应排序更高
2. 动作类型适配 - click优先匹配BUTTON，fill优先匹配INPUT
"""

import sys
import os
import io

# 设置标准输出编码为UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.services.keyword_matcher import (
    _calculate_match_score,
    _apply_action_type_adjustment,
    EXACT_MATCH_SCORE,
    CONTAINS_MATCH_SCORE,
)


def test_match_score():
    """测试匹配分数计算"""
    print("=" * 60)
    print("测试匹配分数计算")
    print("=" * 60)

    test_cases = [
        # (关键词, 目标文本, 期望精确匹配)
        ("确定", "确定", True),
        ("确定", "确定按钮", False),
        ("新建", "新建会议", False),
        ("新建会议", "新建会议", True),
        ("admin", "admin@xty", False),
        ("admin@xty", "admin@xty", True),
    ]

    passed = 0
    failed = 0

    for keyword, target, expect_exact in test_cases:
        score = _calculate_match_score(keyword, target)
        is_exact = (score == EXACT_MATCH_SCORE)

        if is_exact == expect_exact:
            match_type = "精确" if is_exact else "包含"
            print(f"[PASS] '{keyword}' vs '{target}' -> {match_type}匹配 (score={score:.2f})")
            passed += 1
        else:
            print(f"[FAIL] '{keyword}' vs '{target}'")
            print(f"   期望: {'精确' if expect_exact else '包含'}匹配")
            print(f"   实际: score={score:.2f}")
            failed += 1

    print()
    print(f"结果: 通过 {passed}/{passed + failed}")
    return failed == 0


def test_action_type_adjustment():
    """测试动作类型适配"""
    print()
    print("=" * 60)
    print("测试动作类型适配")
    print("=" * 60)

    test_cases = [
        # (原分数, 标签, 动作, 期望结果描述)
        (0.5, "BUTTON", "click", "应该加分"),
        (0.5, "INPUT", "click", "应该减分"),
        (0.5, "INPUT", "fill", "应该加分"),
        (0.5, "BUTTON", "fill", "应该减分"),
        (0.5, "SELECT", "select", "应该加分"),
    ]

    passed = 0
    failed = 0

    for base_score, tag, action, expect_desc in test_cases:
        adjusted = _apply_action_type_adjustment(base_score, tag, action, [])

        if expect_desc == "应该加分" and adjusted > base_score:
            print(f"[PASS] {tag}+{action}: {base_score:.2f} -> {adjusted:.2f} ({expect_desc})")
            passed += 1
        elif expect_desc == "应该减分" and adjusted < base_score:
            print(f"[PASS] {tag}+{action}: {base_score:.2f} -> {adjusted:.2f} ({expect_desc})")
            passed += 1
        else:
            print(f"[FAIL] {tag}+{action}: {base_score:.2f} -> {adjusted:.2f} ({expect_desc})")
            failed += 1

    print()
    print(f"结果: 通过 {passed}/{passed + failed}")
    return failed == 0


def test_exact_vs_contains_ranking():
    """测试精确匹配排名高于包含匹配"""
    print()
    print("=" * 60)
    print("测试精确匹配排名高于包含匹配")
    print("=" * 60)

    # 模拟场景：关键词"确定"
    # 元素A: text="确定" (精确匹配)
    # 元素B: text="确定按钮" (包含匹配)
    # 期望：A的分数高于B

    score_exact = _calculate_match_score("确定", "确定") * 0.15  # text维度权重
    score_contains = _calculate_match_score("确定", "确定按钮") * 0.15

    if score_exact > score_contains:
        print(f"[PASS] 精确匹配({score_exact:.4f}) > 包含匹配({score_contains:.4f})")
        passed = True
    else:
        print(f"[FAIL] 精确匹配({score_exact:.4f}) <= 包含匹配({score_contains:.4f})")
        passed = False

    # 模拟场景：关键词"新建"
    # 元素A: text="新建" (精确匹配)
    # 元素B: text="新建会议" (包含匹配)
    score_exact2 = _calculate_match_score("新建", "新建") * 0.15
    score_contains2 = _calculate_match_score("新建", "新建会议") * 0.15

    if score_exact2 > score_contains2:
        print(f"[PASS] 精确匹配({score_exact2:.4f}) > 包含匹配({score_contains2:.4f})")
        passed2 = True
    else:
        print(f"[FAIL] 精确匹配({score_exact2:.4f}) <= 包含匹配({score_contains2:.4f})")
        passed2 = False

    return passed and passed2


def main():
    """运行所有测试"""
    print("\n" + "=" * 60)
    print("Phase 2 评分体系归一化 - 验证测试")
    print("=" * 60)

    all_passed = True

    if not test_match_score():
        all_passed = False

    if not test_action_type_adjustment():
        all_passed = False

    if not test_exact_vs_contains_ranking():
        all_passed = False

    print()
    print("=" * 60)
    if all_passed:
        print("[SUCCESS] 所有测试通过！Phase 2 验证成功")
    else:
        print("[WARNING] 部分测试失败，请检查")
    print("=" * 60)

    return 0 if all_passed else 1


if __name__ == "__main__":
    sys.exit(main())