#!/usr/bin/env python3
"""
Gift-Advisor 命令行测试工具
用于10位用户测试的简单界面
"""
import sys
import json
from datetime import datetime
from pathlib import Path

# 添加src目录到路径
sys.path.insert(0, str(Path(__file__).parent.parent))

from src.api import parse_and_recommend, recommend_gift

def print_header():
    """打印标题"""
    print("🎁 Gift-Advisor AI礼物推荐专家")
    print("=" * 50)
    print("版本: 2.0.0 | 测试时间: 4月1日-4月7日")
    print("=" * 50)

def print_menu():
    """打印菜单"""
    print("\n请选择测试方式:")
    print("1. 自然语言输入（推荐）")
    print("2. 指定参数输入")
    print("3. 示例场景测试")
    print("4. 查看测试历史")
    print("5. 退出")
    print("-" * 30)

def natural_language_input():
    """自然语言输入"""
    print("\n💬 自然语言输入模式")
    print("示例: '送妈妈的生日礼物，预算500元左右'")
    print("       '给女朋友的情人节礼物，浪漫一点'")
    print("       '同事离职送什么，预算200元'")
    
    while True:
        query = input("\n请输入你的送礼需求: ").strip()
        if query:
            break
        print("请输入有效内容！")
    
    print(f"\n正在分析: {query}")
    print("请稍候...")
    
    try:
        result = parse_and_recommend(query)
        display_result(result)
        return result
    except Exception as e:
        print(f"❌ 出错了: {e}")
        return None

def parameter_input():
    """参数输入"""
    print("\n📋 参数输入模式")
    
    relation = input("关系（如：妈妈、女友、同事）: ").strip()
    occasion = input("场合（如：生日、情人节、离职）: ").strip()
    
    while True:
        try:
            budget_min = int(input("最低预算（元）: ").strip())
            budget_max = int(input("最高预算（元）: ").strip())
            if budget_min <= budget_max:
                break
            print("最低预算不能高于最高预算！")
        except ValueError:
            print("请输入有效的数字！")
    
    special_requirements = input("特殊要求（可选）: ").strip()
    
    print(f"\n正在分析: 送{relation}的{occasion}礼物，预算{budget_min}-{budget_max}元")
    if special_requirements:
        print(f"特殊要求: {special_requirements}")
    print("请稍候...")
    
    try:
        result = recommend_gift(
            relation=relation,
            occasion=occasion,
            budget_min=budget_min,
            budget_max=budget_max,
            special_requirements=special_requirements if special_requirements else None
        )
        display_result(result)
        return result
    except Exception as e:
        print(f"❌ 出错了: {e}")
        return None

def example_scenarios():
    """示例场景测试"""
    examples = [
        {
            "name": "送妈妈生日礼物",
            "query": "送妈妈的生日礼物，预算500元左右，要实用养生",
            "description": "测试基础场景，推荐实用养生礼物"
        },
        {
            "name": "送女友情人节礼物",
            "query": "给女朋友的情人节礼物，预算1000元，要浪漫有纪念意义",
            "description": "测试浪漫场景，推荐有纪念意义的礼物"
        },
        {
            "name": "送同事离职礼物",
            "query": "同事离职送什么礼物好，预算200元，要有意义",
            "description": "测试商务场景，推荐有意义的小礼物"
        },
        {
            "name": "送老板商务礼物",
            "query": "送老板的商务感谢礼物，预算2000元，要体面有价值",
            "description": "测试高端商务场景，推荐体面有价值的礼物"
        },
        {
            "name": "送长辈节日礼物",
            "query": "送长辈的中秋节礼物，预算300元，要传统健康",
            "description": "测试传统节日场景，推荐健康礼物"
        }
    ]
    
    print("\n📚 示例场景测试")
    for i, example in enumerate(examples, 1):
        print(f"{i}. {example['name']}")
        print(f"   描述: {example['description']}")
    
    while True:
        try:
            choice = int(input("\n请选择示例场景 (1-5): ").strip())
            if 1 <= choice <= 5:
                break
            print("请输入1-5之间的数字！")
        except ValueError:
            print("请输入有效的数字！")
    
    selected = examples[choice-1]
    print(f"\n正在测试: {selected['name']}")
    print(f"需求: {selected['query']}")
    print("请稍候...")
    
    try:
        result = parse_and_recommend(selected['query'])
        display_result(result)
        return result
    except Exception as e:
        print(f"❌ 出错了: {e}")
        return None

