#!/usr/bin/env python3
# Snusbase-Harvest 0992_COINMARKETCAP_COM_3M_CRYPTO_2021 weltweit (restart-fähig)
import requests, json, os, time, sys

AUTH = {'Auth': 'sb9uhv9hleb635srefovmsred6cf9s', 'Content-Type': 'application/json'}
TABLE = '0992_COINMARKETCAP_COM_3M_CRYPTO_2021'
CD = os.path.expanduser('~/krypto-angriff')
OUT = CD + '/raw_cmc'
os.makedirs(OUT, exist_ok=True)
JSONL = OUT + '/cmc_rows.jsonl'
PROG = OUT + '/progress.json'
LOG = OUT + '/extract.log'

WW_BIG = ['gmail.com','yahoo.com','hotmail.com','outlook.com','icloud.com','msn.com','live.com','aol.com',
          'protonmail.com','proton.me','googlemail.com','ymail.com','me.com','gmx.com','yandex.com','mail.ru']
WW_EU  = ['comcast.net','hotmail.co.uk','yahoo.co.uk','libero.it','hotmail.it','free.fr','orange.fr',
           'web.de','gmx.de','rediffmail.com','bol.com.br','uol.com.br','mail.com','t-online.de','tiscali.it','wanadoo.fr','live.fr','sfr.fr']
DOMS = WW_BIG + WW_EU   # 34
DOMS += ['yahoo.de','hotmail.de','freenet.de','arcor.de','gmx.net','yahoo.com.br','yahoo.com.ar',
         'yahoo.com.mx','hotmail.com.ar','terra.com.br','ig.com.br','yahoo.it','virgilio.it','alice.it',
         'hotmail.es','att.net','sbcglobal.net','verizon.net','bellsouth.net','cox.net','qq.com',
         '163.com','naver.com','hanmail.net','yahoo.co.jp','yahoo.co.in','yahoo.com.au','hotmail.com.au']
BATCH = 3
CAP = 200000

prog = json.load(open(PROG)) if os.path.exists(PROG) else {'done': [], 'rows': 0, 'new_emails': 0}
done = set(prog['done'])
seen = set()
if os.path.exists(JSONL + '.emails'):
    for line in open(JSONL + '.emails'):
        seen.add(line.strip())

def logmsg(m):
    line = time.strftime('%H:%M:%S ') + m
    print(line, flush=True)
    with open(LOG, 'a') as f: f.write(line + '\n')

batches = [DOMS[i:i+BATCH] for i in range(0, len(DOMS), BATCH)]
with open(JSONL, 'a') as fj, open(JSONL + '.emails', 'a') as fe:
    for bi, doms in enumerate(batches):
        key = '+'.join(doms)
        if key in done:
            continue
        body = {"terms": doms, "types": ["_domain"], "tables": [TABLE]}
        got = None
        for att in range(5):
            try:
                r = requests.post('https://api.snusbase.com/data/search', json=body, headers=AUTH, timeout=300)
                rem = r.headers.get('x-rate-limit-remaining')
                if r.status_code == 200:
                    d = r.json()
                    res = d.get('results', [])
                    if isinstance(res, dict):
                        got = []
                        for v in res.values():
                            got.extend(v if isinstance(v, list) else [])
                    else:
                        got = res
                    break
                else:
                    logmsg(f'{key} HTTP {r.status_code} rem={rem} att={att}')
                    time.sleep(30 if r.status_code == 429 else 10)
            except Exception as e:
                logmsg(f'{key} ERR {str(e)[:80]}')
                time.sleep(15)
        if got is None:
            logmsg(f'{key} FAILED, skip')
            continue
        new = 0
        for row in got:
            e = (row.get('email') or '').lower().strip()
            if e and '@' in e and e not in seen:
                seen.add(e); new += 1
                fj.write(json.dumps(row, ensure_ascii=False) + '\n')
                fe.write(e + '\n')
        prog['rows'] += len(got)
        prog['new_emails'] += new
        prog['done'].append(key)
        json.dump(prog, open(PROG, 'w'))
        logmsg(f'{key} rows={len(got)} new={new} total_new={prog["new_emails"]}')
        time.sleep(8)
logmsg('HARVEST DONE ' + json.dumps(prog))
