#!/usr/bin/env python3
# LENDENCLUB-Vollextraktion (Tabelle 2039_LENDENCLUB_COM_11M_FINANCE_122023, Snusbase)
# Strategie: rekursives Wildcard-Slicing der E-Mail-Spalte ('a%','ab%',...), da
# _domain-Queries bei 200k Rows gecappt werden (gmail.com allein = 8.875.087 Rows).
# Restart-faehig: Fortschritt in slices_state.json + progress.json, Rohdaten in lenden_raw.jsonl
import requests, json, os, time, random, string, sys

AUTH = {'Auth': 'sb9uhv9hleb635srefovmsred6cf9s', 'Content-Type': 'application/json'}
SEARCH = 'https://api.snusbase.com/data/search'
COUNT = 'https://api.snusbase.com/data/count'
TABLE = '2039_LENDENCLUB_COM_11M_FINANCE_122023'

BASE = os.path.expanduser('~/investoren-daten/crypto_expansion')
OUT = os.path.join(BASE, 'lenden')
os.makedirs(OUT, exist_ok=True)
RAW = os.path.join(OUT, 'lenden_raw.jsonl')
STATE = os.path.join(OUT, 'slices_state.json')
PROGRESS = os.path.join(OUT, 'progress.json')
ERRLOG = os.path.join(OUT, 'errors.log')
LOGJ = os.path.join(OUT, 'extraction-log.jsonl')

CAP = 190000          # Sicherheits-Cap unter dem API-Limit von 200k
MAXDEPTH = 6          # max. Praefixlaenge (deckt selbst degenerierte Verteilungen)
# moegliche erste Zeichen von E-Mails (latin, lowercase - Snusbase normalisiert)
# Hinweis: KEINE Wildcard-Zeichen (%,_,?) als moegliche Mail-Erstzeichen enthalten
CHARS = string.ascii_lowercase + string.digits + "._-+'"

KEEP = ['email', 'phone', 'gender', 'birthdate', 'job', 'uid', 'id', 'created', 'updated']

def log(obj):
    obj['ts'] = time.strftime('%Y-%m-%dT%H:%M:%S')
    with open(LOGJ, 'a') as f:
        f.write(json.dumps(obj, ensure_ascii=False) + '\n')
    print(json.dumps(obj, ensure_ascii=False)[:220], flush=True)

def err(msg):
    with open(ERRLOG, 'a') as f:
        f.write(time.strftime('%Y-%m-%dT%H:%M:%S ') + msg + '\n')

def api(url, body, tries=8):
    for attempt in range(tries):
        try:
            r = requests.post(url, headers=AUTH, json=body, timeout=900)
            if r.status_code == 200:
                return r.json()
            if r.status_code in (429, 500, 502, 503, 504):
                wait = min(20 * (attempt + 1), 300) + random.uniform(0, 5)
                err(f'{url} {body.get("terms")}: HTTP {r.status_code}, warte {wait:.0f}s')
                time.sleep(wait)
                continue
            err(f'{url} {body.get("terms")}: HTTP {r.status_code} {r.text[:200]}')
            return None
        except Exception as e:
            wait = min(20 * (attempt + 1), 300) + random.uniform(0, 5)
            err(f'{url} {body.get("terms")}: EXC {e}, warte {wait:.0f}s')
            time.sleep(wait)
    return None

def wcount(prefix):
    body = {'terms': [prefix + '%'], 'types': ['email'], 'wildcard': True, 'tables': [TABLE]}
    d = api(COUNT, body)
    if d is None:
        return None
    return int(d.get('size') or 0)

def wsearch(prefix):
    body = {'terms': [prefix + '%'], 'types': ['email'], 'wildcard': True, 'tables': [TABLE]}
    d = api(SEARCH, body)
    if d is None:
        return None
    rows = []
    for t, v in (d.get('results') or {}).items():
        rows.extend(v)
    return rows

def save_state(st):
    tmp = STATE + '.tmp'
    json.dump(st, open(tmp, 'w'))
    os.replace(tmp, STATE)

def save_progress(p):
    tmp = PROGRESS + '.tmp'
    json.dump(p, open(tmp, 'w'))
    os.replace(tmp, PROGRESS)

