#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
快速创建草稿脚本（支持多账号）

使用方法：
 python xqcwechat/xqcwechat-skill/scripts/quick_create_draft_multi.py "文章标题" "文章内容" cover.jpg

参数：
 1. 文章标题（必填）
 2. 文章内容（必填）
 3. 封面图片路径（必填，需要本地存在）
 4. 账号列表（可选，默认为所有账号，例如：1,2 或 1）

示例：
 # 为所有账号创建草稿
 python xqcwechat/xqcwechat-skill/scripts/quick_create_draft_multi.py "标题" "内容" cover.jpg

 # 为指定账号创建草稿
 python xqcwechat/xqcwechat-skill/scripts/quick_create_draft_multi.py "标题" "内容" cover.jpg "1,2"
"""

import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))

from dotenv import load_dotenv

script_dir = os.path.dirname(os.path.abspath(__file__))
skill_dir = os.path.dirname(script_dir)

# 加载环境变量 - 按优先级加载
env_paths = []
skill_env = os.path.join(skill_dir, ".env")
if os.path.exists(skill_env):
    env_paths.append(skill_env)

project_root = os.path.dirname(skill_dir)
project_env = os.path.join(project_root, ".env")
if os.path.exists(project_env):
    env_paths.append(project_env)

# 加载当前工作目录的 .env（用户项目根目录）
cwd_env = os.path.join(os.getcwd(), ".env")
if os.path.exists(cwd_env) and cwd_env not in env_paths:
    env_paths.append(cwd_env)

for env_path in env_paths:
    load_dotenv(env_path, override=True)


def detect_accounts():
    """检测配置的账号"""
    accounts = []
    account_num = 1

    while True:
        # 支持多种配置方式
        token_app_id = os.environ.get(f"WECHAT_ACCOUNT_{account_num}_TOKEN_APP_ID")
        app_id = os.environ.get(f"WECHAT_ACCOUNT_{account_num}_APP_ID")
        app_secret = os.environ.get(f"WECHAT_ACCOUNT_{account_num}_APP_SECRET")
        token_module = os.environ.get(f"WECHAT_ACCOUNT_{account_num}_TOKEN_GETTER_MODULE")

        # 判断是否有有效配置
        has_config = (
            (app_id and app_secret) or  # 方式一：官方API
            token_app_id or              # 方式二：默认回调
            token_module                 # 方式三：自定义回调
        )

        if has_config:
            accounts.append(account_num)
            account_num += 1
        else:
            # 检查是否有全局配置
            if account_num == 1:
                token_secret = os.environ.get("WECHAT_TOKEN_SECRET")
                global_app_id = os.environ.get("WECHAT_APP_ID")
                global_app_secret = os.environ.get("WECHAT_APP_SECRET")
                if token_secret or (global_app_id and global_app_secret):
                    accounts.append(1)
            break

    return accounts


def main():
    if len(sys.argv) < 4:
        print("用法：python xqcwechat/xqcwechat-skill/scripts/quick_create_draft_multi.py <标题> <内容> <封面图片路径> [账号列表]")
        print("示例：")
        print('  python xqcwechat/xqcwechat-skill/scripts/quick_create_draft_multi.py "我的文章" "这是文章内容" cover.jpg')
        print('  python xqcwechat/xqcwechat-skill/scripts/quick_create_draft_multi.py "我的文章" "这是文章内容" cover.jpg "1,2"')
        sys.exit(1)

    title = sys.argv[1]
    content = sys.argv[2]
    cover_path = sys.argv[3]
    account_list_str = sys.argv[4] if len(sys.argv) > 4 else None

    print("=" * 60)
    print("快速创建草稿（多账号支持）")
    print("=" * 60)

    if not os.path.exists(cover_path):
        print(f"\n❌ 封面图片不存在：{cover_path}")
        sys.exit(1)

    from xqcwechat import Auth, Draft, Asset

    all_accounts = detect_accounts()

    if not all_accounts:
        print("\n❌ 未检测到任何账号配置！")
        sys.exit(1)

    if account_list_str:
        target_accounts = [int(x.strip()) for x in account_list_str.split(",")]
        invalid_accounts = [acc for acc in target_accounts if acc not in all_accounts]
        if invalid_accounts:
            print(f"\n❌ 无效的账号：{invalid_accounts}")
            print(f" 可用账号：{all_accounts}")
            sys.exit(1)
    else:
        target_accounts = all_accounts

    print(f"\n📋 配置的账号：{all_accounts}")
    print(f"📋 目标账号：{target_accounts}")

    results = []

    for account_num in target_accounts:
        print(f"\n{'='*60}")
        print(f"正在为账号 {account_num} 创建草稿...")
        print(f"{'='*60}")

        try:
            print(f"\n1. 初始化 Auth（账号 {account_num}）...")
            auth = Auth.from_env(str(account_num))
            print(" ✅ Auth 初始化成功")
            print(f" 📋 app_id: {auth.app_id}")
            print(f" 📋 cache_key: {auth.cache_key}")

            print("\n2. 获取封面图片 media_id...")
            asset = Asset(auth)
            cover_result = asset.add_material("image", cover_path)
            thumb_media_id = cover_result.get("media_id")
            print(f" ✅ 封面上传成功，media_id: {thumb_media_id}")

            print("\n3. 创建草稿...")
            draft = Draft(auth)
            result = draft.create_draft([{
                "title": title,
                "content": content,
                "thumb_media_id": thumb_media_id,
                "show_cover_pic": 1,
            }])

            if "media_id" in result:
                print(" ✅ 草稿创建成功！")
                print(f" 📝 media_id: {result['media_id']}")
                results.append({
                    "account": account_num,
                    "media_id": result['media_id'],
                    "success": True
                })
            else:
                print(f" ❌ 草稿创建失败：{result}")
                results.append({
                    "account": account_num,
                    "error": str(result),
                    "success": False
                })

        except Exception as e:
            print(f"\n❌ 错误：{str(e)}")
            import traceback
            traceback.print_exc()
            results.append({
                "account": account_num,
                "error": str(e),
                "success": False
            })

    print(f"\n{'='*60}")
    print("创建结果汇总")
    print(f"{'='*60}")

    for result in results:
        if result["success"]:
            print(f"✅ 账号 {result['account']}: media_id={result['media_id']}")
        else:
            print(f"❌ 账号 {result['account']}: {result.get('error', '未知错误')}")

    success_count = sum(1 for r in results if r["success"])
    print(f"\n总计：{success_count}/{len(results)} 个账号创建成功")

    if success_count > 0:
        print("\n💡 提示：使用以下命令发布草稿：")
        for result in results:
            if result["success"]:
                print(f"  python xqcwechat/xqcwechat-skill/scripts/quick_publish.py {result['media_id']}")


if __name__ == "__main__":
    main()
