#!/usr/bin/env python3
# Finalizer fuer daily_drain.py coingecko.com (KRYPTO-PLATTFORMEN)
# Baut aus ~/investoren-daten/elektro/lr_unlocks_electro/coingecko.com.jsonl
# die Lieferung /var/www/dl/data/krypto-kunden-coingecko.csv (+xlsx)
# Aufruf: /usr/bin/python3 finalize_coingecko.py coingecko.com
import os, json, csv, sys, re, time

CD = os.path.expanduser('~/investoren-daten/elektro')
DATA = '/var/www/dl/data'
dom = sys.argv[1] if len(sys.argv) > 1 else 'coingecko.com'
SRC = os.path.join(CD, 'lr_unlocks_electro', dom + '.jsonl')
OUT = DATA + '/krypto-kunden-coingecko.csv'

if not os.path.exists(SRC):
    print('no source', SRC); sys.exit(0)

# Bestand (E-Mails) aus allen gelieferten Krypto-Listen
EMAIL_RE = re.compile(r'[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}')
seen = set()
for fn in 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 '@' in line:
                    for m in EMAIL_RE.findall(line[:400]):
                        seen.add(m.lower())
print('bestand', len(seen))

rows = []
for line in open(SRC, encoding='utf-8'):
    try:
        r = json.loads(line)
    except Exception:
        continue
    e = (r.get('email') or '').strip().lower()
    if not EMAIL_RE.fullmatch(e) or e in seen:
        continue
    seen.add(e)
    rows.append({
        'E-Mail': e,
        'Name': (r.get('name') or (r.get('first_name', '') + ' ' + r.get('last_name', '')).strip()),
        'Telefon': (r.get('phone') or '').strip(),
        'Stadt': (r.get('city') or '').strip(),
        'Region': (r.get('state') or '').strip(),
        'Land': (r.get('country') or '').strip(),
        'PLZ': (r.get('zip') or str(r.get('postal_code') or '')).strip(),
        'Quelle': f'LeakRadar coingecko.com ({dom}) Kunden-Pool',
    })
if not rows:
    print('keine neuen Zeilen'); sys.exit(0)

header = ['E-Mail', 'Name', 'Telefon', 'Stadt', 'Region', 'PLZ', 'Land', 'Quelle']
with open(OUT, 'w', encoding='utf-8', newline='') as f:
    w = csv.DictWriter(f, fieldnames=header)
    w.writeheader()
    w.writerows(rows)
print('WROTE', OUT, len(rows))

import openpyxl
from openpyxl.cell import WriteOnlyCell
from openpyxl.styles import PatternFill, Font
XP = 100000
nx = (len(rows) + XP - 1) // XP
for i in range(nx):
    fn = DATA + f'/krypto-kunden-coingecko-TEIL-{i+1}.xlsx'
    wb = openpyxl.Workbook(write_only=True)
    ws = wb.create_sheet('CoinGecko 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 r in rows[i*XP:(i+1)*XP]:
        ws.append([r[k] for k in header])
    wb.save(fn)
    print('xlsx teil', i + 1, fn)
print('DONE', len(rows))
