# -*- coding: utf-8 -*-
"""
小红书文案生成器 - OpenClaw Skill 执行脚本
"""
import sys
import os
import io
import json
from pathlib import Path

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

# 使用相对于此脚本的路径
skill_dir = os.path.dirname(os.path.abspath(__file__))
project_path = os.path.join(skill_dir, "xiaohongshu-content-assistant")

if os.path.exists(project_path):
    sys.path.insert(0, project_path)
else:
    print("❌ 未找到 xiaohongshu-content-assistant 项目")
    print(f"   期望路径: {project_path}")
    sys.exit(1)

from models import OpenAICompatibleProvider
from core import ContentGenerator
from config import settings


def get_api_key():
    """
    获取 API Key（按优先级）：
    1. 命令行参数 --api-key
    2. 环境变量 QWEN_API_KEY
    3. 环境变量 OPENAI_API_KEY
    4. skill 目录下的 api_key.txt 文件
    5. 用户目录下的 .openclaw/api_key.txt 文件
    """
    # 1. 命令行参数
    for i, arg in enumerate(sys.argv):
        if arg == "--api-key" and i + 1 < len(sys.argv):
            return sys.argv[i + 1], None
    
    # 2. 环境变量 QWEN_API_KEY
    key = os.getenv("QWEN_API_KEY")
    if key:
        return key, "https://dashscope.aliyuncs.com/compatible-mode/v1"
    
    # 3. 环境变量 OPENAI_API_KEY
    key = os.getenv("OPENAI_API_KEY")
    if key:
        return key, os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
    
    # 4. skill 目录下的 api_key.txt
    skill_key_file = Path(skill_dir) / "api_key.txt"
    if skill_key_file.exists():
        content = skill_key_file.read_text(encoding="utf-8").strip()
        if content and not content.startswith("#"):
            lines = content.split("\n")
            key = lines[0].strip()
            base_url = lines[1].strip() if len(lines) > 1 else None
            return key, base_url
    
    # 5. 用户目录下的 .openclaw/api_key.txt
    user_key_file = Path.home() / ".openclaw" / "api_key.txt"
    if user_key_file.exists():
        content = user_key_file.read_text(encoding="utf-8").strip()
        if content and not content.startswith("#"):
            lines = content.split("\n")
            key = lines[0].strip()
            base_url = lines[1].strip() if len(lines) > 1 else None
            return key, base_url
    
    return None, None


def generate_xiaohongshu(topic: str, content_type: str = "lifestyle", style: str = "轻松活泼", api_key: str = None, base_url: str = None):
    """
    生成小红书文案

    Args:
        topic: 主题
        content_type: 内容类型
        style: 风格
        api_key: API Key（可选，不传则自动获取）
        base_url: API Base URL（可选）
    """
    # 获取 API Key
    if not api_key:
        api_key, detected_base_url = get_api_key()
        if base_url is None and detected_base_url:
            base_url = detected_base_url
    
    if not api_key:
        return {
            "error": """未配置 API Key！

请选择以下方式之一配置：

方式一：命令行传入
  python run.py --api-key YOUR_KEY "主题"

方式二：设置环境变量
  Windows: set QWEN_API_KEY=your-key
  Linux/Mac: export QWEN_API_KEY=your-key

方式三：创建配置文件
  在 skill 目录创建 api_key.txt 文件，写入你的 API Key

获取 API Key: https://dashscope.console.aliyun.com/"""
        }

    # 设置 API
    actual_base_url = base_url or "https://dashscope.aliyuncs.com/compatible-mode/v1"
    
    llm = OpenAICompatibleProvider(
        api_key=api_key,
        base_url=actual_base_url,
        model=settings.MODEL if "dashscope" in actual_base_url else "gpt-3.5-turbo"
    )
    generator = ContentGenerator(llm)

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

    try:
        result = generator.generate(
            content_type=content_type,
            params=params,
            style=style
        )
        return result
    except Exception as e:
        return {"error": str(e)}


if __name__ == "__main__":
    # 命令行使用
    import argparse
    
    parser = argparse.ArgumentParser(description="小红书文案生成器")
    parser.add_argument("topic", nargs="?", help="内容主题")
    parser.add_argument("--type", "-t", default="lifestyle", 
                       choices=["lifestyle", "knowledge", "coffee_culture", "product_review", "ootd", "food", "travel"],
                       help="内容类型")
    parser.add_argument("--style", "-s", default="轻松活泼", help="写作风格")
    parser.add_argument("--api-key", "-k", help="API Key（可选，不传则自动检测）")
    parser.add_argument("--base-url", "-b", help="API Base URL（可选）")
    
    args = parser.parse_args()
    
    if not args.topic:
        print("小红书文案生成器")
        print("")
        print("用法:")
        print("  python run.py <主题> [--type 类型] [--api-key KEY]")
        print("")
        print("示例:")
        print('  python run.py "手冲咖啡" --type coffee_culture')
        print('  python run.py "生日" --type lifestyle --api-key sk-xxx')
        print("")
        print("配置 API Key 方式:")
        print("  1. 命令行: --api-key YOUR_KEY")
        print("  2. 环境变量: set QWEN_API_KEY=your-key")
        print("  3. 配置文件: 创建 api_key.txt 文件")
        sys.exit(0)
    
    result = generate_xiaohongshu(
        topic=args.topic,
        content_type=args.type,
        style=args.style,
        api_key=args.api_key,
        base_url=args.base_url
    )
    
    if "error" in result:
        print(f"❌ {result['error']}")
    else:
        print(f"标题: {result.get('title', '')}")
        print(f"字数: {result.get('word_count', 0)} 字")
        print("-" * 40)
        print(result["content"])
        print("-" * 40)
        print(f"标签: {' '.join(result.get('tags', [])[:5])}")
