#!/usr/bin/env python3
import json, urllib.request, urllib.parse, os, sys, time

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

def api_get(path):
    url = "https://cloud-api.yandex.net/v1/disk/resources?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())

def api_mkdir(path):
    url = "https://cloud-api.yandex.net/v1/disk/resources?path=" + urllib.parse.quote(path)
    req = urllib.request.Request(url, method="PUT", headers=H)
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            return json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        if "alreadyExists" in body:
            return {"already": True}
        print("MKDIR FAIL", path, e.code, body[:200]); return None

def api_copy(src, dst):
    url = ("https://cloud-api.yandex.net/v1/disk/resources/copy?"
           "from=" + urllib.parse.quote(src, safe="") +
           "&path=" + urllib.parse.quote(dst, safe=""))
    req = urllib.request.Request(url, method="POST", headers=H)
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            return json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        print("COPY FAIL", src, "->", dst, e.code, e.read().decode()[:150]); return None

SRC_ROOT = "/Добротный дом рендеры"
DST_ROOT = "/Рендеры с сайта"

# 1. projects
d = api_get(SRC_ROOT)
projects = [i["name"] for i in d.get("_embedded", {}).get("items", []) if i["type"] == "dir"]
print("Проектов:", len(projects))

# 2. create destination root
api_mkdir(DST_ROOT)

IMG_EXT = (".jpg", ".jpeg", ".png", ".webp", ".bmp")
stats = {}
for p in projects:
    sub = api_get(SRC_ROOT + "/" + p)
    imgs = [i for i in sub.get("_embedded", {}).get("items", [])
            if i["type"] == "file" and i["name"].lower().endswith(IMG_EXT)]
    if not imgs:
        stats[p] = 0
        continue
    dst_dir = DST_ROOT + "/" + p
    api_mkdir(dst_dir)
    ok = 0
    for img in imgs:
        src_full = SRC_ROOT + "/" + p + "/" + img["name"]
        dst_full = dst_dir + "/" + img["name"]
        api_copy(src_full, dst_full)
        ok += 1
        time.sleep(0.15)
    stats[p] = ok
    print(f"  {p}: {ok} файлов")

total = sum(stats.values())
print("ИТОГО скопировано:", total)
with open("/root/site/video/disk_stats.json", "w", encoding="utf-8") as f:
    json.dump({"projects": stats, "total": total}, f, ensure_ascii=False, indent=1)
print("DONE")
