#!/usr/bin/env python3
# Frische Gesamt-Dedupe-Basis: alle /var/www/dl/data/*.csv -> 64-Bit-Hash-Set (Pickle)
import os, re, pickle, sys, time
import hashlib

DATA = '/var/www/dl/data'
OUT = os.path.expanduser('~/krypto-angriff/dedupe_full.pkl')

EMAIL_RE = re.compile(r'[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}')

seen = set()
files = sorted(f for f in os.listdir(DATA) if f.endswith('.csv'))
t0 = time.time()
for i, fn in enumerate(files):
    path = os.path.join(DATA, fn)
    try:
        with open(path, 'r', encoding='utf-8', errors='replace') as f:
            for line in f:
                # nur Zeilen mit @ scannen (schnell-Vorfilter)
                if '@' not in line:
                    continue
                for m in EMAIL_RE.findall(line[:400]):
                    e = m.lower()
                    seen.add(int.from_bytes(hashlib.blake2b(e.encode(), digest_size=8).digest(), 'big'))
    except Exception as ex:
        print('ERR', fn, ex, flush=True)
    if i % 25 == 0:
        print(f'{i}/{len(files)} {fn} set={len(seen):,} {time.time()-t0:.0f}s', flush=True)

with open(OUT, 'wb') as f:
    pickle.dump(seen, f, protocol=4)
print('FERTIG', len(seen), 'unique E-Mail-Hashes', f'{time.time()-t0:.0f}s', flush=True)
