# -*- coding: utf-8 -*-
"""
小红书 AI 内容助手 - 主入口

功能：
1. CLI 快速生成模式
2. 交互式对话模式
3. API 服务模式
4. OpenClaw 集成模式
"""

import asyncio
import sys
import io
import argparse
from pathlib import Path

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

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


# 验证配置
def check_config(api_key: str = None):
    """检查 API Key 配置"""
    # 支持命令行传入 API Key
    if api_key:
        settings.set_api_key(api_key)
    
    if not settings.API_KEY:
        print("""
========================================
  ❌ 未配置 API Key
========================================

使用方式：

1. 命令行传入（推荐）:
   python main.py --api-key YOUR_KEY --topic "主题"

2. 环境变量:
   设置 QWEN_API_KEY 环境变量

3. .env 文件:
   创建 .env 文件，写入 QWEN_API_KEY=your-key

获取 API Key: https://dashscope.console.aliyun.com/
        """)
        sys.exit(1)


# ============================================
# 模式一：CLI 快速生成
# ============================================

def cli_mode(topic: str, content_type: str):
    """命令行快速生成模式"""
    # 初始化
    llm = OpenAICompatibleProvider(
        api_key=settings.API_KEY,
        base_url=settings.API_BASE_URL,
        model=settings.MODEL
    )
    generator = ContentGenerator(llm)

    # 根据类型设置参数
    params = get_params_by_type(content_type, topic)

    print(f"\n⏳ 正在生成 {content_type} 内容...")

    try:
        result = generator.generate(
            content_type=content_type,
            params=params,
            style="轻松活泼"
        )

        print(f"""
========================================
  ✨ 生成完成！
========================================

标题: {result['title']}
字数: {result['word_count']} 字符

----------------------------------------
{result['content']}
----------------------------------------

标签: {' '.join(result['tags'][:5])}
        """)

    except Exception as e:
        print(f"❌ 生成失败: {e}")


def get_params_by_type(content_type: str, topic: str) -> dict:
    """根据类型获取参数"""
    if content_type == "coffee_culture":
        return {
            "topic": topic,
            "cafe_scenario": "日常探店",
            "mood_keywords": "温暖,治愈,小资"
        }
    elif content_type == "product_review":
        return {
            "product_name": topic,
            "product_info": "待补充",
            "target_audience": "年轻人",
            "price_range": "待定"
        }
    elif content_type == "ootd":
        return {
            "outfit_description": topic,
            "style": "休闲",
            "occasion": "日常",
            "items": "待补充"
        }
    elif content_type == "knowledge":
        return {
            "topic": topic,
            "knowledge_point": topic,
            "target_audience": "年轻人"
        }
    elif content_type == "food":
        return {
            "shop_name": topic,
            "shop_info": "特色餐厅",
            "signature_dishes": "招牌菜",
            "price": "人均50-100元",
            "location": topic
        }
    elif content_type == "travel":
        return {
            "destination": topic,
            "travel_type": "周末游",
            "season": "四季皆宜",
            "budget": "人均500-1000元"
        }
    else:
        return {
            "topic": topic,
            "scenario": "日常生活",
            "mood": "轻松愉快"
        }


# ============================================
# 模式二：交互式对话
# ============================================

def interactive_mode():
    """交互式对话模式"""
    print(f"""
========================================
   小红书 AI 内容助手 v{settings.VERSION}
   Xiaohongshu Content Assistant
========================================
    """)

    agent = OpenClawAgent()

    print("\n💡 你可以对我说：")
    print("   - \"帮我写一篇咖啡探店的文案\"")
    print("   - \"生成关于秋冬穿搭的小红书内容\"")
    print("   - \"写一个产品测评，关于瑞幸拿铁\"")
    print("   - 输入 'quit' 退出\n")

    while True:
        try:
            user_input = input("👤 你: ").strip()

            if not user_input:
                continue

            if user_input.lower() in ['quit', 'exit', '退出', 'q']:
                print("👋 再见！")
                break

            # 处理请求
            result = agent.process(user_input)

            if result["status"] == "success":
                print(f"\n📝 AI助手:\n")
                content = result["content"]["content"]
                print(content[:500] + "..." if len(content) > 500 else content)
                print(f"\n标签: {' '.join(result['content']['tags'][:5])}\n")

            elif result["status"] == "need_more_info":
                print(f"\n🤔 AI助手: {result['message']}")
                if result.get("suggestions"):
                    print("💡 建议:")
                    for s in result["suggestions"]:
                        print(f"   - {s}")
                print()

            else:
                print(f"\n❌ 出错了: {result.get('message', '未知错误')}\n")

        except KeyboardInterrupt:
            print("\n👋 再见！")
            break
        except Exception as e:
            print(f"\n❌ 错误: {e}\n")


