#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Unduh kandidat foto Pexels (id dari pencarian via r.jina.ai) dan buat contact sheet berlabel."""
import os
import sys

import requests
from PIL import Image, ImageDraw, ImageFont

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tsc_ads_sample"
os.makedirs(OUT, exist_ok=True)
IDS = sys.argv[1:]

font = ImageFont.truetype("/home/mantapman/.fonts/Poppins-Bold.ttf", 34)
files = []
for i, pid in enumerate(IDS, 1):
    path = os.path.join(OUT, f"pex_{i:02d}_{pid}.jpg")
    if not os.path.exists(path):
        url = (f"https://images.pexels.com/photos/{pid}/pexels-photo-{pid}.jpeg"
               f"?auto=compress&cs=tinysrgb&w=1400")
        try:
            r = requests.get(url, timeout=60, headers={"User-Agent": "Mozilla/5.0"})
            if r.status_code != 200 or len(r.content) < 5000:
                print(f"{i:02d} {pid}: GAGAL {r.status_code} {len(r.content)}")
                continue
            with open(path, "wb") as f:
                f.write(r.content)
        except Exception as e:
            print(f"{i:02d} {pid}: {e}")
            continue
    with Image.open(path) as im:
        print(f"{i:02d} | {pid} | {im.size[0]}x{im.size[1]} | rasio {im.size[0]/im.size[1]:.2f}")
    files.append((i, path))

lebar, tinggi, kolom = 340, 460, 4
baris = (len(files) + kolom - 1) // kolom
sheet = Image.new("RGB", (lebar * kolom, tinggi * baris), (18, 18, 18))
d = ImageDraw.Draw(sheet)
for n, (i, path) in enumerate(files):
    with Image.open(path) as im:
        im = im.convert("RGB")
        rasio = min(lebar / im.width, tinggi / im.height)
        im = im.resize((int(im.width * rasio), int(im.height * rasio)), Image.LANCZOS)
        x = (n % kolom) * lebar + (lebar - im.width) // 2
        y = (n // kolom) * tinggi + (tinggi - im.height) // 2
        sheet.paste(im, (x, y))
        d.rectangle([x, y, x + 96, y + 46], fill=(0, 0, 0))
        d.text((x + 10, y + 6), f"{i:02d}", font=font, fill=(255, 210, 60))
sheet.save(os.path.join(OUT, "sheet_pexels.jpg"), quality=88)
print("sheet:", os.path.join(OUT, "sheet_pexels.jpg"), sheet.size)
