#!/usr/bin/env python3
"""Baixa candidatas selecionadas de familia 3 pessoas."""
import requests
from pathlib import Path

PEXELS_KEY = "YDqxXGXvOaPQnitSVyxbhghbH49w95DV2fbAkynBjNVvus1TI60Qffdo"
OUT = Path('/opt/mia/workspace/clientes/px3lab/lancamento_photorf2/criativos/pexels_faces/family3')
OUT.mkdir(parents=True, exist_ok=True)

CANDIDATOS = [
    17615677,  # family celebrates graduation with proud parents (BEST: contexto formatura)
    12196195,  # happy family celebrating graduation sunny outdoor
    20889983,  # parents with daughter indoor
    34928345,  # joyful family of three studio
    8841582,   # cheerful family of three sunny outdoor
    35875041,  # joyful family of three forest
    38777037,  # parents hugging smiling child outdoors
    8550665,   # parents and daughter outdoors green
    5416624,   # family togetherness sunset
    9521699,   # family Christmas tree red gowns
    20024372,  # family wedding portrait formal
    18687703,  # father adjusts daughter tiara outdoor
]


def fetch(pid):
    headers = {'Authorization': PEXELS_KEY}
    r = requests.get(f'https://api.pexels.com/v1/photos/{pid}', headers=headers, timeout=30)
    r.raise_for_status()
    return r.json()


def baixar(url, dest):
    r = requests.get(url, timeout=60)
    r.raise_for_status()
    Path(dest).write_bytes(r.content)
    return len(r.content)


if __name__ == '__main__':
    for pid in CANDIDATOS:
        try:
            data = fetch(pid)
            alt = data.get('alt', '')[:80]
            src = data['src']
            url_large = src.get('large2x') or src.get('large') or src.get('original')
            dest = OUT / f'{pid}.jpg'
            sz = baixar(url_large, dest)
            print(f'{pid}: {dest.name} ({sz//1024}KB) w={data.get("width")} h={data.get("height")} alt="{alt}"')
        except Exception as e:
            print(f'{pid}: FAIL {e}')
