# -*- coding: utf-8 -*-
"""
小红书视频笔记上传示例

展示如何使用XiaoHongShuVideoNote类上传视频笔记
"""

import sys
import os
import asyncio
from pathlib import Path
from datetime import datetime, timedelta

# 添加项目根目录到系统路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
sys.path.append(project_root)

from conf import BASE_DIR
from uploader.xhs_note_uploader.main import (
    XiaoHongShuVideoNote,
    xiaohongshu_note_setup
)


async def upload_video_note_example():
    """视频笔记上传示例"""
    
    print("=" * 60)
    print("小红书视频笔记上传示例")
    print("=" * 60)
    
    # ========== 配置参数 ==========
    
    # 标题（最多30字符）
    title = "一分钟学会做蛋糕🍰"
    
    # 正文内容（最多1000字符）
    content = """超简单的蛋糕教程来啦！

📝 材料清单：
🥚 鸡蛋 3个
🍬 白糖 50g
🌾 低筋面粉 60g
🥛 牛奶 30ml

新手也能一次成功
快来试试吧～

完整配方在评论区👇"""
    
    # 话题标签（建议最多3个）
    tags = ["美食教程", "烘焙", "蛋糕"]
    
    # 视频文件路径
    video_path = str(Path(BASE_DIR) / "videos" / "demo.mp4")
    
    # 视频封面路径（可选，不设置则使用视频第一帧）
    thumbnail_path = None  # str(Path(BASE_DIR) / "videos" / "thumbnail.jpg")
    
    # Cookie文件路径
    account_file = Path(BASE_DIR) / "cookies" / "xiaohongshu_note" / "account.json"
    account_file.parent.mkdir(parents=True, exist_ok=True)
    
    # 发布时间设置
    # 方式1: 立即发布
    publish_date = 0
    
    # 方式2: 定时发布（明天上午10点）
    # publish_date = datetime.now() + timedelta(days=1)
    # publish_date = publish_date.replace(hour=10, minute=0, second=0)
    
    # 可选参数
    location = "北京市·朝阳区"  # 地点（可选）
    
    # 是否使用无头模式（不推荐）
    headless = False
    
    # ========== 检查Cookie ==========
    
    print(f"\n[1/3] 检查Cookie...")
    cookie_valid = await xiaohongshu_note_setup(str(account_file), handle=True)
    
    if not cookie_valid:
        print("❌ Cookie无效，请重新登录")
        return
    
    print("✅ Cookie有效")
    
    # ========== 验证视频文件 ==========
    
    print(f"\n[2/3] 验证视频文件...")
    
    if not os.path.exists(video_path):
        print(f"❌ 视频文件不存在: {video_path}")
        print(f"提示: 请将视频放在 {Path(BASE_DIR) / 'videos'} 目录下")
        return
    
    file_size_mb = os.path.getsize(video_path) / (1024 * 1024)
    print(f"✅ 视频文件: {os.path.basename(video_path)}")
    print(f"   大小: {file_size_mb:.2f} MB")
    
    if thumbnail_path and not os.path.exists(thumbnail_path):
        print(f"⚠️  封面文件不存在: {thumbnail_path}")
        print(f"   将使用视频第一帧作为封面")
        thumbnail_path = None
    
    # ========== 创建上传器并执行上传 ==========
    
    print(f"\n[3/3] 开始上传视频笔记...")
    print(f"标题: {title}")
    print(f"标签: {tags}")
    print(f"地点: {location}")
    print(f"发布方式: {'立即发布' if publish_date == 0 else f'定时发布({publish_date})'}")
    print()
    
    try:
        # 创建视频笔记上传器
        note = XiaoHongShuVideoNote(
            title=title,
            content=content,
            tags=tags,
            video_path=video_path,
            publish_date=publish_date,
            account_file=str(account_file),
            thumbnail_path=thumbnail_path,
            location=location,
            headless=headless
        )
        
        # 执行上传
        await note.main()
        
        print("\n" + "=" * 60)
        print("🎉 视频笔记上传成功！")
        print("=" * 60)
        
    except Exception as e:
        print("\n" + "=" * 60)
        print(f"❌ 上传失败: {e}")
        print("=" * 60)
        raise


async def upload_video_with_schedule_example():
    """定时发布视频笔记示例"""
    
    print("=" * 60)
    print("小红书视频笔记定时发布示例")
    print("=" * 60)
    
    account_file = Path(BASE_DIR) / "cookies" / "xiaohongshu_note" / "account.json"
    account_file.parent.mkdir(parents=True, exist_ok=True)
    
    # 检查Cookie
    cookie_valid = await xiaohongshu_note_setup(str(account_file), handle=True)
    if not cookie_valid:
        print("❌ Cookie无效")
        return
    
    # 配置定时发布
    video_path = str(Path(BASE_DIR) / "videos" / "demo.mp4")
    
    # 设置发布时间（明天下午3点）
    publish_time = datetime.now() + timedelta(days=1)
    publish_time = publish_time.replace(hour=15, minute=0, second=0, microsecond=0)
    
    print(f"定时发布时间: {publish_time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    try:
        note = XiaoHongShuVideoNote(
            title="定时发布测试🕐",
            content="这是一条定时发布的视频笔记",
            tags=["测试", "定时发布"],
            video_path=video_path,
            publish_date=publish_time,
            account_file=str(account_file),
            headless=False
        )
        
        await note.main()
        
        print(f"\n✅ 视频已设置为定时发布: {publish_time.strftime('%Y-%m-%d %H:%M:%S')}")
        
    except Exception as e:
        print(f"\n❌ 设置失败: {e}")


if __name__ == "__main__":
    # 运行单个视频笔记上传示例
    asyncio.run(upload_video_note_example())
    
    # 如果需要定时发布，注释掉上面一行，取消下面的注释
    # asyncio.run(upload_video_with_schedule_example())

