#!/usr/bin/env python3
# MX-Stichproben-Audit raw4: 20 zufaellige Mails je Quelle (Seed 42), dig MX pruefen.
import json, os, random, subprocess

RAW4 = os.path.expanduser('~/investoren-daten/crypto_expansion/raw4')
OUT = os.path.join(RAW4, 'mx_stichproben.json')
random.seed(42)

results = {}
for fn in sorted(os.listdir(RAW4)):
    if not fn.endswith('.jsonl'):
        continue
    src = fn[:-6]
    emails = []
    with open(os.path.join(RAW4, fn), encoding='utf-8') as f:
        for line in f:
            try:
                row = json.loads(line)
            except Exception:
                continue
            em = (row.get('email') or row.get('Email') or '').strip().lower()
            if '@' in em and '.' in em.rsplit('@', 1)[1]:
                emails.append(em)
    if not emails:
        continue
    sample = random.sample(emails, min(20, 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)
    results[src] = {'n_sample': len(sample), 'domains_checked': len(domains), 'mx_ok': ok,
                    'domains_bad': bad,
                    'ampel': 'GRUEN' if ok >= len(domains) * 0.95 else ('GELB' if ok >= len(domains) * 0.7 else 'ROT')}
    print(src, results[src]['domains_checked'], 'doms,', ok, 'ok,', results[src]['ampel'], flush=True)

json.dump(results, open(OUT, 'w'), indent=1, ensure_ascii=False)
print('saved', OUT)
