#!/usr/bin/env python3
"""
Gift-Advisor 优化版功能测试脚本
用于专家评测新功能
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from src.api import (
    recommend_gift,
    parse_and_recommend,
    explain_gift_taboo,
    get_blessing_options,
    start_conversation,
    GiftAdvisor
)
import json

def test_enhanced_recommendation():
    """测试增强推荐功能"""
    print("=" * 60)
    print("测试1: 增强推荐功能")
    print("=" * 60)
    
    # 测试用例
    test_cases = [
        {
            "name": "妈妈生日",
            "relation": "妈妈",
            "occasion": "生日",
            "budget_min": 200,
            "budget_max": 1000
        },
        {
            "name": "女友情人节",
            "relation": "女友",
            "occasion": "情人节",
            "budget_min": 300,
            "budget_max": 2000
        },
        {
            "name": "商务送礼",
            "relation": "客户",
            "occasion": "商务",
            "budget_min": 500,
            "budget_max": 1500
        }
    ]
    
    all_passed = True
    for test in test_cases:
        print(f"\n📋 测试: {test['name']}")
        print(f"  关系: {test['relation']}, 场合: {test['occasion']}, 预算: {test['budget_min']}-{test['budget_max']}元")
        
        try:
            # 增强版推荐
            result = recommend_gift(
                relation=test['relation'],
                occasion=test['occasion'],
                budget_min=test['budget_min'],
                budget_max=test['budget_max'],
                enhanced=True
            )
            
            if result['success']:
                print(f"  ✅ 成功! 推荐数量: {result['count']}")
                print(f"    禁忌报告: {result['taboo_report']['summary']}")
                
                # 检查是否有禁忌过滤
                if "发现" in result['taboo_report']['summary']:
                    print(f"    ⚠️ 发现禁忌礼物")
                
                # 显示Top推荐
                if result['recommendations']:
                    top = result['recommendations'][0]
                    print(f"    Top推荐: {top['name']} ({top['price']}元) - 评分: {top['score']}")
                    print(f"    推荐理由: {top['reason'][:40]}...")
                
                # 检查祝福语
                if result.get('blessing'):
                    print(f"    祝福语: {result['blessing'][:50]}...")
                
                # 检查祝福语选项
                if result.get('blessing_options'):
                    print(f"    祝福语选项: {len(result['blessing_options'])}个")
                
            else:
                print(f"  ❌ 失败: {result.get('message', '未知错误')}")
                all_passed = False
                
        except Exception as e:
            print(f"  ❌ 异常: {e}")
            all_passed = False
    
    return all_passed

def test_taboo_explanation():
    """测试禁忌解释功能"""
    print("\n" + "=" * 60)
    print("测试2: 禁忌解释功能")
    print("=" * 60)
    
    test_cases = [
        {"gift": "精美时钟", "relation": "长辈", "expected_taboo": True},
        {"gift": "水晶梨果篮", "relation": "情侣", "expected_taboo": True},
        {"gift": "白色菊花束", "relation": "病人", "expected_taboo": True},
        {"gift": "蓝牙耳机", "relation": "朋友", "expected_taboo": False},
        {"gift": "猪肉制品", "relation": "伊斯兰教朋友", "expected_taboo": True},
    ]
    
    all_passed = True
    for test in test_cases:
        print(f"\n📋 测试: {test['gift']} (关系: {test['relation']})")
        
        try:
            result = explain_gift_taboo(test['gift'], test['relation'])
            
            if result['success']:
                has_taboo = result['has_taboo']
                expected = test['expected_taboo']
                
                if has_taboo == expected:
                    print(f"  ✅ 正确! 禁忌检测: {'有' if has_taboo else '无'}")
                    if has_taboo:
                        print(f"    解释: {result['explanation'][:60]}...")
                        if result['alternatives']:
                            print(f"    替代品: {', '.join(result['alternatives'][:3])}")
                else:
                    print(f"  ❌ 错误! 期望: {'有' if expected else '无'}, 实际: {'有' if has_taboo else '无'}")
                    all_passed = False
            else:
                print(f"  ❌ 失败: {result.get('message', '未知错误')}")
                all_passed = False
                
        except Exception as e:
            print(f"  ❌ 异常: {e}")
            all_passed = False
    
    return all_passed

def test_blessing_options():
    """测试祝福语选项功能"""
    print("\n" + "=" * 60)
    print("测试3: 祝福语选项功能")
    print("=" * 60)
    
    test_cases = [
        {"occasion": "生日", "relation": "妈妈", "gift": "鲜花"},
        {"occasion": "情人节", "relation": "女友", "gift": "巧克力"},
        {"occasion": "母亲节", "relation": "妈妈", "gift": "护肤品"},
    ]
    
    all_passed = True
    for test in test_cases:
        print(f"\n📋 测试: {test['occasion']} - {test['relation']} - {test['gift']}")
        
        try:
            result = get_blessing_options(
                occasion=test['occasion'],
                relation=test['relation'],
                gift_name=test['gift'],
                count=3
            )
            
            if result['success']:
                options = result.get('options', [])
                print(f"  ✅ 成功! 生成{len(options)}个选项")
                
                for i, option in enumerate(options, 1):
                    style = option.split('：')[0] if '：' in option else "未知风格"
                    content = option.split('：')[1] if '：' in option else option
                    print(f"    {i}. {style}: {content[:40]}...")
            else:
                print(f"  ❌ 失败: {result.get('message', '未知错误')}")
                all_passed = False
                
        except Exception as e:
            print(f"  ❌ 异常: {e}")
            all_passed = False
    
    return all_passed

def test_dialog_system():
    """测试对话系统功能"""
    print("\n" + "=" * 60)
    print("测试4: 对话系统功能")
    print("=" * 60)
    
    all_passed = True
    
    try:
        print("📋 测试: 多轮对话")
        
        # 创建对话实例
        advisor = start_conversation("test_expert")
        
        # 第一轮：基本信息
        print("  用户: 我想给妈妈选生日礼物")
        result1 = advisor.process_message("我想给妈妈选生日礼物")
        print(f"  助手: {result1.get('message', '无回复')[:50]}...")
        
        # 第二轮：预算
        print("  用户: 预算500元左右")
        result2 = advisor.process_message("预算500元左右")
        print(f"  助手: {result2.get('message', '无回复')[:50]}...")
        
        # 第三轮：兴趣
        print("  用户: 她喜欢养花")
        result3 = advisor.process_message("她喜欢养花")
        print(f"  助手: {result3.get('message', '无回复')[:50]}...")
        
        # 第四轮：风格偏好
        print("  用户: 实用一点的")
        result4 = advisor.process_message("实用一点的")
        
        # 检查是否进入推荐状态
        if result4.get('type') == 'question' or 'recommendations' in result4:
            print("  ✅ 对话流程正常")
        else:
            print(f"  ❌ 对话状态异常: {result4}")
            all_passed = False
            
        # 测试对话状态
        print("\n📋 测试: 对话状态管理")
        advisor.reset_conversation()
        result_reset = advisor.process_message("你好")
        if "重新开始" in result_reset.get('message', ''):
            print("  ✅ 对话重置成功")
        else:
            print(f"  ❌ 对话重置异常: {result_reset}")
            all_passed = False
            
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        all_passed = False
    
    return all_passed

def test_natural_language():
    """测试自然语言解析"""
    print("\n" + "=" * 60)
    print("测试5: 自然语言解析")
    print("=" * 60)
    
    test_cases = [
        "送妈妈的生日礼物，预算500元左右",
        "情人节送女友，想要浪漫惊喜，预算1000-2000",
        "送客户节日礼物，要体面大方，预算500-1500",
        "给爸爸选父亲节礼物，他喜欢喝茶，预算300-800",
    ]
    
    all_passed = True
    for text in test_cases:
        print(f"\n📋 测试: {text}")
        
        try:
            result = parse_and_recommend(text, enhanced=True)
            
            if result['success']:
                print(f"  ✅ 成功! 推荐数量: {result.get('count', 0)}")
                
                if result.get('query'):
                    query = result['query']
                    print(f"    解析结果: {query.get('relation', '?')}的{query.get('occasion', '?')}, 预算{query.get('budget', '?')}")
                
                if result.get('recommendations'):
                    top = result['recommendations'][0]
                    print(f"    Top推荐: {top['name']} ({top['price']}元)")
            else:
                if result.get('needs_clarification'):
                    print(f"  ⚠️ 需要追问: {result.get('clarification_questions', [])}")
                else:
                    print(f"  ❌ 失败: {result.get('message', '未知错误')}")
                    all_passed = False
                    
        except Exception as e:
            print(f"  ❌ 异常: {e}")
            all_passed = False
    
    return all_passed

def run_comprehensive_test():
    """运行综合测试"""
    print("🚀 Gift-Advisor 优化版综合测试")
    print("=" * 60)
    print("测试时间: 2026-03-31")
    print("测试目标: 验证优化效果 (8.0 → 9.0+)")
    print("=" * 60)
    
    test_results = []
    
    # 运行所有测试
    test_results.append(("增强推荐", test_enhanced_recommendation()))
    test_results.append(("禁忌解释", test_taboo_explanation()))
    test_results.append(("祝福语选项", test_blessing_options()))
    test_results.append(("对话系统", test_dialog_system()))
    test_results.append(("自然语言解析", test_natural_language()))
    
    # 统计结果
    print("\n" + "=" * 60)
    print("📊 测试结果汇总")
    print("=" * 60)
    
    passed_count = 0
    total_count = len(test_results)
    
    for test_name, passed in test_results:
        status = "✅ 通过" if passed else "❌ 失败"
        print(f"{test_name}: {status}")
        if passed:
            passed_count += 1
    
    success_rate = (passed_count / total_count) * 100
    
    print(f"\n📈 测试通过率: {passed_count}/{total_count} ({success_rate:.1f}%)")
    
    # 生成测试报告
    report = {
        "test_date": "2026-03-31",
        "total_tests": total_count,
        "passed_tests": passed_count,
        "success_rate": success_rate,
        "test_results": [
            {"test": name, "passed": passed}
            for name, passed in test_results
        ],
        "optimization_verdict": "✅ 优化成功" if success_rate >= 80 else "⚠️ 需要改进",
        "expected_score": "9.0+" if success_rate >= 80 else "8.0-8.5"
    }
    
    # 保存报告
    report_file = "test_report_20260331.json"
    with open(report_file, 'w', encoding='utf-8') as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    
    print(f"\n📄 测试报告已保存: {report_file}")
    print("\n" + "=" * 60)
    
    if success_rate >= 80:
        print("🎉 恭喜！优化版测试通过率达标！")
        print(f"📊 预计评分: 9.0+ (原8.0)")
        print("🚀 建议: 可以邀请专家进行正式评测")
    else:
        print("⚠️ 注意：部分测试未通过")
        print("🔧 建议：先修复问题再进行专家评测")
    
    return success_rate >= 80

def main():
    """主函数"""
    try:
        # 导入检查
        print("🔍 检查环境...")
        from src.api import __version__
        print(f"✅ Gift-Advisor版本: {getattr(__version__, '__version__', '2.0.0')}")
        
        # 运行测试
        success = run_comprehensive_test()
        
        # 退出码
        sys.exit(0 if success else 1)
        
    except ImportError as e:
        print(f"❌ 导入失败: {e}")
        print("请确保在项目根目录运行: python scripts/test_enhanced_features.py")
        sys.exit(1)
    except Exception as e:
        print(f"❌ 测试异常: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()