#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
快速查看草稿列表脚本

使用方法：
 python -m xqcwechat.scripts.quick_list_drafts [账号编号]

参数：
 1. 账号编号（可选，默认为账号1）

示例：
 python -m xqcwechat.scripts.quick_list_drafts
 python -m xqcwechat.scripts.quick_list_drafts 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 main():
    account_num = sys.argv[1] if len(sys.argv) > 1 else "1"

    print("=" * 60)
    print(f"快速查看草稿列表（账号 {account_num}）")
    print("=" * 60)

    from xqcwechat import Auth, Draft

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

        print("\n2. 获取草稿列表...")
        draft = Draft(auth)
        result = draft.get_draft_list(offset=0, count=10, no_content=True)

        if "item" in result:
            items = result["item"]
            total_count = result.get("total_count", len(items))
            print(f" ✅ 共 {total_count} 篇草稿，显示前 {len(items)} 篇：\n")

            for i, item in enumerate(items, 1):
                media_id = item.get("media_id", "N/A")
                content = item.get("content", {})
                news_item = content.get("news_item", [{}])[0] if content.get("news_item") else {}
                title = news_item.get("title", "无标题")
                author = news_item.get("author", "未知")
                print(f" {i}. {title}")
                print(f"    作者：{author}")
                print(f"    media_id：{media_id}")
                print()
        else:
            print(f" ❌ 获取失败：{result}")

    except Exception as e:
        print(f"\n❌ 错误：{str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
