"""上传图片到七牛云 OSS"""

import os
import glob
from qiniu import Auth, put_file

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


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', '001', 'images')
    files = sorted(glob.glob(os.path.join(img_dir, '*.png')))

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

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

    return results


if __name__ == '__main__':
    main()
