#!/usr/bin/env python3
# Ручная проверка: скачиваем 1 HEIC и 1 JPG целиком, смотрим EXIF всеми способами
import json, io, os, urllib.request, urllib.parse

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

def get_download_url(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:
        return json.loads(r.read().decode())["href"]

def fetch_full(url):
    req = urllib.request.Request(url)
    with urllib.request.urlopen(req, timeout=120) as r:
        return r.read()

# выбираем по одному файлу каждого типа из индекса
idx = json.load(open("/root/site/video/hram_photos_index.json"))
samples = {}
for folder, items in idx.items():
    for p in items:
        if p[3] == ".heic" and "heic" not in samples:
            samples["heic"] = p
        if p[3] == ".jpg" and "jpg" not in samples:
            samples["jpg"] = p
    if len(samples) >= 2:
        break

for ext, p in samples.items():
    print(f"\n=== {ext}: {p[1]} ({p[2]} байт)")
    href = get_download_url(p[0])
    data = fetch_full(href)
    print(f"  скачано {len(data)} байт")
    # 1) первые 64 байта hex — ищем маркеры
    print("  hex первых 32:", data[:32].hex())
    # 2) exifread
    try:
        import exifread
        tags = exifread.process_file(io.BytesIO(data), details=False)
        gps_tags = {k: str(v) for k, v in tags.items() if "GPS" in k}
        print("  exifread GPS:", gps_tags if gps_tags else "нет")
        # есть ли вообще EXIF
        exif_any = {k: str(v) for k, v in tags.items() if k not in ("JPEGThumbnail",)}
        print("  exifread всего тегов:", len(exif_any))
    except ImportError:
        print("  exifread не установлен")
    except Exception as e:
        print("  exifread ERR:", e)
    # 3) pillow
    try:
        from PIL import Image
        from PIL.ExifTags import TAGS, GPSTAGS
        if ext == ".heic":
            import pillow_heif
            pillow_heif.register_heif_opener()
        img = Image.open(io.BytesIO(data))
        exif = img.getexif()
        print("  PIL тегов EXIF:", len(exif))
        for tag_id, value in exif.items():
            tag = TAGS.get(tag_id, tag_id)
            if tag in ("GPSInfo", "DateTime", "Make", "Model"):
                print(f"    {tag}: {value}")
    except Exception as e:
        print("  PIL ERR:", e)
