#!/usr/bin/env python3
"""tastyfx.com-Sample (999 Zeilen US-Forex-Contracts) verarbeiten.
Dedupe gegen Bestands-Hashes + alle gelieferten forex-kunden-*.csv (inkl. zacks).
Lieferung: /var/www/dl/data/forex-kunden-tastyfx-1k.csv + .xlsx"""
import csv, os, re, sys, hashlib, socket, random
from array import array
from bisect import bisect_left
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment

OUT = '/var/www/dl/data'
NAME = 'tastyfx-1k'
CSVP = os.path.join(OUT, f'forex-kunden-{NAME}.csv')
RAW = os.path.expanduser('~/investoren-daten/forex/raw/tastyfx_fallen.txt')

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

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)

def norm_phone_us(p):
    p = re.sub(r'\D', '', p or '')
    if len(p) == 10: return '+1' + p
    if len(p) == 11 and p.startswith('1'): return '+' + p
    return ''

rows = []
seen = set()
with open(RAW, encoding='utf-8', errors='replace') as f:
    rd = csv.reader(f)
    header = next(rd)
    for r in rd:
        if len(r) < 7: continue
        name = (r[0] or '').strip()
        email = (r[2] or '').strip().lower()
        if '@' not in email or ' ' in email: continue
        h = h64(email)
        if in_arr(skip, h) or h in seen: continue
        seen.add(h)
        addr = (r[9] if len(r) > 9 else '').strip()
        stadt = ''
        m = re.match(r'^\d+\s[^A-Z]*(.+)$', addr)
        # Adresse ist verklebt (z.B. '528 #B DivisaderoSan Francisco') - Stadt nicht sauber trennbar
        rows.append({'quelle': f'forex-{NAME}', 'email': email,
                     'telefon': norm_phone_us(r[5]),
                     'name': name, 'land': 'USA' if r[3] else '',
                     'broker': 'tastyfx.com',
                     'strasse': addr, 'stadt': stadt,
                     'bundesland': (r[3] or '').strip(),
                     'plz': (r[4] or '').strip(),
                     'kontromarge': (r[6] or '').strip(),
                     'ausfuehrungspreis': (r[1] or '').strip(),
                     'rolle': (r[8] if len(r) > 8 else '').strip(),
                     'broker_firma': (r[7] or '').strip()})

print('roh-zeilen nutzbar:', len(rows), flush=True)

COLS = list(rows[0].keys()) if rows else []
with open(CSVP, 'w', newline='', encoding='utf-8') as f:
    w = csv.DictWriter(f, fieldnames=COLS)
    w.writeheader()
    for r in rows: w.writerow(r)

# 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(COLS))
ws.auto_filter.ref = f'A1:{lastcol}{len(rows) + 1}'
fill = PatternFill('solid', fgColor='1F3864')
hdr = []
from openpyxl.cell import WriteOnlyCell
for h in COLS:
    c = WriteOnlyCell(ws, value=h)
    c.font = Font(color='FFFFFF', bold=True); c.fill = fill
    c.alignment = Alignment(vertical='center')
    hdr.append(c)
ws.append(hdr)
clean = lambda r: [re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', str(r.get(c, '') or '')) for c in COLS]
for r in rows: ws.append(clean(r))
XLP = os.path.join(OUT, f'forex-kunden-{NAME}.xlsx')
wb.save(XLP)
print('GELIEFERT:', len(rows))
print('csv:', CSVP, os.path.getsize(CSVP))
print('xlsx:', XLP, os.path.getsize(XLP))

# MX-Stichprobe
doms = sorted(set(r['email'].split('@')[1] for r in rows))
random.seed(42); random.shuffle(doms)
ok = bad = 0
for d in doms[:20]:
    try:
        socket.getaddrinfo(d, 25, socket.AF_INET)
        ok += 1
    except Exception:
        try:
            import dns.resolver
            dns.resolver.resolve(d, 'MX')
            ok += 1
        except Exception:
            bad += 1
print('MX-Stichprobe: alive', ok, 'dead', bad, 'von', min(20, len(doms)))
