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

token = None
for line in open("/root/site/yandex/.env_hram", encoding="utf-8"):
    if line.startswith("YANDEX2_ACCESS_TOKEN="):
        token = line.split("=", 1)[1].strip()

def api(path):
    url = "https://cloud-api.yandex.net/v1/disk/resources?path=" + urllib.parse.quote(path) + "&limit=100"
    req = urllib.request.Request(url, headers={"Authorization": f"OAuth {token}"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read().decode())

def human(n):
    if n is None: return "?"
    for u in ["Б", "КБ", "МБ", "ГБ"]:
        if n < 1024: return f"{n:.0f} {u}"
        n /= 1024
    return f"{n:.1f} ТБ"

def join(p, name):
    return (p.rstrip("/") + "/" + name) if p != "/" else "/" + name

def scan(path, depth=0, maxdepth=2, out=None):
    try:
        d = api(path)
    except Exception as e:
        out.append("  "*depth + f"[ошибка] {path}: {e}")
        return
    items = d.get("_embedded", {}).get("items", [])
    for i in items:
        name = i["name"]
        size = i.get("size")
        if i["type"] == "dir":
            out.append("  "*depth + f"📁 {name}  ({human(size)})")
            if depth < maxdepth:
                scan(join(path, name), depth + 1, maxdepth, out)
        else:
            out.append("  "*depth + f"📄 {name}  ({human(size)})")

out = []
scan("/", 0, 1, out)
print("\n".join(out[:120]))
