"""Second reading of six quarters keeping ALL CVSS entries per record, to test how much
the high/critical results depend on which score is chosen. No personal data is sent."""
import json, sys, time, urllib.request

UA = {'User-Agent': 'PublicDataCheck/1.0'}
sys.stdout.reconfigure(encoding='utf-8')
QUARTERS = {
    '2025Q3': ('2025-07-01', '2025-09-30'), '2026Q3': ('2026-07-01', '2026-09-30'),
    '2025Q1': ('2025-01-01', '2025-03-31'), '2025Q2': ('2025-04-01', '2025-06-30'),
    '2026Q1': ('2026-01-01', '2026-03-31'), '2026Q2': ('2026-04-01', '2026-06-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)


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'])
            scores = []
            for key in ('cvssMetricV40', 'cvssMetricV31', 'cvssMetricV30'):
                for m in c.get('metrics', {}).get(key, []):
                    scores.append([key[-3:], m.get('type'), m.get('source'),
                                   m['cvssData'].get('baseSeverity') or 'NONE', m['cvssData'].get('baseScore')])
            rows_out.append([c['id'], c.get('sourceIdentifier', ''), scores])
        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)
