#!/usr/bin/env python3
"""Upload thumbnails pendentes para o YouTube.
Usa as imagens ja geradas em lives/thumbs/
Rodar quando a cota do YouTube resetar (meia-noite PT).
"""
import json, sys, os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
from scheduler import get_access_token, upload_thumbnail

THUMB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lives', 'thumbs')
PENDING_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lives', 'pending_thumbs.json')

with open(PENDING_FILE) as f:
    clips = json.load(f)

success = 0
errors = 0
remaining = []

for i, clip in enumerate(clips, 1):
    vid = clip['id']
    title = clip['title']
    thumb_path = os.path.join(THUMB_DIR, f'{vid}.jpg')

    if not os.path.exists(thumb_path):
        print(f'[{i}/{len(clips)}] SEM IMAGEM: {title[:50]}')
        remaining.append(clip)
        continue

    print(f'[{i}/{len(clips)}] Uploading: {title[:50]}', flush=True)
    try:
        upload_thumbnail(vid, thumb_path)
        success += 1
        print(f'  OK', flush=True)
    except Exception as e:
        err_msg = str(e)
        if 'quota' in err_msg.lower():
            print(f'  QUOTA EXCEDIDA - parando')
            remaining.append(clip)
            remaining.extend(clips[i:])
            break
        errors += 1
        print(f'  ERRO: {e}', flush=True)
        remaining.append(clip)

# Update pending file
with open(PENDING_FILE, 'w') as f:
    json.dump(remaining, f, indent=2, ensure_ascii=False)

print(f'\n=== {success} uploaded, {errors} erros, {len(remaining)} pendentes ===')
