#!/usr/bin/env python3
# Глубокий обход ключевых папок Hram: собираем все фотофайлы (jpg/jpeg/png/heic/webp) с путями и размерами
import json, urllib.request, urllib.parse, sys

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}"}

IMG_EXT = (".jpg", ".jpeg", ".png", ".heic", ".webp", ".heif", ".bmp", ".tiff", ".dng")

def ls(path):
    url = "https://cloud-api.yandex.net/v1/disk/resources?path=" + urllib.parse.quote(path) + "&limit=200"
    req = urllib.request.Request(url, headers=H)
    return json.loads(urllib.request.urlopen(req, timeout=60).read())

def walk(path, depth, maxdepth, stats):
    """Возвращает список (path, name, size, ext)"""
    out = []
    try:
        r = ls(path)
    except Exception as e:
        return out
    items = r.get("_embedded", {}).get("items", [])
    for it in items:
        if it["type"] == "dir":
            if depth < maxdepth:
                out += walk(it["path"], depth + 1, maxdepth, stats)
        else:
            name = it["name"].lower()
            if name.endswith(IMG_EXT):
                ext = "." + name.rsplit(".", 1)[1]
                out.append((it["path"], it["name"], it.get("size", 0), ext))
    return out

# обходим ключевые папки
targets = [
    ("/Добротный дом", 4),
    ("/Фото", 4),
    ("/Фотокамера", 3),
    ("/Компьютеры", 5),
    ("/Загрузки", 3),
    ("/Документы", 2),
]
all_photos = {}
for tpath, md in targets:
    photos = walk(tpath, 0, md, {})
    all_photos[tpath] = photos
    total_size = sum(p[2] for p in photos) / 1024 / 1024
    print(f"{tpath}: фото {len(photos)}, {total_size:.0f} МБ")

# сохраняем полный список
with open("/root/site/video/hram_photos_index.json", "w", encoding="utf-8") as f:
    json.dump({k: v for k, v in all_photos.items()}, f, ensure_ascii=False, indent=1)
print("\nИндекс сохранён: /root/site/video/hram_photos_index.json")
