#!/usr/bin/env python3
"""Finisher: Zacks-Build nach OOM-Abbruch abschliessen.
- tmp (3.927.192 gestreamte Zeilen) an Haupt-CSV anhaengen
- TEIL-9.xlsx aus tmp-Zeilen 3.587.605..Ende bauen (Teile 5-8 = 4.000.000 Zeilen)
- tmp loeschen, Gesamtzahl verifizieren."""
import csv, os, re, sys
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.cell import WriteOnlyCell
from openpyxl.utils import get_column_letter

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

SKIP_TMP_ROWS = 3587604   # Zeilen 1..3.587.604 liegen in TEIL-5..8 (412.396 Prepass + 3.587.604 Stream)
XLSX_MAX = 1000000

with open(CSVP, encoding='utf-8') as f:
    header = next(csv.reader(f))
print('header:', header, flush=True)

# 1) TEIL-9 aus tmp bauen
xlp = os.path.join(OUT, f'forex-kunden-{NAME}-TEIL-9.xlsx')
fill = PatternFill('solid', fgColor='1F3864')
wb = Workbook(write_only=True)
ws = wb.create_sheet('Kunden')
ws.freeze_panes = 'A2'
clean = lambda row: [re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', str(v or '')) for v in row]
n9 = 0
with open(tmp, encoding='utf-8') as f:
    for i, line in enumerate(f, 1):
        if i <= SKIP_TMP_ROWS: continue
        if i == SKIP_TMP_ROWS + 1:
            lastcol = get_column_letter(len(header))
            # auto_filter-Ref auf echte Zeilenzahl setzen nach dem Zaehlen -> temporaer max
            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)
        row = next(csv.reader([line]))
        ws.append(clean(row))
        n9 += 1
        if n9 % 100000 == 0: print('  teil9:', n9, flush=True)
print('TEIL-9 Zeilen:', n9, flush=True)
wb.save(xlp)
print('TEIL-9 gespeichert:', xlp, os.path.getsize(xlp), flush=True)

# 2) tmp an Haupt-CSV anhaengen
with open(CSVP, 'ab') as fout, open(tmp, 'rb') as fin:
    while True:
        chunk = fin.read(1 << 24)
        if not chunk: break
        fout.write(chunk)
os.remove(tmp)
print('tmp angehaengt + geloescht', flush=True)

# 3) Verifizieren
with open(CSVP, encoding='utf-8') as f:
    total = sum(1 for _ in f) - 1
print('CSV GESAMT:', total, flush=True)
assert total == 4412396 + 3927192, 'Zeilenzahl passt nicht!'
print('OK: 4.412.396 + 3.927.192 =', 4412396 + 3927192, flush=True)
