#!/usr/bin/env python3
# MX-Stichproben-Audit LendenClub: 60 zufaellige Mails (Seed 46), dig MX gegen 1.1.1.1
import json, os, random, subprocess

CSV = os.path.expanduser('~/investoren-daten/lendenclub-NEU.csv')
OUT = os.path.expanduser('~/investoren-daten/crypto_expansion/lenden/mx_stichprobe_lendenclub.json')
import csv

random.seed(46)
emails = []
with open(CSV, encoding='utf-8') as f:
    for r in csv.DictReader(f):
        em = (r.get('email') or '').strip().lower()
        if '@' in em and '.' in em.rsplit('@', 1)[1]:
            emails.append(em)
print('Grundgesamtheit:', len(emails))
sample = random.sample(emails, min(60, len(emails)))
domains = sorted({e.rsplit('@', 1)[1] for e in sample})
ok, bad = 0, []
for dom in domains:
    try:
        r = subprocess.run(['dig', '+short', 'MX', dom, '@1.1.1.1'], capture_output=True, text=True, timeout=10)
        if r.stdout.strip():
            ok += 1
        else:
            bad.append(dom)
    except Exception:
        bad.append(dom)
    print(dom, 'ok' if dom not in bad else 'BAD')
ampel = 'GRUEN' if ok >= len(domains) * 0.95 else ('GELB' if ok >= len(domains) * 0.7 else 'ROT')
res = {'n_sample': len(sample), 'domains_checked': len(domains), 'mx_ok': ok, 'domains_bad': bad, 'ampel': ampel}
json.dump(res, open(OUT, 'w'), indent=1, ensure_ascii=False)
print(res)
