#!/usr/bin/env python3
# PRESALE-JAGD: Snusbase-Pulls (restart-faehig) fuer presale-affine Tabellen
# 0992_CoinMarketCap_3M (Krypto-Research-Plattform = presale-affin), 1108_CHAIN_LINK (ICO-Teilnehmer),
# 0536_COLLECTION1_BTC_23M (BTC-Kombo). Adaptive Wildcard-Slices, 200k-Cap, Rate-Limit-Backoff.
import requests, json, os, time, sys

AUTH = {'Auth': 'sb9uhv9hleb635srefovmsred6cf9s', 'Content-Type': 'application/json'}
SEARCH = 'https://api.snusbase.com/data/search'
OUT = os.path.expanduser('~/investoren-daten/presale/snus')
os.makedirs(OUT, exist_ok=True)
LOG = os.path.join(OUT, 'pull_log.jsonl')
PROG = os.path.join(OUT, 'progress.json')

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

def load_prog():
    return json.load(open(PROG)) if os.path.exists(PROG) else {'done': {}}

def save_prog(p):
    json.dump(p, open(PROG, 'w'))

def search(terms, table, wildcards=True, timeout=900):
    body = {"terms": terms, "types": ["email"], "tables": [table], "group_by": False}
    if wildcards: body["wildcard"] = True
    for attempt in range(10):
        try:
            r = requests.post(SEARCH, headers=AUTH, json=body, timeout=timeout)
            rem = r.headers.get('x-rate-limit-remaining')
            if r.status_code == 200:
                return r.json(), int(rem) if rem else None
            if r.status_code == 429:
                reset = int(r.headers.get('x-rate-limit-reset', '120'))
                log({'ev': '429', 'reset': reset})
                time.sleep(min(reset + 30, 3700)); continue
            if r.status_code == 500:
                log({'ev': '500', 'terms': terms}); time.sleep(20); continue
            log({'ev': 'http', 'code': r.status_code, 'body': r.text[:120]})
            time.sleep(15)
        except Exception as e:
            log({'ev': 'exc', 'err': str(e)[:120]}); time.sleep(20)
    return None, None

def rows_of(d):
    res = d.get('results')
    if res is None: return []
    if isinstance(res, list): return list(res)
    out = []
    for t, lst in res.items():
        for row in lst: out.append(row)
    return out

def pull_table(key, table, prefixes, min_keep=1000, max_queries=None, batch_small=4, batch_letters=False):
    """Ziehe Tabelle via E-Mail-Wildcard-Prefixes; bei Cap (>=195k) adaptiv splitten.
    2-Zeichen-Prefixes (Term-Laenge >=3 mit %) werden gebatcht um Rate-Tokens zu sparen.
    Ergebnisse als JSONL in OUT/<key>.jsonl (Zeile = Row-Dict)."""
    prog = load_prog()
    fn = os.path.join(OUT, key + '.jsonl')
    done = prog['done'].setdefault(key, {'prefixes': [], 'rows': 0})
    seen_prefixes = set(done['prefixes'])
    total_new = done['rows']
    nq = 0
    def add_rows(rows, prefixes_done):
        nonlocal total_new
        with open(fn, 'a') as f:
            for row in rows: f.write(json.dumps(row) + '\n')
        total_new += len(rows)
        for p in prefixes_done: seen_prefixes.add(p)
        done['prefixes'] = sorted(seen_prefixes); done['rows'] = total_new
        save_prog(prog)

    queue = [[p] for p in prefixes if p not in seen_prefixes]
    no_rebatch = set()  # Terme, die aus einem capped Batch entnommen wurden

    def make_ext(p):
        """Splitte Prefix 'xy%' in ['xx%','xy%','xz%',...] (2-stellige Basis)."""
        base = p[:-1]
        CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_-.'
        return [base + c + '%' for c in CHARS]

    while queue:
        batch = queue.pop(0)
        if all(p in seen_prefixes for p in batch): continue
        # einzelne kleine Prefixes zu Batches zusammenfassen
        def _batchable(t):
            return (len(t) >= 3 or (batch_letters and len(t) >= 2)) and t not in no_rebatch
        if len(batch) == 1 and _batchable(batch[0]):
            while len(batch) < batch_small and queue and len(queue[0]) == 1 and _batchable(queue[0][0]) and len(queue[0][0]) == len(batch[0]):
                batch.append(queue.pop(0)[0])
        if max_queries and nq >= max_queries:
            log({'ev': 'maxq', 'key': key}); break
        d, rem = search(batch, table)
        nq += 1
        if d is None:
            log({'ev': 'fail', 'terms': batch, 'key': key}); time.sleep(5); continue
        rows = rows_of(d)
        n = len(rows)
        capped = n >= 195000
        if capped and len(batch) == 1 and len(batch[0]) <= 4:
            p = batch[0]
            ext = make_ext(p)
            # Extensions gleichmaessig vorbatchen (gruppe von batch_small)
            groups = [ext[i:i + batch_small] for i in range(0, len(ext), batch_small)]
            queue = groups + queue
            log({'ev': 'split', 'prefix': p, 'rows': n, 'rem': rem})
        elif capped and len(batch) > 1:
            # Batch zu gross: in Einzelterme zerlegen (nicht wieder zusammenfuehren)
            for t in batch:
                no_rebatch.add(t)
            queue = [[t] for t in batch] + queue
            log({'ev': 'unbatch', 'terms': batch, 'rows': n, 'rem': rem})
        else:
            add_rows(rows, batch)
            log({'ev': 'ok', 'terms': batch, 'rows': n, 'total': total_new, 'rem': rem})
        if rem is not None and rem < 100:
            log({'ev': 'lowrate', 'rem': rem}); break
        time.sleep(1.5)
    log({'ev': 'end', 'key': key, 'total': total_new, 'queries': nq})

if __name__ == '__main__':
    which = sys.argv[1] if len(sys.argv) > 1 else 'all'
    LET = [c + '%' for c in 'abcdefghijklmnopqrstuvwxyz0123456789_-.']
    if which in ('cmc', 'all'):
        pull_table('cmc', '0992_COINMARKETCAP_COM_3M_CRYPTO_2021', LET)
    if which in ('chainlink', 'all'):
        pull_table('chainlink', '1108_CHAIN_LINK_6057_CRYPTO_202X', LET, batch_small=26)
    if which in ('opensea', 'all2'):
        pull_table('opensea', '2144_OPENSEA_IO_6108K_CRYPTO_202X', LET)
    if which in ('everycoin', 'all2'):
        pull_table('everycoin', '1276_EVERYCOIN_IO_288K_CRYPTO_022019', LET)
    if which in ('btce', 'all2'):
        pull_table('btce', '0466_BTCE_COM_700K_CRYPTO_2017', LET)
    if which in ('robinhood', 'all2'):
        pull_table('robinhood', '1157_ROBINHOOD_COM_7213K_FINANCE_112021', LET)
    if which in ('coll1', 'all'):
        pull_table('coll1', '0536_COLLECTION1_BTC_23M_FINANCE_2019', LET, max_queries=int(sys.argv[2]) if len(sys.argv) > 2 else None)
