#!/usr/bin/env python3
# KRYPTO-PLATTFORMEN: Crypto.com 1.8M Kunden liefern — RAM-schonend (numpy+mmap statt Python-Set)
# Dedupe gegen Gesamtbestand (dedupe_full.pkl + gelieferte Krypto-CSVs), Streaming-Ausgabe.
import os, re, csv, pickle, hashlib, time
import numpy as np

CD = os.path.expanduser('~/krypto-angriff')
DATA = '/var/www/dl/data'
EMAIL_RE = re.compile(r'[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}')
STORE = CD + '/bestand_hashes.npy'
t0 = time.time()

def h(e):
    return int.from_bytes(hashlib.blake2b(e.lower().encode(), digest_size=8).digest(), 'big')

# ---- 1) Bestands-Hash-Store bauen (falls nicht vorhanden) ----
if os.path.exists(STORE):
    base = np.load(STORE, mmap_mode='r')
    print('store geladen', len(base), f'{time.time()-t0:.0f}s', flush=True)
else:
    with open(CD + '/dedupe_full.pkl', 'rb') as f:
        seen = pickle.load(f)
    print('pkl', f'{len(seen):,}', f'{time.time()-t0:.0f}s', flush=True)
    arr = np.fromiter(seen, dtype=np.uint64, count=len(seen))
    del seen
    more = []
    for fn in sorted(os.listdir(DATA)):
        if fn.startswith('krypto-') and fn.endswith('.csv'):
            with open(os.path.join(DATA, fn), 'r', encoding='utf-8', errors='replace') as f:
                for line in f:
                    if '@' not in line:
                        continue
                    for m in EMAIL_RE.findall(line[:400]):
                        more.append(int.from_bytes(hashlib.blake2b(m.lower().encode(), digest_size=8).digest(), 'big'))
    print('csv-hashes', f'{len(more):,}', f'{time.time()-t0:.0f}s', flush=True)
    if more:
        arr = np.concatenate([arr, np.fromiter(more, dtype=np.uint64, count=len(more))])
    arr.sort()
    np.save(STORE, arr)
    base = np.load(STORE, mmap_mode='r')
    print('store gebaut', len(base), f'{time.time()-t0:.0f}s', flush=True)

# ---- 2) Streaming durch den TSV, neue Zeilen direkt in Master-CSV ----
src = CD + '/cryptocom_dl/cryptocom_1809807.tsv'
out_csv = DATA + '/krypto-kunden-cryptocom.csv'
header = ['E-Mail', 'Vorname', 'Nachname', 'Telefon', 'Strasse', 'Stadt', 'Region', 'PLZ', 'Land', 'Quelle']
new_hashes = []
n_new = 0
n_dup = 0
de_provider = 0
BATCH = 50000
buf = []
f_in = open(src, 'r', encoding='utf-8', errors='replace', newline='')
f_out = open(out_csv, 'w', encoding='utf-8', newline='')
w = csv.DictWriter(f_out, fieldnames=header)
w.writeheader()

def flush_buf(buf):
    global n_new, n_dup, de_provider
    if not buf:
        return
    hs = np.array([h(b['E-Mail']) for b in buf], dtype=np.uint64)
    idx = np.searchsorted(base, hs)
    idx_clip = np.clip(idx, 0, len(base) - 1)
    is_dup = base[idx_clip] == hs
    for b, d in zip(buf, is_dup):
        if d:
            n_dup += 1
            continue
        n_new += 1
        if any(p in b['E-Mail'] for p in ('web.de', 'gmx.de', 'gmx.net', 't-online.de', 'freenet.de', 'online.de', 'arcor.de')):
            de_provider += 1
        new_hashes.append(h(b['E-Mail']))
        w.writerow(b)

r = csv.DictReader(f_in, delimiter='\t')
for row in r:
    e = (row.get('email') or '').strip().lower()
    if not e or '@' not in e or ' ' in e:
        continue
    buf.append({
        'E-Mail': e,
        'Vorname': (row.get('firstname') or '').strip(),
        'Nachname': (row.get('lastname') or '').strip(),
        'Telefon': (row.get('phone') or '').strip(),
        'Strasse': (row.get('address') or '').strip(),
        'Stadt': (row.get('city') or '').strip(),
        'Region': (row.get('state') or '').strip(),
        'PLZ': (row.get('zip') or '').strip(),
        'Land': (row.get('country') or '').strip(),
        'Quelle': 'spear.cx Thread 3220: Crypto.com 1.8M User Database (pixeldrain)',
    })
    if len(buf) >= BATCH:
        flush_buf(buf); buf = []
        print(f'... {n_new} neu / {n_dup} dup', f'{time.time()-t0:.0f}s', flush=True)
flush_buf(buf)
f_in.close(); f_out.close()
print('cryptocom: neu', n_new, 'dup', n_dup, 'de-provider', de_provider, f'{time.time()-t0:.0f}s', flush=True)

# ---- 3) CSV/XLSX-Teile aus der Master-CSV (RAM-schonend, zeilenweise) ----
import openpyxl
from openpyxl.cell import WriteOnlyCell
from openpyxl.styles import PatternFill, Font

total = n_new
PC, PX = 400000, 100000
nc = (total + PC - 1) // PC
f_in = open(out_csv, 'r', encoding='utf-8', newline='')
rd = csv.DictReader(f_in)
for i in range(nc):
    with open(DATA + f'/krypto-kunden-cryptocom-TEIL-{i+1}.csv', 'w', encoding='utf-8', newline='') as f:
        ww = csv.DictWriter(f, fieldnames=header)
        ww.writeheader()
        for j, row in enumerate(rd):
            if j >= PC:
                break
            ww.writerow(row)
    print('csv teil', i + 1, f'{time.time()-t0:.0f}s', flush=True)
f_in.close()

f_in = open(out_csv, 'r', encoding='utf-8', newline='')
rd = csv.DictReader(f_in)
nx = (total + PX - 1) // PX
for i in range(nx):
    wb = openpyxl.Workbook(write_only=True)
    ws = wb.create_sheet('Crypto.com Kunden')
    hdr = []
    for hname in header:
        c = WriteOnlyCell(ws, value=hname)
        c.fill = PatternFill('solid', fgColor='1F3864')
        c.font = Font(color='FFFFFF', bold=True)
        hdr.append(c)
    ws.append(hdr)
    for j, row in enumerate(rd):
        if j >= PX:
            break
        ws.append([row[k] for k in header])
    wb.save(DATA + f'/krypto-kunden-cryptocom-TEIL-{i+1}.xlsx')
    print('xlsx teil', i + 1, f'{time.time()-t0:.0f}s', flush=True)
f_in.close()
print('ALL DONE neu=%d dup=%d csv_teile=%d xlsx_teile=%d %.0fs' % (n_new, n_dup, nc, nx, time.time() - t0), flush=True)
