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

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()
H = {"Authorization": f"OAuth {token}"}

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=H)
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read().decode())

def download_href(path):
    url = "https://cloud-api.yandex.net/v1/disk/resources/download?path=" + urllib.parse.quote(path)
    req = urllib.request.Request(url, headers=H)
    with urllib.request.urlopen(req, timeout=60) as r:
        href = json.loads(r.read().decode())["href"]
    req = urllib.request.Request(href)
    with urllib.request.urlopen(req, timeout=120) as r:
        return r.read()

# 1. содержимое папок
for folder in ["/Загрузки/1210 - 9В", "/Загрузки/lmarena"]:
    try:
        d = api(folder)
        items = d.get("_embedded", {}).get("items", [])
        print(f"=== {folder}: {len(items)} элементов")
        for i in items[:15]:
            print(f"   [{i['type']}] {i['name']} ({i.get('size')})")
    except Exception as e:
        print(f"=== {folder}: ошибка {e}")

# 2. PDF-файлы — читаем начало
from pypdf import PdfReader
import tempfile, os
for name in ["2905165.pdf", "6626-gorodnaneve-com.pdf", "files-01.pdf", "o40636_instruction.pdf", "pdf", "Добро Пожаловать.pdf"]:
    try:
        data = download_href("/Загрузки/" + name) if name != "Добро Пожаловать.pdf" else download_href("/" + name)
        if len(data) < 100:
            print(f"=== {name}: файл {len(data)} байт (не PDF?)")
            continue
        try:
            r = PdfReader(io.BytesIO(data))
            txt = (r.pages[0].extract_text() or "")[:250].replace("\n", " ")
            print(f"=== {name} ({len(data)//1024} КБ): {txt}")
        except Exception as e:
            print(f"=== {name}: не PDF-разбор ({len(data)//1024} КБ): {data[:60]!r}")
    except Exception as e:
        print(f"=== {name}: ошибка скачивания {e}")

# 3. План2.jpg — просто переименуем по названию (план дома)
print("=== План2.jpg: план дома (по названию)")
