"""
小红书 AI 内容助手 - 完整测试

测试覆盖：
1. 基础功能测试
2. OpenClaw 集成测试
3. API 接口测试
4. 内容质量测试
"""

import sys
import io
from pathlib import Path

# 修复编码
if sys.platform == "win32":
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

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

from models import OpenAICompatibleProvider
from core import ContentGenerator, TemplateManager
from openclaw_integration import OpenClawAgent, IntentParser
from config import settings


def test_basic_generation():
    """测试基础内容生成"""
    print("\n" + "="*50)
    print("测试 1: 基础内容生成")
    print("="*50)

    try:
        llm = OpenAICompatibleProvider(
            api_key=settings.API_KEY,
            base_url=settings.API_BASE_URL,
            model=settings.MODEL
        )
        generator = ContentGenerator(llm)

        result = generator.generate(
            content_type="coffee_culture",
            params={
                "topic": "周末咖啡探店",
                "cafe_scenario": "独自工作",
                "mood_keywords": "安静,治愈"
            }
        )

        print("✅ 生成成功")
        print(f"标题: {result['title'][:50]}...")
        print(f"字数: {result['word_count']}")
        print(f"标签: {', '.join(result['tags'][:3])}")
        return True

    except Exception as e:
        print(f"❌ 失败: {e}")
        return False


def test_intent_parsing():
    """测试意图解析"""
    print("\n" + "="*50)
    print("测试 2: 意图解析")
    print("="*50)

    parser = IntentParser()

    test_cases = [
        "帮我写一篇关于咖啡探店的文案",
        "生成秋冬穿搭分享",
        "产品测评：瑞幸拿铁",
        "周末美食探店分享"
    ]

    for test_input in test_cases:
        result = parser.parse(test_input)
        print(f"\n输入: {test_input}")
        print(f"  主题: {result['topic']}")
        print(f"  类型: {result['content_type']}")
        print(f"  置信度: {result['confidence']:.2f}")

    return True


def test_openclaw_agent():
    """测试 OpenClaw 智能代理"""
    print("\n" + "="*50)
    print("测试 3: OpenClaw 智能代理")
    print("="*50)

    try:
        agent = OpenClawAgent()

        # 简单对话
        result = agent.process("写一篇关于手冲咖啡的文案")

        if result["status"] == "success":
            print("✅ 对话处理成功")
            print(f"识别类型: {result['intent']['content_type']}")
            print(f"内容预览: {result['content']['content'][:100]}...")
            return True
        else:
            print(f"❌ 处理失败: {result.get('message')}")
            return False

    except Exception as e:
        print(f"❌ 异常: {e}")
        return False


def test_content_types():
    """测试所有内容类型"""
    print("\n" + "="*50)
    print("测试 4: 所有内容类型")
    print("="*50)

    llm = OpenAICompatibleProvider(
        api_key=settings.API_KEY,
        base_url=settings.API_BASE_URL,
        model=settings.MODEL
    )
    generator = ContentGenerator(llm)
    template_manager = TemplateManager()

    types = template_manager.list_types()
    print(f"\n支持的内容类型 ({len(types)} 种):")

    for i, ct in enumerate(types, 1):
        print(f"  {i}. {ct}")

    return True


def test_batch_generation():
    """测试批量生成"""
    print("\n" + "="*50)
    print("测试 5: 批量生成")
    print("="*50)

    try:
        llm = OpenAICompatibleProvider(
            api_key=settings.API_KEY,
            base_url=settings.API_BASE_URL,
            model=settings.MODEL
        )
        generator = ContentGenerator(llm)

        results = generator.generate_batch(
            content_type="coffee_culture",
            params={"topic": "咖啡"},
            count=3
        )

        print(f"\n✅ 批量生成成功 ({len(results)} 个版本)")
        for i, r in enumerate(results, 1):
            print(f"  版本{i}: {r['title'][:40]}... ({r['word_count']}字)")

        return True

    except Exception as e:
        print(f"❌ 失败: {e}")
        return False


def run_all_tests():
    """运行所有测试"""
    print("""
╔════════════════════════════════════════╗
║   小红书 AI 内容助手 - 测试套件        ║
╚════════════════════════════════════════╝
    """)

    tests = [
        ("基础内容生成", test_basic_generation),
        ("意图解析", test_intent_parsing),
        ("OpenClaw 智能代理", test_openclaw_agent),
        ("所有内容类型", test_content_types),
        ("批量生成", test_batch_generation)
    ]

    results = []
    for name, test_func in tests:
        try:
            result = test_func()
            results.append((name, result))
        except Exception as e:
            print(f"\n❌ {name} 测试异常: {e}")
            results.append((name, False))

    # 汇总结果
    print("\n" + "="*50)
    print("测试结果汇总")
    print("="*50)

    passed = sum(1 for _, r in results if r)
    total = len(results)

    for name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"  {status}  {name}")

    print(f"\n总计: {passed}/{total} 通过")

    if passed == total:
        print("\n🎉 所有测试通过！")
    else:
        print(f"\n⚠️  {total - passed} 个测试失败")


if __name__ == "__main__":
    run_all_tests()
    input("\n按回车键退出...")
