"""
上传默认故事媒体资源到 OSS

使用方法:
    python manage.py upload_default_story_media
    python manage.py upload_default_story_media --dry-run   # 仅检查，不上传

上传内容:
    - 视频: rtc_prd/动态绘本/失控的魔法扫帚.mp4  →  stories/defaults/失控的魔法扫帚.mp4
    - 封面: rtc_prd/故事书封面图/卡皮巴拉的奇幻漂流.png  →  stories/defaults/失控的魔法扫帚_cover.png
"""
import os

from django.conf import settings
from django.core.management.base import BaseCommand

try:
    import oss2
    OSS_AVAILABLE = True
except ImportError:
    OSS_AVAILABLE = False

# 上传目标 OSS key（固定路径，与 utils.py 中的 URL 对应）
_PRD_ROOT = os.path.expanduser("~/Desktop/zyc/qiyuan_gitea/rtc_prd")

UPLOAD_ITEMS = [
    {
        "desc": "绘本视频",
        "local": os.path.join(_PRD_ROOT, "动态绘本/失控的魔法扫帚.mp4"),
        "oss_key": "stories/defaults/失控的魔法扫帚.mp4",
        "content_type": "video/mp4",
    },
    {
        "desc": "故事封面",
        "local": os.path.join(_PRD_ROOT, "故事书封面图/卡皮巴拉的奇幻漂流.png"),
        "oss_key": "stories/defaults/失控的魔法扫帚_cover.png",
        "content_type": "image/png",
    },
]


class Command(BaseCommand):
    help = "上传默认故事的视频和封面到 OSS"

    def add_arguments(self, parser):
        parser.add_argument(
            "--dry-run",
            action="store_true",
            help="仅打印计划，不实际上传",
        )

    def handle(self, *args, **options):
        dry_run = options["dry_run"]

        if not OSS_AVAILABLE:
            self.stderr.write(self.style.ERROR("oss2 未安装，请先 pip install oss2"))
            return

        oss_config = settings.ALIYUN_OSS
        if not oss_config.get("ACCESS_KEY_ID"):
            self.stderr.write(self.style.ERROR("OSS 未配置，请检查 .env 中的 ALIYUN_OSS 设置"))
            return

        auth = oss2.Auth(oss_config["ACCESS_KEY_ID"], oss_config["ACCESS_KEY_SECRET"])
        bucket = oss2.Bucket(auth, oss_config["ENDPOINT"], oss_config["BUCKET_NAME"])
        oss_base = f"https://{oss_config['BUCKET_NAME']}.{oss_config['ENDPOINT']}"

        for item in UPLOAD_ITEMS:
            local_path = os.path.normpath(item["local"])
            oss_key = item["oss_key"]
            target_url = f"{oss_base}/{oss_key}"

            self.stdout.write(f"\n[{item['desc']}]")
            self.stdout.write(f"  本地文件: {local_path}")
            self.stdout.write(f"  OSS 目标: {oss_key}")
            self.stdout.write(f"  访问 URL: {target_url}")

            if not os.path.isfile(local_path):
                self.stderr.write(self.style.WARNING(f"  ⚠ 本地文件不存在，跳过"))
                continue

            file_size = os.path.getsize(local_path)
            self.stdout.write(f"  文件大小: {file_size / 1024 / 1024:.1f} MB")

            # 检查 OSS 是否已存在
            try:
                bucket.get_object_meta(oss_key)
                self.stdout.write(self.style.WARNING("  ✓ OSS 已存在，跳过上传"))
                continue
            except oss2.exceptions.NoSuchKey:
                pass  # 不存在，需要上传

            if dry_run:
                self.stdout.write(self.style.NOTICE("  [dry-run] 将会上传此文件"))
                continue

            self.stdout.write("  上传中...")
            with open(local_path, "rb") as f:
                bucket.put_object(
                    oss_key,
                    f,
                    headers={"Content-Type": item["content_type"]},
                )
            self.stdout.write(self.style.SUCCESS(f"  ✓ 上传成功: {target_url}"))

        self.stdout.write(self.style.SUCCESS("\n完成。请确认 utils.py 中的 URL 与上述 OSS URL 一致。"))
