#!/usr/bin/env python3
"""Phase B: restliche Forex-Quellen mit kompakter Hash-basierter Dedupe (RAM-schonend).
Laeuft nach build_delivery.py Phase A (etoro, tradeify, traedex, stockz11, broker50k sind fertig).
Quellen hier: investvoyager, hotex-arabien21k, agcapital-au-uk, jmbullion-490k, zacks-10m (streaming).
"""
import csv, json, os, re, sys, pickle, hashlib
from array import array
from bisect import bisect_left, insort
from openpyxl import Workbook, load_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'

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

def load_bestand_arr():
    """Bestand-Hashes aus numpy-Cache (.npy, sortiert+unique)."""
    import numpy as np
    p = os.path.expanduser('~/investoren-daten/forex/bestand_hashes.npy')
    a = np.fromfile(p, dtype=np.int64)  # Raw-Binaerdatei (tofile), kein .npy-Header
    # als sortiertes array('q') spiegeln (Bytelayout identisch int64)
    arr = array('q')
    arr.frombytes(a.tobytes())
    return arr

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

class HashSeen:
    """Wachsende Seen-Menge auf Hash-Basis mit periodischem Rebuild."""
    def __init__(self):
        self.hashes = set()
        self.arr = None
    def seen_or_add(self, h):
        if h in self.hashes: return True
        self.hashes.add(h)
        if self.arr is not None and in_arr(self.arr, h): return True
        if len(self.hashes) > 2_000_000:
            # rebuild: alles in sortiertes Array ueberfuehren, Hash-Set leeren
            if self.arr is None:
                self.arr = array('q', sorted(self.hashes))
            else:
                merged = sorted(set(self.arr.tolist()) | self.hashes)
                self.arr = array('q', merged)
            self.hashes = set()
        return False

def main():
    bestand = load_bestand_arr()
    print('Bestand-Hashes:', len(bestand), flush=True)
    # bereits gelieferte Forex-CSVs aus Phase A zur Dedupe hinzufuegen
    import glob
    phaseA = []
    for p in sorted(glob.glob(os.path.join(OUT, 'forex-kunden-*.csv'))):
        if os.path.basename(p).split('forex-kunden-')[1].split('.csv')[0].split('-TEIL')[0] in (
                'etoro-200k','tradeify-240k','traedex-67k','stockz11-48k','bfst-broker50k'):
            phaseA.append(p)
    extra = array('q')
    for p in phaseA:
        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('Phase-A-Emails zugefuegt:', len(extra), flush=True)
    if extra:
        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:])
        bestand = merged
    print('Bestand gesamt:', len(bestand), flush=True)

    seen = HashSeen()

    def keep(r):
        em = r.get('email')
        if em:
            if in_arr(bestand, h64(em)): return None
            if seen.seen_or_add(h64(em)): return None
            return r
        ph = r.get('telefon')
        if not ph: return None
        return r

    sources = [
        ('investvoyager',      B.parse_investvoyager),
        ('hotex-arabien21k',  B.parse_arabian21k),
        ('agcapital-au-uk',   B.parse_agcapital),
        ('jmbullion-490k',    B.parse_jmbullion),
    ]
    stats = {}
    for name, fn in sources:
        print('parse', name, '...', flush=True)
        rows = fn()
        n0 = len(rows)
        out = []
        for r in rows:
            k = keep(r)
            if k is not None:
                k['quelle'] = f'forex-{name}'
                out.append(k)
        del rows
        if not out:
            stats[name] = {'roh': n0, 'geliefert': 0}
            print(name, 'leer', flush=True); continue
        csvp, xlfiles = B.write_delivery(name, out)
        del out
        # Zeilen zaehlen
        with open(csvp, encoding='utf-8') as f:
            n = sum(1 for _ in f) - 1
        stats[name] = {'roh': n0, 'geliefert': n, 'csv': csvp, 'xlsx': xlfiles}
        print(name, {k2: v for k2, v in stats[name].items() if k2 != 'xlsx'}, flush=True)
        for x in xlfiles: print('  xlsx:', x, os.path.getsize(x), flush=True)

    # ---- Zacks streaming ----
    print('parse zacks-10m (streaming)...', flush=True)
    name = 'zacks-10m'
    csvp = os.path.join(OUT, f'forex-kunden-{name}.csv')
    fcsv = open(csvp, 'w', newline='', encoding='utf-8')
    header = None
    wcsv = None
    wb = ws = None
    xlfiles = []
    part = 0
    n_read = n_out = 0
    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]
    def new_part():
        nonlocal wb, ws, part
        if wb is not None:
            wb.save(xlfiles[-1]); wb = None
        part += 1
        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'
        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)
    for r in B.iter_zacks():
        n_read += 1
        em = r.get('email')
        if in_arr(bestand, h64(em)): continue
        if seen.seen_or_add(h64(em)): continue
        if header is None:
            used = [c for c in B.COLS if c in r]
            header = ['quelle'] + used
            wcsv = csv.DictWriter(fcsv, fieldnames=header, extrasaction='ignore')
            wcsv.writeheader()
        r['quelle'] = f'forex-{name}'
        wcsv.writerow(r)
        if n_out % XLSX_MAX == 0: new_part()
        ws.append(clean(r))
        n_out += 1
        if n_read % 1000000 == 0:
            print('  zacks:', n_read, 'gelesen,', n_out, 'geliefert', flush=True)
    if wb is not None: wb.save(xlfiles[-1])
    fcsv.close()
    if part == 1:
        os.replace(xlfiles[0], os.path.join(OUT, f'forex-kunden-{name}.xlsx'))
        xlfiles = [os.path.join(OUT, f'forex-kunden-{name}.xlsx')]
    stats[name] = {'roh': n_read, 'geliefert': n_out, 'csv': csvp, 'xlsx': xlfiles}
    print('zacks-10m', {k2: v for k2, v in stats[name].items() if k2 != 'xlsx'}, flush=True)
    for x in xlfiles: print('  xlsx:', x, os.path.getsize(x), flush=True)

    json.dump(stats, open(os.path.expanduser('~/investoren-daten/forex/stats_phaseB.json'),'w'), indent=1)
    print('PHASE B FERTIG. Gesamt:', sum(s.get('geliefert',0) for s in stats.values()), flush=True)

if __name__ == '__main__':
    main()
