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

# load token
token = None
for line in open("/root/site/yandex/.env", encoding="utf-8"):
    line = line.strip()
    if line.startswith("YANDEX_ACCESS_TOKEN="):
        token = line.split("=", 1)[1].strip()
if not token:
    print("NO TOKEN"); sys.exit(1)

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

def list_dir(path):
    d = api(path)
    items = d.get("_embedded", {}).get("items", [])
    return [(i["type"], i["name"], i.get("size"), i.get("file")) for i in items]

print("=== ROOT ===")
for t, n, s, f in list_dir("/"):
    print(f"  [{t}] {n}  ({s} bytes)")

# find target folder
target = None
for t, n, s, f in list_dir("/"):
    if t == "dir" and "добротн" in n.lower() and "рендер" in n.lower():
        target = n
        break
if not target:
    # try looser match
    for t, n, s, f in list_dir("/"):
        if t == "dir" and "добротн" in n.lower():
            target = n; break
if not target:
    print("FOLDER 'добротный дом рендеры' NOT FOUND in root")
    sys.exit(2)
print(f"\n=== FOUND: {target} ===")
sub = None
for t, n, s, f in list_dir("/" + target):
    print(f"  [{t}] {n}  ({s} bytes)")
    if t == "dir" and "троицк" in n.lower():
        sub = n
if not sub:
    print("SUBFOLDER 'троицкий' NOT FOUND"); sys.exit(3)
print(f"\n=== SUBFOLDER: {sub} ===")
files = list_dir("/" + target + "/" + sub)
for t, n, s, f in files:
    print(f"  [{t}] {n}  ({s} bytes)  file_url={'yes' if f else 'no'}")
