#!/usr/bin/env python3
"""Bestand-Hash-Cache RAM-schonend bauen: CSVs streamen, 64-Bit-Hashes, numpy unique."""
import csv, glob, os, hashlib
import numpy as np

def h64(email):
    return int.from_bytes(hashlib.blake2b(email.encode(), digest_size=8).digest(), 'big', signed=True)

paths = [os.path.expanduser('~/investoren-daten/retail-investoren-MASTER.csv')] + sorted(glob.glob('/var/www/dl/data/*.csv'))
chunks = []
buf = []
n_files = 0
for p in paths:
    try:
        with open(p, encoding='utf-8', errors='replace') as f:
            rd = csv.DictReader(f)
            for r in rd:
                em = (r.get('email') or '').strip().lower()
                if '@' in em:
                    buf.append(h64(em))
                    if len(buf) >= 2_000_000:
                        chunks.append(np.array(buf, dtype=np.int64)); buf = []
        n_files += 1
    except Exception as e:
        print('skip', p, e, flush=True)
if buf: chunks.append(np.array(buf, dtype=np.int64))
print('Dateien:', n_files, 'Hashes roh:', sum(len(c) for c in chunks), flush=True)
allh = np.concatenate(chunks)
del chunks
uniq = np.unique(allh)  # sortiert + unique
del allh
print('unique:', len(uniq), flush=True)
uniq.tofile(os.path.expanduser('~/investoren-daten/forex/bestand_hashes.npy'))
print('gespeichert bestand_hashes.npy', uniq.nbytes, 'bytes', flush=True)
