#!/usr/bin/env python3
# Превью для кластеров C2, C3, C4, C12 — качаем больше данных (старые JPG 2015)
import json, io, os, urllib.request, urllib.parse
from PIL import Image, ImageDraw

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=1_500_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:
    cid = cl["cluster"]
    if cid not in (2, 3, 4, 12):
        continue
    keys = cl["keys"]
    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}: {str(e)[:60]}")
    if not imgs:
        print(f"C{cid}: НЕТ превью"); continue
    n = len(imgs); cols = min(4, n); rows = (n + cols - 1) // cols
    sheet = Image.new("RGB", (cols*330, rows*250), "white")
    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'][:45]}")