# ============================================
# 模式三：API 服务
# ============================================

def api_mode():
    """API 服务模式"""
    import uvicorn
    from api.server import app

    print("""
========================================
   API 服务模式
========================================

🚀 启动 API 服务...
📍 服务地址: http://localhost:8000
📚 API 文档: http://localhost:8000/docs

💡 按 Ctrl+C 停止服务
    """)

    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        log_level="info"
    )


# ============================================
# 模式四：OpenClaw 集成
# ============================================

def openclaw_mode():
    """OpenClaw 集成模式"""
    print("""
========================================
   OpenClaw 集成模式
========================================

✅ OpenClaw Skill 已安装
📍 技能位置: ~/.openclaw/skills/xiaohongshu-writer/

💡 使用方式：
   在 OpenClaw 中说：
   - "写一篇关于咖啡的小红书文案"
   - "帮我生成穿搭分享内容"

🔗 技能文件已配置，OpenClaw 会自动识别并调用
    """)

    # 测试技能
    agent = OpenClawAgent()
    result = agent.process("写一篇关于手冲咖啡入门的小红书文案")

    if result["status"] == "success":
        print("\n✅ 技能测试成功！\n")
        print(result["content"]["content"][:300] + "...")
    else:
        print(f"\n❌ 技能测试失败: {result.get('message')}")


# ============================================
# 主入口
# ============================================

def main():
    parser = argparse.ArgumentParser(
        description="小红书 AI 内容助手",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  python main.py --api-key YOUR_KEY --topic "手冲咖啡" --type coffee_culture
  python main.py --api-key YOUR_KEY --mode interactive
  python main.py --api-key YOUR_KEY --mode api
  python main.py --mode openclaw
        """
    )

    parser.add_argument("--mode", choices=["cli", "interactive", "api", "openclaw"],
                       default="cli", help="运行模式")
    parser.add_argument("--topic", help="内容主题（CLI模式）")
    parser.add_argument("--type", default="lifestyle",
                       choices=["coffee_culture", "product_review", "ootd",
                               "lifestyle", "food", "travel", "knowledge"],
                       help="内容类型（CLI模式）")
    parser.add_argument("--api-key", help="通义千问 API Key（动态传入）")
    parser.add_argument("--base-url", help="API Base URL（可选）")
    parser.add_argument("--model", help="模型名称（可选，默认 qwen-plus）")

    args = parser.parse_args()

    # 检查配置（支持动态传入 API Key）
    check_config(api_key=getattr(args, 'api_key', None))
    
    # 如果指定了 base_url 或 model，也设置
    if args.base_url:
        settings.set_api_key(settings.API_KEY, args.base_url)
    if args.model:
        settings.set_api_key(settings.API_KEY, model=args.model)

    # 根据模式执行
    if args.mode == "api":
        api_mode()
    elif args.mode == "interactive":
        interactive_mode()
    elif args.mode == "openclaw":
        openclaw_mode()
    else:  # cli mode
        if args.topic:
            cli_mode(args.topic, args.type)
        else:
            print("❌ CLI 模式需要 --topic 参数")
            print("💡 示例: python main.py --topic \"手冲咖啡\" --type coffee_culture")
            print("💡 或使用交互模式: python main.py --mode interactive")


if __name__ == "__main__":
    main()
