#!/usr/bin/env python3
# Swan Bitcoin + spear CMC 3.1M: normalisieren, gegen Gesamtbestand dedupen, CSV liefern
import os, re, csv, pickle, hashlib, sys, time

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,}')

t0 = time.time()
with open(CD + '/dedupe_full.pkl', 'rb') as f:
    seen = pickle.load(f)
print('base', f'{len(seen):,}', f'{time.time()-t0:.0f}s', flush=True)

# pkl wurde VOR den beiden Krypto-Lieferungen gebaut -> deren E-Mails nachtragen
for fn in ['krypto-kunden-bitbox-bestellungen.csv', 'krypto-kunden-coinmarketcap.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]):
                seen.add(int.from_bytes(hashlib.blake2b(m.lower().encode(), digest_size=8).digest(), 'big'))
print('base+new', f'{len(seen):,}', f'{time.time()-t0:.0f}s', flush=True)

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

# ---------- 1) Swan Bitcoin ----------
src = CD + '/swan_orders.csv'
out = DATA + '/krypto-kunden-swan-bitcoin.csv'
fields = ['Email', 'First Name', 'Last Name', 'Phone Number', 'City', 'State / Region', 'Country', 'Birthdate', 'How much are you looking to invest in Bitcoin over the next 12 months?']
new_rows = []
with open(src, 'r', encoding='utf-8', errors='replace', newline='') as f:
    r = csv.DictReader(f)
    for row in r:
        e = (row.get('Email') or '').strip().lower()
        if not e or '@' not in e:
            continue
        hv = h(e)
        if hv in seen:
            continue
        seen.add(hv)
        new_rows.append({
            'E-Mail': e,
            'Vorname': (row.get('First Name') or '').strip(),
            'Nachname': (row.get('Last Name') or '').strip(),
            'Telefon': (row.get('Phone Number') or '').strip(),
            'Stadt': (row.get('City') or '').strip(),
            'Region': (row.get('State / Region') or '').strip(),
            'Land': (row.get('Country') or '').strip(),
            'Geburtsdatum': (row.get('Birthdate') or '').strip(),
            'Investitionsvorhaben': (row.get('How much are you looking to invest in Bitcoin over the next 12 months?') or '').strip(),
            'Quelle': 'spear.cx Thread 306: Swan Bitcoin (Bitcoin-Investment-Interessenten)',
        })
print('swan new', len(new_rows), f'{time.time()-t0:.0f}s', flush=True)
with open(out, 'w', encoding='utf-8', newline='') as f:
    w = csv.DictWriter(f, fieldnames=list(new_rows[0].keys()))
    w.writeheader()
    w.writerows(new_rows)
print('WROTE', out, len(new_rows), flush=True)

# ---------- 2) spear CMC 3.1M E-Mails ----------
src = CD + '/cmc_spear/3.1MCoinMarketCapEmails_Spear/3.1MCoinMarketCapEmails_Spear/6yhinh.txt'
out = DATA + '/krypto-emails-coinmarketcap-spear.csv'
new_emails = []
with open(src, 'r', encoding='utf-8', errors='replace') as f:
    for line in f:
        e = line.strip().lower()
        if not e or '@' not in e or ' ' in e:
            continue
        hv = h(e)
        if hv in seen:
            continue
        seen.add(hv)
        new_emails.append(e)
print('cmc-spear new', len(new_emails), f'{time.time()-t0:.0f}s', flush=True)
if new_emails:
    with open(out, 'w', encoding='utf-8', newline='') as f:
        w = csv.writer(f)
        w.writerow(['E-Mail', 'Quelle'])
        for e in new_emails:
            w.writerow([e, 'spear.cx Thread 147: 3.1M CoinMarketCap E-Mails'])
    print('WROTE', out, len(new_emails), flush=True)
print('ALL DONE', f'{time.time()-t0:.0f}s', flush=True)