def main():
    st = {'census': {}, 'leaves': [], 'done': [], 'rows_saved': 0, 'emails_seen': 0}
    if os.path.exists(STATE):
        st = json.load(open(STATE))
    p = {'queries_count': 0, 'queries_search': 0, 'slices_done': 0,
         'rows_saved': st.get('rows_saved', 0), 'emails_seen': st.get('emails_seen', 0),
         'started': time.strftime('%Y-%m-%dT%H:%M:%S'), 'finished': None}
    if os.path.exists(PROGRESS):
        old = json.load(open(PROGRESS))
        p.update({k: old.get(k, v) for k, v in p.items() if k not in ('started',)})
        p['started'] = old.get('started', p['started'])

    # ---- Phase 1: Census der Erstzeichen (Summe = Tabellengesamtrows mit E-Mail) ----
    if not st['census']:
        total = 0
        for ch in CHARS:
            n = wcount(ch)
            while n is None:
                n = wcount(ch)
            st['census'][ch] = n
            p['queries_count'] += 1
            total += n
            save_state(st); save_progress(p)
        st['census_total'] = total
        log({'event': 'census-done', 'total_rows': total, 'chars': len(CHARS)})
        if total < 5000000:
            log({'event': 'WARN', 'msg': 'Census-Summe weit unter 11M — Erstzeichen pruefen!', 'total': total})

    # ---- Phase 2: Worklist aufbauen aus Census ----
    if not st['leaves'] and not st['done']:
        st['pending'] = [ch for ch in CHARS if st['census'].get(ch, 0) > 0]
    st.setdefault('pending', [])
    save_state(st)

    seen_emails = set()
    # bereits gesicherte E-Mails einlesen (Restart)
    if os.path.exists(RAW) and os.path.getsize(RAW) > 0:
        with open(RAW, encoding='utf-8') as f:
            for line in f:
                try:
                    seen_emails.add(json.loads(line)['email'])
                except Exception:
                    pass
        log({'event': 'restart', 'emails_seen': len(seen_emails)})

    t0 = time.time()
    while st['pending']:
        prefix = st['pending'].pop(0)
        if prefix in st['done']:
            continue
        n = st['census'].get(prefix)
        if n is None:
            n = wcount(prefix)
            p['queries_count'] += 1
        if n is None:
            st['pending'].insert(0, prefix)  # spaeter erneut
            save_state(st); save_progress(p)
            time.sleep(30)
            continue
        st['census'][prefix] = n
        if n == 0:
            st['done'].append(prefix)
            save_state(st)
            continue
        if n <= CAP or len(prefix) >= MAXDEPTH:
            rows = wsearch(prefix)
            p['queries_search'] += 1
            if rows is None:
                st['pending'].insert(0, prefix)
                save_state(st); save_progress(p)
                time.sleep(30)
                continue
            new = 0
            with open(RAW, 'a', encoding='utf-8') as f:
                for r in rows:
                    em = (r.get('email') or '').strip().lower()
                    if not em or em in seen_emails:
                        continue
                    seen_emails.add(em)
                    slim = {k: r.get(k, '') for k in KEEP}
                    slim['email'] = em
                    f.write(json.dumps(slim, ensure_ascii=False) + '\n')
                    new += 1
            st['done'].append(prefix)
            st['leaves'].append({'prefix': prefix, 'count': n, 'rows': len(rows), 'new': new})
            st['rows_saved'] += len(rows)
            st['emails_seen'] = len(seen_emails)
            p['slices_done'] = len(st['done'])
            p['rows_saved'] = st['rows_saved']
            p['emails_seen'] = st['emails_seen']
            log({'event': 'slice', 'prefix': prefix, 'count': n, 'rows': len(rows), 'new_unique': new,
                 'total_emails': len(seen_emails), 'eta_min': round((time.time()-t0)/60, 1)})
            save_state(st); save_progress(p)
        else:
            # zu gross -> Praefix um ein Zeichen verlaengern
            if len(prefix) >= MAXDEPTH:
                err(f'Praefix {prefix} mit {n} Rows trotz MAXDEPTH — Cap-Verlust moeglich!')
            children = [prefix + c for c in CHARS]
            st['census'][prefix] = n
            st['pending'] = children + st['pending']
            save_state(st)

    p['finished'] = time.strftime('%Y-%m-%dT%H:%M:%S')
    p['emails_seen'] = len(seen_emails)
    p['rows_saved'] = st['rows_saved']
    save_progress(p)
    log({'event': 'FERTIG', 'emails_unique': len(seen_emails), 'slices': len(st['done']),
         'census_total': st.get('census_total')})

if __name__ == '__main__':
    main()
