#!/usr/bin/env python3
"""FOREX-Snusbase-Extraktion: neue Forex-/Trader-Tabellen + zusaetzliche Daytrading-Slices.
Restart-faehig, Dedupe gegen MASTER + /var/www/dl/data/*.csv."""
import requests, json, os, time, random, csv, sys

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)

RU = ['yandex.ru','yandex.com','mail.ru','bk.ru','list.ru','inbox.ru','rambler.ru','gmail.com',
      'hotmail.com','yahoo.com','outlook.com','ukr.net','mail.ua','tut.by','gmx.de','web.de']
INTL = ['gmail.com','yahoo.com','hotmail.com','outlook.com','live.com','aol.com','icloud.com',
        'msn.com','protonmail.com','yandex.com','mail.com']
DAYTRADING_NEU = ['gmx.de','web.de','t-online.de','freenet.de','googlemail.com','me.com',
                 'ymail.com','rediffmail.com','libero.it','hotmail.it','alice.it','tiscali.it',
                 'wanadoo.nl','zeelandnet.nl','upcmail.nl','skynet.be','telenet.be','hotmail.be',
                 'live.be','vodafone.de','arcor.de','online.de','terra.com.br','uol.com.br',
                 'bol.com.br','ig.com.br','yahoo.com.br','hotmail.com.ar','yahoo.com.ar',
                 'yahoo.com.mx','hotmail.es','telefonica.net','terra.es','yahoo.es','ya.ru']

PLAN = [
    ('forexdengi_ru', '1021_FOREXDENGI_COM_62K_FINANCE_092012', RU, 'forex'),
    ('srimurugan_sg', '1601_SRIMURUGANTRADING_COMSG_24K_FINANCE_012023', INTL, 'forex'),
    ('forexelate', '1340_FOREXELATE_COM_40_FINANCE_102019', ['gmail.com','yahoo.com'], 'forex'),
    ('demoforex', '1614_DEMOFOREXTRADING_COM_109_FINANCE_022022', ['gmail.com','yahoo.com','hotmail.com'], 'forex'),
    ('generalbroker_bg', '0910_GENERALBROKER_BG_498_INSURANCE_122020', ['gmail.com','abv.bg','yahoo.com','hotmail.com'], 'forex'),
    ('daytrading_fx', '0525_DAYTRADING_COM_1M_FINANCE_2018', DAYTRADING_NEU, 'forex'),
]

def load_bestand():
    """Emails aus MASTER + allen ausgelieferten CSVs."""
    s = set()
    master = os.path.expanduser('~/investoren-daten/retail-investoren-MASTER.csv')
    for path in [master] + sorted(__import__('glob').glob('/var/www/dl/data/*.csv')):
        try:
            with open(path, 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 as e:
            print('skip', path, e)
    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=300)
            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 as e:
            time.sleep(10)
    return None

def main():
    bestand = load_bestand()
    print('Bestand-Emails geladen:', len(bestand), flush=True)
    for key, table, domains, kat 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)
            time.sleep(2)
        out.close()
        print(f'>>> {key} FERTIG: {neu_gesamt} neue Unikate', flush=True)

if __name__ == '__main__':
    main()
