#!/usr/bin/env python3
# Snusbase _domain-Sweep fuer Krypto-Exchange-Domains (KRYPTO-PLATTFORMEN 2026-11-08)
# Sucht in ALLEN Tabellen nach Zeilen mit E-Mails der Domain (Exchange-Mitarbeiter/Insider-Kontakte).
import requests, json, os, time, sys

AUTH = {'Auth': 'sb9uhv9hleb635srefovmsred6cf9s', 'Content-Type': 'application/json'}
SEARCH = 'https://api.snusbase.com/data/search'
OUT = os.path.expanduser('~/krypto-angriff/snusbase_sweeps')
os.makedirs(OUT, exist_ok=True)
DOMAINS = ['coinbase.com', 'coingecko.com', 'binance.com', 'bitpanda.com',
           'bitpanda.de', 'kraken.com', 'kucoin.com', 'crypto.com']
PROGRESS = os.path.join(OUT, 'progress.json')

def search(dom, tables=None, timeout=900):
    body = {"terms": [dom], "types": ["_domain"]}
    if tables: body["tables"] = tables
    for attempt in range(8):
        try:
            r = requests.post(SEARCH, headers=AUTH, json=body, timeout=timeout)
            if r.status_code == 200:
                return r.json()
            if r.status_code == 429:
                time.sleep(20 * (attempt + 1)); continue
            print(f'  {dom}: HTTP {r.status_code} {r.text[:150]}', flush=True)
            time.sleep(10)
        except Exception as e:
            print(f'  {dom}: exc {e}', flush=True); time.sleep(15)
    return None

prog = json.load(open(PROGRESS)) if os.path.exists(PROGRESS) else {}
for dom in DOMAINS:
    if dom in prog:
        continue
    print(f'== {dom}', flush=True)
    d = search(dom)
    if d is None:
        prog[dom] = 'failed'; json.dump(prog, open(PROGRESS, 'w')); continue
    fn = os.path.join(OUT, dom + '.json')
    json.dump(d, open(fn, 'w'))
    res = d.get('results') or {}
    total = sum(len(v) for v in res.values())
    tabs = {t: len(v) for t, v in res.items() if v}
    print(f'  {dom}: {total} Zeilen in {len(tabs)} Tabellen', flush=True)
    for t, n in sorted(tabs.items(), key=lambda x: -x[1])[:8]:
        print(f'    {n:6d}  {t}', flush=True)
    prog[dom] = {'rows': total, 'tables': len(tabs)}
    json.dump(prog, open(PROGRESS, 'w'))
    time.sleep(3)
print('DONE', json.dumps(prog))
