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

使用方法：
 python xqcwechat/xqcwechat-skill/scripts/quick_publish.py <media_id> [标题] [账号列表]

参数：
 1. media_id（必填）- 草稿的 media_id
 2. 标题（可选）- 用来指定本次发布的标题
 3. 账号列表（可选）- 指定发布的账号，如 "1,2"，默认为所有账号

示例：
 # 发布到所有账号
 python xqcwechat/xqcwechat-skill/scripts/quick_publish.py abc123xyz

 # 发布到指定账号
 python xqcwechat/xqcwechat-skill/scripts/quick_publish.py abc123xyz "标题" "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) < 2:
        print("用法：python xqcwechat/xqcwechat-skill/scripts/quick_publish.py <media_id> [标题] [账号列表]")
        print("示例：")
        print("  python xqcwechat/xqcwechat-skill/scripts/quick_publish.py abc123xyz")
        print('  python xqcwechat/xqcwechat-skill/scripts/quick_publish.py abc123xyz "自定义标题"')
        print('  python xqcwechat/xqcwechat-skill/scripts/quick_publish.py abc123xyz "标题" "1,2"')
        sys.exit(1)

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

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

    from xqcwechat import Auth, Publish

    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}")
    print(f"📋 草稿 media_id：{media_id}")

    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. 发布草稿...")
            publish = Publish(auth)
            result = publish.publish_draft(media_id, title)

            if "publish_id" in result:
                print(" ✅ 草稿发布成功！")
                print(f" 📢 publish_id: {result['publish_id']}")
                results.append({
                    "account": account_num,
                    "publish_id": result['publish_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']}: publish_id={result['publish_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 __name__ == "__main__":
    main()
