#!/usr/bin/env python3
# PRESALE-JAGD: Delivery-Pipeline — JSONL -> Dedupe gegen Bestand -> CSV + XLSX (Teile a 100k)
# Deutsche Header, Freeze A2, Autofilter, Quelle je Zeile. Ausfuehren mit /usr/bin/python3 (openpyxl)!
import json, os, re, sys, csv, random, subprocess
sys.path.insert(0, os.path.expanduser('~/.hermes/cache/scratch/mode_leaks'))
from bestand_checker import BestandChecker
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.utils import get_column_letter
from openpyxl.cell import WriteOnlyCell

BASE = os.path.expanduser('~/investoren-daten/presale')
DL = '/var/www/dl/data'
BESTAND = os.path.expanduser('~/.hermes/cache/scratch/mode_leaks/bestand_emails.txt')
EMAIL_RE = re.compile(r'^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$')

# Quelle -> (jsonl, csv-name, spalten)  Spalten: (csv_key, deutscher_header)
QUELLEN = {
    'cmc': {
        'jsonl': os.path.join(BASE, 'snus', 'cmc.jsonl'),
        'name': 'presale-coinmarketcap',
        'quelle': 'Snusbase 0992_COINMARKETCAP_COM_3M (CoinMarketCap-User 2021)',
        'cols': [('email', 'E-Mail'), ('kategorie', 'Kategorie')],
    },
    'chainlink': {
        'jsonl': os.path.join(BASE, 'snus', 'chainlink.jsonl'),
        'name': 'presale-chainlink-ico',
        'quelle': 'Snusbase 1108_CHAIN_LINK_6057 (Chainlink-ICO-Teilnehmer)',
        'cols': [('email', 'E-Mail'), ('wallet', 'Wallet-Adresse'), ('betrag', 'ICO-Betrag'), ('kategorie', 'Kategorie')],
    },
    'opensea': {
        'jsonl': os.path.join(BASE, 'snus', 'opensea.jsonl'),
        'name': 'presale-opensea',
        'quelle': 'Snusbase 2144_OPENSEA_IO_6108K (OpenSea-NFT-Trader)',
        'cols': [('email', 'E-Mail'), ('kategorie', 'Kategorie')],
    },
    'everycoin': {
        'jsonl': os.path.join(BASE, 'snus', 'everycoin.jsonl'),
        'name': 'presale-everycoin',
        'quelle': 'Snusbase 1276_EVERYCOIN_IO_288K (Everycoin-Exchange-User)',
        'cols': [('email', 'E-Mail'), ('kategorie', 'Kategorie')],
    },
    'btce': {
        'jsonl': os.path.join(BASE, 'snus', 'btce.jsonl'),
        'name': 'presale-btce',
        'quelle': 'Snusbase 0466_BTCE_COM_700K (BTC-e-Börsen-User 2017)',
        'cols': [('email', 'E-Mail'), ('kategorie', 'Kategorie')],
    },
    'robinhood': {
        'jsonl': os.path.join(BASE, 'snus', 'robinhood.jsonl'),
        'name': 'presale-robinhood',
        'quelle': 'Snusbase 1157_ROBINHOOD_COM_7213K (Robinhood-Investoren inkl. Krypto)',
        'cols': [('email', 'E-Mail'), ('kategorie', 'Kategorie')],
    },
}

def norm_email(e):
    if not e: return None
    e = e.strip().lower()
    return e if EMAIL_RE.match(e) else None

