#!/usr/bin/env python3
"""Coba unduh beberapa kandidat gambar TSC dengan beberapa cara (untuk tahu kenapa 404)."""
import base64, importlib.util, json, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()

IDS = [9500, 9052, 8471]
h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
for mid in IDS:
    r = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/media/{mid}?_fields=id,source_url,media_details,mime_type", headers=h)
    try:
        d = json.loads(urllib.request.urlopen(r, timeout=90).read())
    except Exception as e:
        print(f"#{mid} gagal baca: {str(e)[:60]}")
        continue
    url = d.get("source_url")
    md = d.get("media_details") or {}
    print(f"\n#{mid} {d.get('mime_type')} {md.get('width')}x{md.get('height')}")
    print(f"   {url}")
    ukuran = (md.get("sizes") or {})
    for nama in ("medium_large", "large", "full", "medium"):
        if nama in ukuran:
            print(f"   {nama}: {ukuran[nama].get('source_url')}")
            break
    for label, kepala in (("polos", {}), ("dengan referer", {"Referer": f"https://www.{DOM}/"}),
                          ("login", {"Authorization": f"Basic {AUTH}"})):
        try:
            with urllib.request.urlopen(urllib.request.Request(
                    url, headers={"User-Agent": "Mozilla/5.0", **kepala}), timeout=45) as x:
                print(f"   unduh {label:<14} HTTP {x.status} · {len(x.read())//1024} KB")
                break
        except urllib.error.HTTPError as e:
            print(f"   unduh {label:<14} HTTP {e.code}")
        except Exception as e:
            print(f"   unduh {label:<14} {str(e)[:40]}")
        time.sleep(1)
