#!/usr/bin/env python3
"""DARURAT TSLaw: cari sumber pemulihan — autosave WordPress, arsip web, dan cache."""
import base64, json, time, urllib.request, urllib.error

DOM = "tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
UA = {"User-Agent": "Mozilla/5.0"}


def wp(path, dom=DOM):
    r = urllib.request.Request(f"https://{dom}{path}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:200]
        except Exception:
            time.sleep(3)
    return 0, "gagal"


print("=== 1. autosave WordPress ===")
st, d = wp("/wp-json/wp/v2/pages/833/autosaves?context=edit")
print(f"   HTTP {st}")
if isinstance(d, list):
    print(f"   {len(d)} autosave")
    for a in d[:10]:
        raw = a.get("content", {}).get("raw", "") if isinstance(a.get("content"), dict) else ""
        print(f"     #{a.get('id')} {a.get('modified')} → {len(raw)} karakter")
else:
    print("   ", str(d)[:200])

print("\n=== 2. revisi semua tipe untuk halaman 833 ===")
for path in ("/wp-json/wp/v2/pages/833/revisions?per_page=50&_fields=id,modified,parent",
             "/wp-json/wp/v2/pages/833?context=edit&_fields=id,modified,date_gmt"):
    st, d = wp(path)
    print(f"   {path.split('?')[0]} → HTTP {st}: {str(d)[:180]}")

print("\n=== 3. arsip web (Wayback) ===")
try:
    u = "https://archive.org/wayback/available?url=tslaw.id&timestamp=20260920"
    with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60) as x:
        j = json.loads(x.read())
    print("   ", json.dumps(j, indent=1)[:400])
except Exception as e:
    print("   gagal:", str(e)[:120])

print("\n=== 4. apakah Google/Cloudflare punya salinan? ===")
for u in ("https://www.tslaw.id/?nocache=1", "https://www.tslaw.id/?v=99"):
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60)
        b = r.read().decode("utf-8", "replace")
        print(f"   {u} → {r.status} | {len(b)//1024} KB | cf={r.headers.get('cf-cache-status')} | "
              f"ada konten lama: {'YA' if 'Kantor Pengacara Terbaik' in b else 'tidak'}")
    except Exception as e:
        print(f"   {u} → gagal {str(e)[:60]}")
