import json, time, urllib.parse, urllib.request, sys

TOKEN = open('/tmp/carrossel-clima/.tok').read().strip()
IG = '17841477402712235'
API = 'https://graph.facebook.com/v25.0'
BASE = 'https://vps.sinocomunicacao.com.br/oo-capas/img/'
imgs = ['cs01-87dc9f0ebafcd636.jpg'] + open('/tmp/carrossel-clima/nomes.txt').read().split()
caption = open('/tmp/carrossel-clima/legenda.txt').read().strip()

def call(method, path, params):
    params = dict(params, access_token=TOKEN)
    data = urllib.parse.urlencode(params).encode()
    if method == 'GET':
        req = urllib.request.Request(f'{API}/{path}?{data.decode()}')
    else:
        req = urllib.request.Request(f'{API}/{path}', data=data, method='POST')
    try:
        with urllib.request.urlopen(req, timeout=90) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        print('ERRO', path, e.read().decode()[:500]); sys.exit(1)

print('conta:', call('GET', IG, {'fields': 'username'}).get('username'))
assert len(imgs) == 8, imgs
children = []
for n in imgs:
    r = call('POST', f'{IG}/media', {'image_url': BASE + n, 'is_carousel_item': 'true'})
    children.append(r['id']); print('item', n, r['id'])
car = call('POST', f'{IG}/media', {'media_type': 'CAROUSEL', 'children': ','.join(children), 'caption': caption})
cid = car['id']; print('carousel', cid)
for _ in range(30):
    st = call('GET', cid, {'fields': 'status_code'}).get('status_code')
    print('status', st)
    if st == 'FINISHED': break
    if st == 'ERROR': sys.exit('container com erro')
    time.sleep(5)
pub = call('POST', f'{IG}/media_publish', {'creation_id': cid})
mid = pub['id']; print('publicado', mid)
print('permalink', call('GET', mid, {'fields': 'permalink'}).get('permalink'))
