#!/usr/bin/env python3
"""
真实世界测试 - 模拟真实用户场景
"""
import sys
import time
from datetime import datetime

sys.path.insert(0, '.')

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

def run_real_world_tests():
    """运行真实世界测试"""
    print("🧪 真实世界功能测试")
    print("=" * 60)
    
    all_passed = True
    test_results = []
    
    # 测试1: 直接推荐（最常用场景）
    print("\n📋 测试1: 直接礼物推荐")
    try:
        start_time = time.time()
        result = recommend_gift('妈妈', '生日', 200, 1000, enhanced=True)
        elapsed = time.time() - start_time
        
        if result['success']:
            score = 10.0
            if result.get('count', 0) < 3:
                score -= 2
            if elapsed > 1.0:
                score -= 1
            if not result.get('recommendations'):
                score = 0
            
            print(f"  ✅ 成功！推荐{result['count']}个礼物，耗时{elapsed:.2f}秒")
            print(f"    评分: {score:.1f}/10")
            
            if result['recommendations']:
                print(f"    推荐示例:")
                for i, rec in enumerate(result['recommendations'][:2], 1):
                    print(f"      {i}. {rec['name']} ({rec['price']}元) - {rec['reason'][:30]}...")
        else:
            print(f"  ❌ 失败！错误: {result.get('message', '未知错误')}")
            score = 0
            all_passed = False
        
        test_results.append(("直接推荐", score))
    
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        test_results.append(("直接推荐", 0))
        all_passed = False
    
    # 测试2: 自然语言解析
    print("\n📋 测试2: 自然语言输入")
    try:
        test_cases = [
            ("送妈妈的生日礼物，预算500元左右", "基本场景"),
            ("情人节送女友，想要浪漫惊喜", "浪漫场景"),
            ("送领导乔迁礼物，要体面大方", "商务场景"),
        ]
        
        for text, desc in test_cases:
            start_time = time.time()
            result = parse_and_recommend(text, enhanced=True)
            elapsed = time.time() - start_time
            
            if result['success']:
                if result.get('type') == 'recommendation':
                    print(f"  ✅ {desc}: 成功推荐{result.get('count', 0)}个礼物，耗时{elapsed:.2f}秒")
                elif result.get('needs_clarification'):
                    print(f"  ⚠️ {desc}: 需要更多信息，耗时{elapsed:.2f}秒")
                    print(f"    问题: {result.get('clarification_questions', [''])[0]}")
                else:
                    print(f"  ❓ {desc}: 其他结果，耗时{elapsed:.2f}秒")
            else:
                print(f"  ❌ {desc}: 失败，耗时{elapsed:.2f}秒")
                print(f"    错误: {result.get('message', '未知错误')}")
                all_passed = False
        
        test_results.append(("自然语言解析", 8.5 if all_passed else 5.0))
    
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        test_results.append(("自然语言解析", 0))
        all_passed = False
    
    # 测试3: 禁忌解释
    print("\n📋 测试3: 禁忌解释")
    try:
        test_cases = [
            ("精美时钟", "长辈", "钟表禁忌"),
            ("梨子", "情侣", "分离禁忌"),
            ("鞋子", "所有关系", "鞋子禁忌"),
        ]
        
        scores = []
        for gift, relation, desc in test_cases:
            result = explain_gift_taboo(gift, relation)
            
            if result['success']:
                explanation = result.get('explanation', '')
                if explanation and "暂无发现禁忌" not in explanation:
                    print(f"  ✅ {desc}: 正确识别禁忌")
                    print(f"    解释: {explanation[:50]}...")
                    scores.append(10.0)
                else:
                    print(f"  ⚠️ {desc}: 未识别到禁忌或解释不完整")
                    scores.append(5.0)
            else:
                print(f"  ❌ {desc}: 失败")
                scores.append(0)
                all_passed = False
        
        avg_score = sum(scores) / len(scores) if scores else 0
        test_results.append(("禁忌解释", avg_score))
    
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        test_results.append(("禁忌解释", 0))
        all_passed = False
    
    # 测试4: 祝福语生成
    print("\n📋 测试4: 祝福语选项")
    try:
        result = get_blessing_options('情人节', '女友', '巧克力', 3)
        
        if result['success']:
            options = result.get('options', [])
            if len(options) >= 3:
                print(f"  ✅ 成功生成{len(options)}个祝福语选项")
                print(f"    示例: {options[0][:50]}...")
                test_results.append(("祝福语生成", 10.0))
            else:
                print(f"  ⚠️ 只生成{len(options)}个选项，需要至少3个")
                test_results.append(("祝福语生成", 6.0))
                all_passed = False
        else:
            print(f"  ❌ 失败: {result.get('message', '未知错误')}")
            test_results.append(("祝福语生成", 0))
            all_passed = False
    
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        test_results.append(("祝福语生成", 0))
        all_passed = False
    
    # 测试5: 对话系统
    print("\n📋 测试5: 对话式推荐")
    try:
        advisor = start_conversation('test_user_123')
        
        # 模拟对话
        responses = []
        test_inputs = [
            "我想给妈妈选生日礼物",
            "预算500元左右",
            "她喜欢养花",
            "实用一点的",
        ]
        
        for user_input in test_inputs:
            result = advisor.process_message(user_input)
            responses.append(result)
            
            if not result['success']:
                print(f"  ❌ 对话失败: {result.get('message', '未知错误')}")
                all_passed = False
                break
        
        # 检查对话是否正常
        if all_passed:
            last_response = responses[-1]
            if last_response.get('type') == 'question' or 'recommendations' in last_response:
                print(f"  ✅ 对话系统工作正常")
                print(f"    对话状态: {advisor.conversation_state}")
                test_results.append(("对话系统", 9.0))
            else:
                print(f"  ⚠️ 对话系统需要优化")
                test_results.append(("对话系统", 6.0))
                all_passed = False
    
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        test_results.append(("对话系统", 0))
        all_passed = False
    
    # 计算总体评分
    print("\n" + "=" * 60)
    print("📊 总体评分汇总")
    print("=" * 60)
    
    total_score = 0
    for test_name, score in test_results:
        print(f"  {test_name}: {score:.1f}/10")
        total_score += score
    
    avg_score = total_score / len(test_results) if test_results else 0
    
    print(f"\n🎯 平均分: {avg_score:.2f}/10")
    
    if avg_score >= 9.7:
        print("✅ 达到9.7+上线标准！")
    elif avg_score >= 9.0:
        print("🟡 接近目标，需要微小优化")
    elif avg_score >= 8.0:
        print("🟠 需要中等优化")
    else:
        print("🔴 需要重大改进")
    
    return avg_score >= 9.7, avg_score, test_results

if __name__ == "__main__":
    passed, avg_score, results = run_real_world_tests()
    
    # 保存测试结果
    import json
    result_data = {
        "test_date": datetime.now().isoformat(),
        "passed": passed,
        "average_score": avg_score,
        "test_results": [
            {"test": name, "score": score} for name, score in results
        ],
        "recommendation": "立即上线" if passed else "需要优化"
    }
    
    with open("real_world_test_results.json", "w", encoding="utf-8") as f:
        json.dump(result_data, f, ensure_ascii=False, indent=2)
    
    print(f"\n📄 测试报告已保存: real_world_test_results.json")
    
    exit(0 if passed else 1)