#!/usr/bin/python3
"""DAYTRADING-NEUJAGD Snusbase-Vollextraktion: unbenutzte Trading-/Finance-Tabellen.
Restart-faehig, JSONL je Quelle, 429-Backoff, sanft (2-3s Jitter)."""
import requests, json, os, time, random, sys

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

DE = ['web.de','gmx.de','gmx.net','t-online.de','freenet.de','arcor.de','online.de',
      'googlemail.com','t-online.at','aon.at','bluewin.ch','gmx.ch','hotmail.de','yahoo.de']
BIG = ['gmail.com','hotmail.com','yahoo.com','outlook.com','live.com','aol.com',
       'icloud.com','msn.com','me.com','protonmail.com','proton.me','googlemail.com']
EU = ['mail.com','yandex.com','libero.it','hotmail.it','free.fr','orange.fr','wanadoo.fr',
      'hotmail.fr','sfr.fr','yahoo.co.uk','hotmail.co.uk','btinternet.com','sky.com',
      'wanadoo.nl','ziggo.nl','hotmail.nl','skynet.be','telenet.be','hotmail.be','live.be',
      'terra.com.br','uol.com.br','bol.com.br','ig.com.br','yahoo.com.br','hotmail.com.br',
      'yahoo.com.ar','hotmail.com.ar','fibertel.com.ar','yahoo.com.mx','hotmail.es','terra.es',
      'yahoo.es','telefonica.net','rediffmail.com','yahoo.co.in','hotmail.co.in','mail.ru',
      'yandex.ru','bk.ru','list.ru','rambler.ru','ukr.net','hotmail.com.tr','yahoo.com.tr',
      'mynet.com','yahoo.com.ph','comcast.net','sbcglobal.net','verizon.net','bellsouth.net',
      'att.net','charter.net','cox.net','earthlink.net','rocketmail.com','ymail.com',
      'yahoo.com.au','hotmail.com.au','yahoo.ca','hotmail.ca','yahoo.co.nz','xtra.co.nz']

PLAN = [
    ('btsave',      '1952_BTSAVE_IO_102K_CRYPTO_082021'),
    ('atlasquantum','0533_ATLASQUANTUM_COM_250K_CRYPTO_2018'),
    ('firstcoin',   '1922_1STCOIN_IO_116K_CRYPTO_2022'),
    ('marketsmojo', '1770_MARKETSMOJO_COM_496K_FINANCE_2021'),
    ('speedtrader', '0949_SPEEDTRADER_COM_52K_FINANCE_2017'),
    ('forexpak',    '0957_FOREXPAK_COM_61K_FINANCE_102020'),
    ('investorbg',  '1345_INVESTOR_BG_59K_FINANCE_102019'),
    ('moneycontrol','1055_MONEYCONTROL_COM_781K_FINANCE_092017'),
    ('teslainvest', '1691_TESLAINVEST_CZ_15K_FINANCE_2022'),
    ('hisseanaliz','1404_HISSEANALIZ_NET_52K_FINANCE_102019'),
    ('coinmama',    '0590_COINMAMA_COM_478K_CRYPTO_062017'),
    ('coinpayex',   '1001_COINPAYEX_LTD_609K_CRYPTO_102021'),
    ('bitmart',     '2143_BITMART_COM_763K_CRYPTO_202X'),
    ('gemini',      '1248_GEMINI_COM_5536K_CRYPTO_2022'),
    ('moneybookers','0520_MONEYBOOKERS_COM_5M_FINANCE_2009'),
]

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

def fetch(table, terms):
    body = {'terms': terms, 'types': ['_domain'], 'tables': [table]}
    for attempt in range(6):
        try:
            r = requests.post(SEARCH, headers=AUTH, json=body, timeout=600)
            if r.status_code == 200:
                rows=[]
                for t,v in (r.json().get('results') or {}).items(): rows.extend(v)
                return rows
            if r.status_code in (429,500,502,503,504):
                wait = min(20*(attempt+1),180)+random.uniform(0,5)
                log({'ev':'http','table':table[:22],'code':r.status_code,'wait':round(wait)})
                time.sleep(wait); continue
            log({'ev':'http','table':table[:22],'code':r.status_code,'body':r.text[:100]})
            return None
        except Exception as e:
            time.sleep(10)
    return None

def batches(doms):
    big = [d for d in doms if d in BIG or d in ('gmail.com','hotmail.com','yahoo.com','outlook.com','icloud.com','mail.ru','yandex.ru')]
    small = [d for d in doms if d not in big]
    out = []
    for i in range(0,len(big),3): out.append(big[i:i+3])
    for i in range(0,len(small),15): out.append(small[i:i+15])
    return out

for key, table in PLAN:
    jf = os.path.join(OUT, key+'.jsonl')
    mf = os.path.join(OUT, key+'.meta.json')
    done = set()
    n_rows = 0
    if os.path.exists(mf):
        m = json.load(open(mf)); done = set(m.get('done',[])); n_rows = m.get('rows',0)
    # Domainreihenfolge: DE zuerst, dann BIG, dann EU/regional
    allb = batches(DE) + batches([d for d in BIG if d not in DE]) + batches([d for d in EU if d not in DE])
    for bi, b in enumerate(allb):
        bid = '|'.join(b)
        if bid in done: continue
        rows = fetch(table, b)
        if rows is None:
            log({'ev':'giveup','key':key,'batch':bid[:60]}); continue
        with open(jf,'a',encoding='utf-8') as f:
            for r in rows: f.write(json.dumps(r,ensure_ascii=False)+'\n')
        n_rows += len(rows)
        done.add(bid)
        json.dump({'done':sorted(done),'rows':n_rows,'table':table},open(mf,'w'))
        log({'ev':'ok','key':key,'batch':bid[:60],'got':len(rows),'total':n_rows,'b':f'{bi+1}/{len(allb)}'})
        time.sleep(random.uniform(2,3.5))
    log({'ev':'source_done','key':key,'rows':n_rows})
print('FERTIG')
