#!/usr/bin/env python3
"""Resume des abgestuerzten Zacks-Streaming-Builds (Phase B).
Vorlauf lief bis ~5,1M gelesen / 4.412.396 geliefert (CSV + TEIL 1-4).
Hier: Rest streamen, an CSV anhaengen, XLSX TEIL-5+ schreiben.
Dedupe: bestand_hashes.npy + alle bereits gelieferten forex-kunden-*.csv."""
import csv, os, re, sys, hashlib
from array import array
from bisect import bisect_left
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.cell import WriteOnlyCell

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import build_delivery as B

OUT = '/var/www/dl/data'
NAME = 'zacks-10m'
CSVP = os.path.join(OUT, f'forex-kunden-{NAME}.csv')

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

def in_arr(arr, h):
    i = bisect_left(arr, h)
    return i < len(arr) and arr[i] == h

# --- Skip-Menge aufbauen ---
import numpy as np
bestand = np.fromfile(os.path.expanduser('~/investoren-daten/forex/bestand_hashes.npy'), dtype=np.int64)
arr = array('q'); arr.frombytes(bestand.tobytes()); bestand = arr
print('bestand:', len(bestand), flush=True)

import glob
extra = array('q')
n_files = 0
for p in sorted(glob.glob(os.path.join(OUT, 'forex-kunden-*.csv'))):
    n_files += 1
    with open(p, encoding='utf-8') as f:
        for r in csv.DictReader(f):
            em = (r.get('email') or '').strip().lower()
            if '@' in em: extra.append(h64(em))
print('csv-dateien gescannt:', n_files, 'emails:', len(extra), flush=True)
extra = array('q', sorted(set(extra.tolist())))
merged = array('q')
i = j = 0
a, b = bestand, extra
while i < len(a) and j < len(b):
    if a[i] < b[j]: merged.append(a[i]); i += 1
    elif a[i] > b[j]: merged.append(b[j]); j += 1
    else: merged.append(a[i]); i += 1; j += 1
merged.extend(a[i:]); merged.extend(b[j:])
skip = merged
del bestand, extra
print('skip-gesamt:', len(skip), flush=True)

# Header der bestehenden CSV uebernehmen
with open(CSVP, encoding='utf-8') as f:
    header = next(csv.reader(f))
print('header:', header, flush=True)

# --- Pre-Pass: CSV-Zeilen 4.000.001+ (aus Teil-1..4 XLSX gedeckt sind 4 Mio.)
# beim Absturz war TEIL-5 ungespeichert -> diese Zeilen hier ins XLSX zurueckholen.
seen = set()
PART_START = 5
XLSX_MAX = 1000000
fill = PatternFill('solid', fgColor='1F3864')
clean = lambda r: [re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', str(r.get(c, '') or '')) for c in B.COLS]

tmp_csv = CSVP + '.resume.tmp'
fcsv = open(tmp_csv, 'w', newline='', encoding='utf-8')
wcsv = csv.DictWriter(fcsv, fieldnames=header, extrasaction='ignore')

wb = ws = None
xlfiles = []
part = PART_START - 1
n_out_part = 0
n_read = n_out = 0

def new_part():
    global wb, ws, part, n_out_part
    if wb is not None:
        wb.save(xlfiles[-1]); wb = None
    part += 1
    n_out_part = 0
    xlp = os.path.join(OUT, f'forex-kunden-{NAME}-TEIL-{part}.xlsx')
    wb = Workbook(write_only=True)
    ws = wb.create_sheet('Kunden')
    ws.freeze_panes = 'A2'
    from openpyxl.utils import get_column_letter
    lastcol = get_column_letter(len(header))
    ws.auto_filter.ref = f'A1:{lastcol}{XLSX_MAX + 1}'
    hdr = [WriteOnlyCell(ws, value=h) for h in header]
    for c in hdr:
        c.font = Font(color='FFFFFF', bold=True); c.fill = fill
        c.alignment = Alignment(vertical='center')
    ws.append(hdr)
    xlfiles.append(xlp)
    print('  neu teil', part, flush=True)

PREPASS_TARGET = 4000000
with open(CSVP, encoding='utf-8') as f:
    rd = csv.reader(f); next(rd)
    idx = 0
    for row in rd:
        idx += 1
        if idx <= PREPASS_TARGET:
            continue
        if wb is None or n_out_part >= XLSX_MAX:
            new_part()
        ws.append(row)
        n_out_part += 1
print('pre-pass: xlsx-zeilen aus bestehender CSV:', n_out_part, flush=True)

for r in B.iter_zacks():
    n_read += 1
    em = r['email']
    h = h64(em)
    if in_arr(skip, h): continue
    if h in seen: continue
    seen.add(h)
    r['quelle'] = f'forex-{NAME}'
    wcsv.writerow(r)
    if wb is None or n_out_part >= XLSX_MAX:
        new_part()
    ws.append(clean(r))
    n_out_part += 1
    n_out += 1
    if n_read % 1000000 == 0:
        print('  zacks-resume:', n_read, 'gelesen,', n_out, 'neu geliefert', flush=True)

if wb is not None:
    wb.save(xlfiles[-1])
    # auto_filter-Ref final korrigieren
fcsv.close()
print('REST FERTIG:', n_read, 'gelesen,', n_out, 'neu', flush=True)
for x in xlfiles: print('  xlsx:', x, os.path.getsize(x), flush=True)

# CSV anhaengen
with open(CSVP, 'ab') as fout, open(tmp_csv, 'rb') as fin:
    while True:
        chunk = fin.read(1 << 20)
        if not chunk: break
        fout.write(chunk)
os.remove(tmp_csv)
with open(CSVP, encoding='utf-8') as f:
    total = sum(1 for _ in f) - 1
print('CSV GESAMT NACH ANHAENGEN:', total, flush=True)
