#!/usr/bin/env python3
# Контактные листы по кластерам: скачиваем по 1-2 фото из каждого кластера (первые 200 КБ -> preview)
import json, io, os, urllib.request, urllib.parse, math
from PIL import Image

tok = None
for line in open("/root/site/yandex/.env_hram", encoding="utf-8"):
    if line.startswith("YANDEX2_ACCESS_TOKEN="):
        tok = line.split("=", 1)[1].strip()
H = {"Authorization": f"OAuth {tok}"}

def get_download_url(path):
    url = "https://cloud-api.yandex.net/v1/disk/resources/download?path=" + urllib.parse.quote(path)
    req = urllib.request.Request(url, headers=H)
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read().decode())["href"]

def fetch(url, maxb=300_000):
    req = urllib.request.Request(url, headers={"Range": f"bytes=0-{maxb-1}"})
    with urllib.request.urlopen(req, timeout=90) as r:
        return r.read()

clusters = json.load(open("/root/site/video/clusters_geocoded.json", encoding="utf-8"))
cache = json.load(open("/root/site/video/gps_cache2.json", encoding="utf-8"))

OUT = "/root/site/video/cluster_previews"
os.makedirs(OUT, exist_ok=True)

import pillow_heif
pillow_heif.register_heif_opener()

for cl in clusters:
    if cl["count"] < 2:
        continue
    cid = cl["cluster"]
    keys = cl["keys"]
    # берём 4 файла равномерно
    step = max(1, len(keys) // 4)
    picks = [keys[i] for i in range(0, len(keys), step)][:4]
    imgs = []
    for k in picks:
        try:
            href = get_download_url(k)
            data = fetch(href)
            im = Image.open(io.BytesIO(data)).convert("RGB")
            im.thumbnail((320, 240), Image.LANCZOS)
            imgs.append((cache[k]["name"], im))
        except Exception as e:
            print(f"  C{cid} skip {k}: {e}")
    if not imgs:
        continue
    n = len(imgs)
    cols = min(4, n)
    rows = (n + cols - 1) // cols
    sheet = Image.new("RGB", (cols*330, rows*250), "white")
    from PIL import ImageDraw
    d = ImageDraw.Draw(sheet)
    for i, (name, im) in enumerate(imgs):
        x = (i % cols) * 330 + 5
        y = (i // cols) * 250 + 5
        sheet.paste(im, (x, y))
        d.rectangle([x, y+210, x+320, y+230], fill="black")
        d.text((x+4, y+212), name[:35], fill="white")
    path = os.path.join(OUT, f"cluster_{cid}_{cl['count']}.jpg")
    sheet.save(path, quality=85)
    print(f"C{cid}: {cl['count']} фото -> {os.path.basename(path)} | {cl['addr'][:50]}")
