# -*- coding: utf-8 -*-
"""
小红书发布工具 - OpenClaw Skill 执行脚本
"""
import sys
import os
import io
import asyncio
import json

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

# 添加当前目录到路径
skill_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, skill_dir)

from publisher import XiaohongshuPublisher


def publish_to_xiaohongshu(
    title: str = None,
    content: str = None,
    tags: list = None,
    images: list = None,
    headless: bool = False
):
    """
    发布内容到小红书

    Args:
        title: 标题
        content: 正文
        tags: 标签列表
        images: 图片路径列表
        headless: 是否无头模式

    Returns:
        结果字典
    """
    async def _publish():
        publisher = XiaohongshuPublisher(headless=headless)
        await publisher.start()

        try:
            # 检查登录
            if not await publisher.check_login():
                print("⚠️ 需要登录小红书账号")
                if not await publisher.wait_for_login():
                    return {"success": False, "error": publisher.last_error or "登录超时", "stage": publisher.last_stage}

            # 发布
            success = await publisher.publish_note(
                title=title,
                content=content,
                tags=tags,
                images=images
            )

            return {
                "success": success,
                "error": None if success else (publisher.last_error or "未知错误"),
                "stage": publisher.last_stage
            }

        finally:
            # 不立即关闭，让用户确认
            await asyncio.sleep(5)
            await publisher.close()

    return asyncio.run(_publish())


def main():
    """命令行入口"""
    import argparse

    parser = argparse.ArgumentParser(description="小红书发布工具")
    parser.add_argument("--title", "-t", help="笔记标题")
    parser.add_argument("--content", "-c", help="笔记正文")
    parser.add_argument("--tags", help="标签（逗号分隔）")
    parser.add_argument("--images", "-i", help="图片路径（逗号分隔）")
    parser.add_argument("--json", help="JSON 格式参数")
    parser.add_argument("--headless", action="store_true", help="无头模式")

    args = parser.parse_args()

    # 解析参数
    if args.json:
        try:
            data = json.loads(args.json)
            title = data.get("title")
            content = data.get("content")
            tags = data.get("tags")
            images = data.get("images")
        except json.JSONDecodeError:
            print("❌ JSON 解析失败")
            return
    else:
        title = args.title
        content = args.content
        tags = [t.strip() for t in args.tags.split(",")] if args.tags else None
        images = [i.strip() for i in args.images.split(",")] if args.images else None

    # 检查必要参数
    if not content:
        print("❌ 请提供正文内容 (--content 或 --json)")
        return

    # 发布
    result = publish_to_xiaohongshu(
        title=title,
        content=content,
        tags=tags,
        images=images,
        headless=args.headless
    )

    if result.get("success"):
        print(f"✅ 内容填充完成，当前阶段: {result.get('stage')}")
        print("ℹ️ 需要在浏览器中手动点击最终发布按钮")
    else:
        print(f"❌ 发布失败[{result.get('stage', 'unknown')}]: {result.get('error', '未知错误')}")


if __name__ == "__main__":
    main()