def display_result(result):
    """显示结果"""
    if not result or not result.get("success"):
        print("❌ 推荐失败，请重试")
        return
    
    recommendations = result.get("recommendations", [])
    if not recommendations:
        print("😔 没有找到合适的推荐")
        return
    
    print("\n" + "=" * 50)
    print("🎯 推荐结果")
    print("=" * 50)
    
    for i, rec in enumerate(recommendations, 1):
        print(f"\n{i}. {rec.get('name', '未知礼物')}")
        print(f"   价格: ¥{rec.get('price', '未知')}")
        print(f"   类型: {rec.get('category', '未知')}")
        print(f"   推荐理由: {rec.get('reason', '暂无理由')}")
        
        # 显示电商链接（如果有）
        shopping_links = rec.get('shopping_links', [])
        if shopping_links:
            print(f"   购买渠道: {len(shopping_links)}个")
            for link in shopping_links[:2]:  # 只显示前两个
                print(f"     - {link.get('platform', '平台')}: {link.get('name', '商品')}")
    
    # 显示祝福语
    blessing = result.get("blessing")
    if blessing:
        print("\n💝 祝福语:")
        print(f"   {blessing}")
    
    # 显示统计信息
    print(f"\n📊 统计: 共推荐{len(recommendations)}个礼物")
    
    # 保存测试历史
    save_test_history(result)

def save_test_history(result):
    """保存测试历史"""
    history_file = Path.home() / ".gift_advisor_test_history.json"
    
    # 读取现有历史
    history = []
    if history_file.exists():
        try:
            with open(history_file, 'r', encoding='utf-8') as f:
                history = json.load(f)
        except:
            history = []
    
    # 添加新记录
    history.append({
        "timestamp": datetime.now().isoformat(),
        "result": result
    })
    
    # 只保留最近20条记录
    if len(history) > 20:
        history = history[-20:]
    
    # 保存历史
    try:
        with open(history_file, 'w', encoding='utf-8') as f:
            json.dump(history, f, ensure_ascii=False, indent=2)
    except:
        pass  # 忽略保存错误

def view_test_history():
    """查看测试历史"""
    history_file = Path.home() / ".gift_advisor_test_history.json"
    
    if not history_file.exists():
        print("📭 暂无测试历史")
        return
    
    try:
        with open(history_file, 'r', encoding='utf-8') as f:
            history = json.load(f)
    except:
        print("❌ 无法读取测试历史")
        return
    
    if not history:
        print("📭 暂无测试历史")
        return
    
    print(f"\n📋 测试历史（最近{len(history)}条）")
    print("=" * 50)
    
    for i, record in enumerate(reversed(history), 1):
        timestamp = record.get("timestamp", "")
        result = record.get("result", {})
        recommendations = result.get("recommendations", [])
        
        # 解析时间
        try:
            dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
            time_str = dt.strftime("%m-%d %H:%M")
        except:
            time_str = timestamp
        
        print(f"\n{i}. {time_str}")
        if recommendations:
            first_rec = recommendations[0]
            print(f"   推荐: {first_rec.get('name', '未知')} (¥{first_rec.get('price', '未知')})")
            print(f"   数量: {len(recommendations)}个推荐")
        else:
            print("   无推荐结果")

def main():
    """主函数"""
    print_header()
    
    while True:
        print_menu()
        
        try:
            choice = input("请选择 (1-5): ").strip()
            if not choice:
                continue
                
            if choice == "1":
                natural_language_input()
            elif choice == "2":
                parameter_input()
            elif choice == "3":
                example_scenarios()
            elif choice == "4":
                view_test_history()
            elif choice == "5":
                print("\n感谢测试Gift-Advisor！")
                print("请记得填写反馈问卷，帮助我们改进产品！")
                print("🎁 祝您使用愉快！")
                break
            else:
                print("❌ 无效选择，请重新输入")
                
        except KeyboardInterrupt:
            print("\n\n👋 感谢测试，再见！")
            break
        except Exception as e:
            print(f"❌ 发生错误: {e}")
            print("请重试或联系技术支持")

if __name__ == "__main__":
    main()