"""上传文章 004 的所有图片到七牛云 OSS"""

import os
import glob
from qiniu import Auth, put_file, CdnManager

ACCESS_KEY = 't1PIPGcvBY9lJVXFZFb48maTQsGGhvLsR5QQlNq0'
SECRET_KEY = 'KGooFdF5eCLdCIMCOD6x5ofMzu4vYE17T5Mvp9qC'
BUCKET_NAME = 'union-saas'
CDN_DOMAIN = 'https://cdn.union.jxyunge.com'
UPLOAD_PREFIX = 'self-media/004/'


def upload_file(local_path, key):
    """上传单个文件到七牛"""
    q = Auth(ACCESS_KEY, SECRET_KEY)
    token = q.upload_token(BUCKET_NAME, key, 3600)
    ret, info = put_file(token, key, local_path, version='v2')
    if info.status_code == 200:
        url = f'{CDN_DOMAIN}/{key}'
        print(f'  OK {os.path.basename(local_path)} -> {url}')
        return url
    else:
        print(f'  FAIL {os.path.basename(local_path)}: {info}')
        return None


def main():
    img_dir = os.path.join(os.path.dirname(__file__), '..', 'articles', '004')

    # 收集所有 PNG 图片文件
    files = sorted(glob.glob(os.path.join(img_dir, '*.png')))

    urls = []
    results = {}
    for f in files:
        name = os.path.basename(f)
        key = UPLOAD_PREFIX + name
        url = upload_file(f, key)
        if url:
            results[name] = url
            urls.append(url)

    print(f'\n===== 上传完成: {len(results)}/{len(files)} =====')
    for name, url in results.items():
        print(f'{name}: {url}')

    # 刷新 CDN 缓存
    if urls:
        print('\n刷新 CDN 缓存...')
        q = Auth(ACCESS_KEY, SECRET_KEY)
        cdn = CdnManager(q)
        ret, info = cdn.refresh_urls(urls)
        if info.status_code == 200:
            print('CDN 缓存刷新成功')
        else:
            print(f'CDN 刷新失败: {info}')

    return results


if __name__ == '__main__':
    main()
