#!/usr/bin/env python3
# Раскладка по подпапкам «Внешний вид»/«Планировки» + заливка на Диск + удаление старых корневых файлов
import json, os, shutil, time, urllib.request, urllib.parse

WORK = "/root/site/video/site_renders"
DISK_ROOT = "/Рендеры с сайта"

# Классификация по vision-проверкам: номер файла -> группа
CLASSIFY = {
    "Александрия":        {"ext": ["01", "02", "03"], "plan": ["04"]},
    "Александрия 1":      {"ext": ["01", "02"], "plan": ["03"]},
    "Александрия 2+":     {"ext": ["01", "02"], "plan": ["03", "04"]},
    "Александрия Барн":   {"ext": ["01", "02", "03"], "plan": ["04", "05"]},
    "Баня Ильинская":     {"ext": ["01", "02", "03"], "plan": ["04", "05"]},
    "Барин":              {"ext": ["01", "02", "03", "04"], "plan": ["05", "06", "07", "08"]},
    "Богородский":        {"ext": ["01", "02", "03", "06", "07", "08", "09", "10", "11", "12", "13"], "plan": ["04", "05"]},
    "Вознесенский":       {"ext": ["01", "02", "03"], "plan": ["04"]},
    "Воскресенский":      {"ext": ["01", "02", "03"], "plan": ["04", "05"]},
    "Знаменский":         {"ext": ["01", "02"], "plan": ["03", "04"]},
    "Невский":            {"ext": ["01", "02", "03", "04"], "plan": ["05", "06", "07", "08"]},
    "Радонежский":        {"ext": ["01", "02", "03", "04"], "plan": ["05", "06"]},
    "Рождественский":     {"ext": ["01", "02", "03"], "plan": ["04", "05"]},
    "Сергиевский":        {"ext": ["01", "02", "03"], "plan": ["04", "05"]},
    "Сколковский":        {"ext": ["01", "02", "03", "04"], "plan": ["05", "06"]},
    "Слобода Дуплекс":    {"ext": ["01", "02", "03"], "plan": ["04", "05"]},
    "Спасский":           {"ext": ["01", "02", "03"], "plan": ["04", "05"]},
    "Сторожевский":       {"ext": ["01", "02"], "plan": ["03", "04"]},
    "Тимба":              {"ext": ["01", "02", "03", "04"], "plan": ["05", "06", "07", "08"]},
    "Троицкий":           {"ext": ["01", "02", "05", "06", "07", "08", "09", "10", "11", "12"], "plan": ["03", "04"]},
    "Успенский":          {"ext": ["01", "02", "03"], "plan": ["04", "05"]},
    "Фердинанд":          {"ext": ["01", "02", "03"], "plan": ["04", "05", "06", "07", "08", "09", "10"]},
}

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 disk_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 True
    except urllib.error.HTTPError as e:
        return "already" in e.read().decode(errors="replace")

def disk_upload(local, path):
    url = ("https://cloud-api.yandex.net/v1/disk/resources/upload?path=" +
           urllib.parse.quote(path) + "&overwrite=true")
    req = urllib.request.Request(url, headers=H)
    with urllib.request.urlopen(req, timeout=60) as r:
        href = json.loads(r.read().decode())[ "href"]
    with open(local, "rb") as f:
        data = f.read()
    req = urllib.request.Request(href, data=data, method="PUT")
    with urllib.request.urlopen(req, timeout=180) as r:
        return r.status

def disk_delete(path):
    url = "https://cloud-api.yandex.net/v1/disk/resources?path=" + urllib.parse.quote(path)
    req = urllib.request.Request(url, method="DELETE", headers=H)
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            return r.status
    except urllib.error.HTTPError as e:
        return e.code

report = {}
for proj, groups in CLASSIFY.items():
    pdir = os.path.join(WORK, proj)
    if not os.path.isdir(pdir):
        print("!!! нет папки:", proj); continue
    files = sorted(os.listdir(pdir))
    ext_n, plan_n = 0, 0
    disk_base = f"{DISK_ROOT}/{proj}"
    # локальная раскладка
    for grp, nums in (("Внешний вид", groups["ext"]), ("Планировки", groups["plan"])):
        gdir = os.path.join(pdir, grp)
        os.makedirs(gdir, exist_ok=True)
        for num in nums:
            matches = [f for f in files if f.startswith(num + ".")]
            for m in matches:
                dst = os.path.join(gdir, m)
                if not os.path.exists(dst):
                    shutil.move(os.path.join(pdir, m), dst)
                if grp == "Внешний вид": ext_n += 1
                else: plan_n += 1
    # на Диске: подпапки + заливка + удаление корневых
    for grp, nums in (("Внешний вид", groups["ext"]), ("Планировки", groups["plan"])):
        disk_mkdir(f"{disk_base}/{grp}")
        for num in nums:
            matches = [f for f in files if f.startswith(num + ".")]
            for m in matches:
                local = os.path.join(pdir, grp, m)
                if os.path.exists(local):
                    try:
                        disk_upload(local, f"{disk_base}/{grp}/{m}")
                    except Exception as e:
                        print("  UPLOAD FAIL", proj, m, e)
    # удалить старые файлы из корня папки проекта (на Диске)
    url = "https://cloud-api.yandex.net/v1/disk/resources?path=" + urllib.parse.quote(disk_base) + "&limit=100"
    try:
        items = json.loads(urllib.request.urlopen(urllib.request.Request(url, headers=H), timeout=60).read()).get("_embedded", {}).get("items", [])
        for it in items:
            if it["type"] == "file":
                disk_delete(it["path"])
    except Exception as e:
        print("  LIST FAIL", proj, e)
    report[proj] = {"Внешний вид": ext_n, "Планировки": plan_n}
    print(f"{proj}: внешний вид {ext_n}, планировки {plan_n}")

with open("/root/site/video/site_structure23.json", "w", encoding="utf-8") as f:
    json.dump(report, f, ensure_ascii=False, indent=1)
total = sum(sum(v.values()) for v in report.values())
print("DONE. Проектов:", len(report), "| файлов:", total)
