#!/usr/bin/env python3
# KRYPTO-KONSOLIDIERUNG: frische LeakRadar-Ernte (krypto_angriff/lr_unlocks_krypto) dedupen
# gegen ALLE bereits gelieferten Krypto-Listen (/var/www/dl/data) + Gesamt-Master.
# Nur ECHT NEUE Kontakte werden je Portal als krypto-<portal>-NEU.csv geliefert.
# RAM-fest: SQLite (keine Python-Sets fuer Millionen), Restart-faehig ueber Progress-Datei.
import csv, glob, json, os, re, sqlite3, sys, time

DL = '/var/www/dl/data'
OUT = os.path.expanduser('~/investoren-daten/krypto_angriff')
NEWDIR = OUT + '/lieferung'
os.makedirs(NEWDIR, exist_ok=True)
DB = OUT + '/krypto_bestand.sqlite'
PROG = OUT + '/konsolidierung_progress.json'
MASTER = os.path.expanduser('~/investoren-daten/retail-investoren-MASTER.csv')
FRESH = {
    'coinmarketcap.com': OUT + '/lr_unlocks_krypto/coinmarketcap.com.jsonl',
    'coingecko.com': OUT + '/lr_unlocks_krypto/coingecko.com.jsonl',
    'etherscan.io': OUT + '/lr_unlocks_krypto/etherscan.io.jsonl',
}
EMAIL_RE = re.compile(r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$')
CRYPTO_PAT = re.compile(r'krypto|coin|daytrad|trading|presale|etherscan|binance|crypto', re.I)

def log(msg):
    line = time.strftime('%H:%M:%S') + ' ' + msg
    print(line, flush=True)
    open(OUT + '/konsolidierung.log', 'a').write(line + '\n')

con = sqlite3.connect(DB)
con.execute('PRAGMA journal_mode=OFF')
con.execute('PRAGMA synchronous=OFF')
con.execute('CREATE TABLE IF NOT EXISTS bestand (email TEXT PRIMARY KEY, quelle TEXT) WITHOUT ROWID')
con.execute('CREATE TABLE IF NOT EXISTS neu (email TEXT PRIMARY KEY, portal TEXT, passwort TEXT, staerke TEXT, url TEXT, added TEXT) WITHOUT ROWID')

prog = json.load(open(PROG)) if os.path.exists(PROG) else {'bestand_files_done': [], 'fresh_done': []}

# Phase 1: Bestand laden (gelieferte Krypto-CSVs)
def csv_email_cols(header):
    cols = []
    for i, h in enumerate(header):
        hl = h.strip().lower()
        if hl in ('email', 'e-mail', 'mail', 'e_mail') or hl.endswith('email'):
            cols.append(i)
    return cols

files = sorted(f for f in os.listdir(DL) if f.endswith('.csv') and CRYPTO_PAT.search(f))
todo = [f for f in files if f not in prog['bestand_files_done']]
log(f'Bestand: {len(files)} Krypto-CSVs, {len(todo)} zu laden')
for n, fn in enumerate(todo):
    path = os.path.join(DL, fn)
    cnt = 0
    try:
        with open(path, newline='', encoding='utf-8', errors='replace') as f:
            r = csv.reader(f)
            try: header = next(r)
            except StopIteration: continue
            cols = csv_email_cols(header)
            if not cols:
                # Header "email" lowercase-Variante
                cols = [i for i, h in enumerate(header) if 'mail' in h.strip().lower()]
            batch = []
            for row in r:
                for c in cols:
                    if c < len(row):
                        e = row[c].strip().lower()
                        if EMAIL_RE.match(e):
                            batch.append((e, fn)); cnt += 1
                            break
                if len(batch) >= 50000:
                    con.executemany('INSERT OR IGNORE INTO bestand VALUES (?,?)', batch); batch = []
            if batch: con.executemany('INSERT OR IGNORE INTO bestand VALUES (?,?)', batch)
    except Exception as ex:
        log(f'  FEHLER {fn}: {str(ex)[:80]}'); continue
    prog['bestand_files_done'].append(fn)
    if n % 25 == 0:
        json.dump(prog, open(PROG, 'w'))
        log(f'  Bestand {n+1}/{len(todo)}: {fn} (+{cnt})')
json.dump(prog, open(PROG, 'w'))

# Gesamt-Master (retail) als Bestand dazu (nur E-Mail-Spalte, known header)
if 'master' not in prog['bestand_files_done']:
    if os.path.exists(MASTER):
        cnt = 0
        with open(MASTER, newline='', encoding='utf-8', errors='replace') as f:
            r = csv.reader(f)
            header = next(r)
            cols = csv_email_cols(header) or [0]
            batch = []
            for row in r:
                for c in cols:
                    if c < len(row):
                        e = row[c].strip().lower()
                        if EMAIL_RE.match(e):
                            batch.append((e, 'MASTER')); cnt += 1; break
                if len(batch) >= 50000:
                    con.executemany('INSERT OR IGNORE INTO bestand VALUES (?,?)', batch); batch = []
            if batch: con.executemany('INSERT OR IGNORE INTO bestand VALUES (?,?)', batch)
        log(f'Master geladen (+{cnt})')
    prog['bestand_files_done'].append('master')
    json.dump(prog, open(PROG, 'w'))

n_bestand = con.execute('SELECT COUNT(*) FROM bestand').fetchone()[0]
log(f'BESTAND TOTAL: {n_bestand} unique Krypto/Master-E-Mails')

# Phase 2: frische Ernte streamen, nur NEUE in neu-Tabelle
for portal, fn in FRESH.items():
    if portal in prog['fresh_done'] or not os.path.exists(fn):
        continue
    total = known = new = 0
    batch = []
    with open(fn, encoding='utf-8') as f:
        for line in f:
            try: d = json.loads(line)
            except Exception: continue
            e = (d.get('username') or '').strip().lower()
            total += 1
            if not EMAIL_RE.match(e): continue
            cur = con.execute('SELECT 1 FROM bestand WHERE email=?', (e,)).fetchone()
            if cur: known += 1; continue
            batch.append((e, portal, d.get('password') or '', str(d.get('password_strength') or ''), d.get('url') or '', (d.get('added_at') or '')[:10]))
            new += 1
            if len(batch) >= 20000:
                con.executemany('INSERT OR IGNORE INTO neu VALUES (?,?,?,?,?,?)', batch)
                con.executemany('INSERT OR IGNORE INTO bestand VALUES (?,?)', [(b[0], 'FRESH') for b in batch])
                batch = []
    if batch:
        con.executemany('INSERT OR IGNORE INTO neu VALUES (?,?,?,?,?,?)', batch)
        con.executemany('INSERT OR IGNORE INTO bestand VALUES (?,?)', [(b[0], 'FRESH') for b in batch])
    prog['fresh_done'].append(portal)
    json.dump(prog, open(PROG, 'w'))
    log(f'{portal}: {total} gelesen, {known} schon im Bestand, {new} NEU')

con.commit()
# Phase 3: Lieferung je Portal
for portal in FRESH:
    rows = con.execute('SELECT email, passwort, staerke, url, added FROM neu WHERE portal=? ORDER BY email', (portal,)).fetchall()
    if not rows: continue
    slug = portal.split('.')[0]
    csvp = f'{NEWDIR}/krypto-{slug}-NEU.csv'
    with open(csvp, 'w', newline='', encoding='utf-8') as f:
        w = csv.writer(f)
        w.writerow(['E-Mail', 'Passwort', 'Passwort-Staerke', 'Portal', 'Login-Kontext (URL)', 'Hinzugefuegt am', 'Quelle'])
        for e, pw, st, url, ad in rows:
            w.writerow([e, pw, st, portal, url, ad, 'LeakRadar 15.11. Ernte'])
    log(f'LIEFERUNG {csvp}: {len(rows)} Zeilen')
log('FERTIG')
con.close()