def build(key):
    q = QUELLEN[key]
    print(f'== {key}: lese {q["jsonl"]}', flush=True)
    bc = BestandChecker(BESTAND)
    print(f'   Bestand: {bc.n} E-Mails', flush=True)
    seen = set()
    rows_out = []
    n_raw = n_bad = n_dup = n_bestand = 0
    with open(q['jsonl']) as f:
        for line in f:
            n_raw += 1
            try: r = json.loads(line)
            except Exception: continue
            e = norm_email(r.get('email'))
            if not e:
                n_bad += 1; continue
            if e in seen:
                n_dup += 1; continue
            if bc.exists(e):
                n_bestand += 1; continue
            seen.add(e)
            row = {'quelle': q['quelle'], 'email': e}
            if key == 'cmc':
                row['kategorie'] = 'presale-affin (CoinMarketCap-Nutzer)'
            elif key == 'chainlink':
                row['kategorie'] = 'ICO-Teilnehmer (Chainlink)'
                row['wallet'] = (r.get('address') or '').strip()
                row['betrag'] = str(r.get('amount') or '').strip()
            elif key == 'opensea':
                row['kategorie'] = 'presale-affin (OpenSea-NFT-Trader, web3-aktiv)'
            elif key == 'everycoin':
                row['kategorie'] = 'krypto-affin (Everycoin-Exchange-User)'
            elif key == 'btce':
                row['kategorie'] = 'krypto-affin (BTC-e-Börse, Frühanleger)'
            elif key == 'robinhood':
                row['kategorie'] = 'investoren-affin (Robinhood inkl. Krypto-Trading)'
            rows_out.append(row)
    print(f'   roh={n_raw} ungueltig={n_bad} dup={n_dup} im_bestand={n_bestand} NEU={len(rows_out)}', flush=True)
    if not rows_out:
        print('   KEINE neuen Zeilen — ueberspringe'); return None

    hdr = ['Quelle'] + [h for _, h in q['cols']]
    keys = ['quelle'] + [k for k, _ in q['cols']]
    csv_path = os.path.join(DL, q['name'] + '.csv')
    with open(csv_path, 'w', newline='', encoding='utf-8') as f:
        w = csv.writer(f)
        w.writerow(hdr)
        for row in rows_out:
            w.writerow([row.get(k, '') for k in keys])
    print(f'   CSV: {csv_path} ({len(rows_out)} Zeilen)', flush=True)

    # XLSX-Teile à 100k
    PART = 100000
    nparts = (len(rows_out) + PART - 1) // PART
    for i in range(nparts):
        chunk = rows_out[i*PART:(i+1)*PART]
        if nparts == 1:
            xlsx_path = os.path.join(DL, q['name'] + '.xlsx')
        else:
            xlsx_path = os.path.join(DL, f'{q["name"]}-TEIL-{i+1}.xlsx')
        wb = Workbook(write_only=True)
        ws = wb.create_sheet('Daten')
        hf = PatternFill('solid', fgColor='1F4E78'); hfont = Font(color='FFFFFF', bold=True, size=11)
        ws.freeze_panes = 'A2'
        ws.auto_filter.ref = f'A1:{get_column_letter(len(hdr))}1'
        cells = []
        for h in hdr:
            c = WriteOnlyCell(ws, value=h); c.fill = hf; c.font = hfont
            c.alignment = Alignment(horizontal='center', vertical='center')
            cells.append(c)
        ws.append(cells)
        for row in chunk:
            ws.append([row.get(k, '') for k in keys])
        wb.save(xlsx_path)
        print(f'   XLSX: {xlsx_path}', flush=True)

    # MX-Stichprobe (25 Domains)
    doms = {}
    for row in rows_out:
        d = row['email'].split('@')[1]
        doms[d] = doms.get(d, 0) + 1
    top = sorted(doms.items(), key=lambda x: -x[1])[:25]
    mx_ok = 0
    for d, _ in top:
        p = subprocess.run(['dig', '+short', 'MX', d], capture_output=True, text=True)
        if p.stdout.strip(): mx_ok += 1
    print(f'   MX-Stichprobe: {mx_ok}/{len(top)} Domains gueltig', flush=True)
    return {'key': key, 'neu': len(rows_out), 'csv': csv_path, 'mx': f'{mx_ok}/{len(top)}'}

if __name__ == '__main__':
    res = [build(k) for k in (sys.argv[1:] or list(QUELLEN))]
    json.dump([r for r in res if r], open(os.path.join(BASE, 'delivery_stats.json'), 'w'), indent=1)
    print('FERTIG')
