#!/usr/bin/env python3
"""FOREX-Snusbase-Extraktion Welle 2: eToro/Tradeify/Traedex/StockZ11.
Restart-faehig, Dedupe gegen MASTER + /var/www/dl/data/*.csv."""
import requests, json, os, time, random, csv, glob

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

BIG = ['gmail.com','hotmail.com','yahoo.com','outlook.com','live.com','aol.com',
       'icloud.com','msn.com','protonmail.com','mail.com','yandex.com','yandex.ru',
       'mail.ru','gmx.de','web.de','t-online.de','orange.fr','free.fr','hotmail.fr',
       'libero.it','hotmail.it','yahoo.com.br','uol.com.br','bol.com.br','terra.com.br',
       'yahoo.co.uk','hotmail.co.uk','btinternet.com','sky.com','wanadoo.nl','ziggo.nl',
       'yahoo.de','gmail.de','comcast.net','sbcglobal.net','verizon.net','bellsouth.net',
       'att.net','charter.net','cox.net','earthlink.net']

PLAN = [
    ('etoro_200k', '1598_ETORO_COM_200K_FINANCE_112022', BIG),
    ('tradeify_240k', '2220_TRADEIFY_CO_240K_FINANCE_062026', BIG),
    ('traedex_67k', '2155_TRAEDEX_COM_67K_FINANCE_032026', BIG),
    ('stockz11_48k', '1987_STOCKZ11_COM_48K_FINANCE_042024', BIG),
]

def load_bestand():
    s = set()
    master = os.path.expanduser('~/investoren-daten/retail-investoren-MASTER.csv')
    try:
        with open(master, encoding='utf-8', errors='replace') as f:
            for r in csv.DictReader(f):
                em = (r.get('email') or r.get('Email') or '').strip().lower()
                if '@' in em: s.add(em)
    except Exception:
        pass
    return s

def fetch(table, domain):
    body = {"terms": [domain], "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:
                d = r.json()
                rows = []
                for t, v in (d.get('results') or {}).items():
                    rows.extend(v)
                return rows
            if r.status_code in (429, 500, 502, 503, 504):
                wait = min(20 * (attempt + 1), 120) + random.uniform(0, 4)
                print(f'  {table[:20]} {domain}: HTTP {r.status_code}, warte {wait:.0f}s', flush=True)
                time.sleep(wait); continue
            print(f'  {table[:20]} {domain}: HTTP {r.status_code} {r.text[:120]}', flush=True)
            return None
        except Exception:
            time.sleep(10)
    return None

def main():
    bestand = load_bestand()
    print('Bestand-Emails geladen:', len(bestand), flush=True)
    for key, table, domains in PLAN:
        metaf = os.path.join(OUT, key + '.meta.json')
        meta = {'done_domains': []}
        if os.path.exists(metaf):
            meta = json.load(open(metaf))
        seen = set()
        jl = os.path.join(OUT, key + '.jsonl')
        if os.path.exists(jl):
            for line in open(jl, encoding='utf-8'):
                try:
                    em = (json.loads(line).get('email') or '').lower()
                    if em: seen.add(em)
                except Exception:
                    pass
        out = open(jl, 'a', encoding='utf-8')
        neu_gesamt = 0
        for dom in domains:
            if dom in meta['done_domains']:
                continue
            rows = fetch(table, dom)
            if rows is None:
                print(f'{key} {dom}: FEHLGESCHLAGEN', flush=True)
                continue
            neu = 0
            for row in rows:
                em = (row.get('email') or '').strip().lower()
                if not em or '@' not in em: continue
                if em in bestand or em in seen: continue
                seen.add(em)
                rec = {'quelle': key, 'tabelle': table, **row}
                out.write(json.dumps(rec, ensure_ascii=False) + '\n')
                neu += 1
            neu_gesamt += neu
            meta['done_domains'].append(dom)
            json.dump(meta, open(metaf, 'w'))
            print(f'{key} {dom}: {len(rows)} rows, {neu} neu', flush=True)
            out.flush()
            time.sleep(2)
        out.close()
        print(f'>>> {key} FERTIG: {neu_gesamt} neue Unikate', flush=True)

if __name__ == '__main__':
    main()
