"""Pages through public NVD API 2.0 and stores one compact tuple per record
(id, source, severity, mentions WordPress) for offline analysis. No personal data is sent."""
import json, re, sys, time, urllib.request

UA = {'User-Agent': 'PublicDataCheck/1.0'}
sys.stdout.reconfigure(encoding='utf-8')
QUARTERS = {
    '2025Q1': ('2025-01-01', '2025-03-31'),
    '2025Q3': ('2025-07-01', '2025-09-30'),
    '2026Q3': ('2026-07-01', '2026-09-30'),
}


def get(url, tries=6):
    for i in range(tries):
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=180) as r:
                return json.loads(r.read())
        except Exception as e:  # noqa
            print('  retry', i, type(e).__name__, str(e)[:80], flush=True)
            time.sleep(15 + 10 * i)
    raise SystemExit('NVD request failed: ' + url)


def severity(metrics):
    for key in ('cvssMetricV40', 'cvssMetricV31', 'cvssMetricV30'):
        if metrics.get(key):
            return metrics[key][0]['cvssData'].get('baseSeverity') or 'NONE'
    return 'MISSING'


result = {}
for name, (a, b) in QUARTERS.items():
    start, total, rows_out, seen = 0, None, [], set()
    while total is None or start < total:
        url = ('https://services.nvd.nist.gov/rest/json/cves/2.0?pubStartDate=%sT00:00:00.000'
               '&pubEndDate=%sT23:59:59.999&resultsPerPage=2000&startIndex=%d&noRejected' % (a, b, start))
        obj = get(url)
        total = obj['totalResults']
        rows = obj['vulnerabilities']
        if not rows:
            break
        for row in rows:
            c = row['cve']
            if c['id'] in seen:
                continue
            seen.add(c['id'])
            text = ' '.join(d['value'] for d in c.get('descriptions', []) if d.get('lang') == 'en')
            rows_out.append([c['id'], c.get('sourceIdentifier', ''), severity(c.get('metrics', {})),
                             int(bool(re.search(r'word\s?press', text, re.I)))])
        start += len(rows)
        print(name, start, '/', total, flush=True)
        time.sleep(6.5)
    result[name] = {'total_api': total, 'rows': rows_out}
    json.dump(result, open(sys.argv[1], 'w', encoding='utf-8'))
    print('DONE', name, len(rows_out), flush=True)
