# -*- coding: utf-8 -*-
"""Pulls every number used in the article from public APIs. No API key needed.
Usage: python fetch_data.py   ->  ../data/nvd_kev_snapshot.json
NVD: API 2.0, UTC calendar periods by `published`, `noRejected`. KEV: CISA JSON feed.
"""
import json, time, calendar, urllib.request, urllib.error, datetime as dt, sys
from pathlib import Path
OUT = Path(__file__).resolve().parent.parent / 'data' / 'nvd_kev_snapshot.json'
UA = {'User-Agent': 'data-check/1.0'}
BASE = 'https://services.nvd.nist.gov/rest/json/cves/2.0?'

def get(url, tries=6):
    for i in range(tries):
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=90) as r:
                return json.loads(r.read())
        except Exception as e:
            time.sleep(8 + 6 * i)
    raise RuntimeError('failed ' + url)

def nvd(start, end, extra='', per_page=1):
    u = f'{BASE}resultsPerPage={per_page}&noRejected&pubStartDate={start}T00:00:00.000Z&pubEndDate={end}T23:59:59.999Z{extra}'
    r = get(u); time.sleep(6.3); return r

def qrange(y, q):
    m0 = 3 * (q - 1) + 1
    return f'{y}-{m0:02d}-01', f'{y}-{m0 + 2:02d}-{calendar.monthrange(y, m0 + 2)[1]}'

res = {'read_at_utc': dt.datetime.now(dt.timezone.utc).isoformat(timespec='seconds'), 'method': 'NVD API 2.0, noRejected, published in UTC period'}
kev = get('https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json')
res['kev_catalog'] = {'version': kev['catalogVersion'], 'count': kev['count']}
res['kev_entries'] = [{k: v.get(k) for k in ('cveID', 'dateAdded', 'dueDate', 'vendorProject', 'product', 'knownRansomwareCampaignUse')} for v in kev['vulnerabilities']]
OUT.write_text(json.dumps(res, indent=1), encoding='utf-8')

res['nvd_monthly'] = {}
for y, m in [(2025, i) for i in range(1, 13)] + [(2026, i) for i in range(1, 12)]:
    res['nvd_monthly'][f'{y}-{m:02d}'] = nvd(f'{y}-{m:02d}-01', f'{y}-{m:02d}-{calendar.monthrange(y, m)[1]}')['totalResults']
    print(y, m, res['nvd_monthly'][f'{y}-{m:02d}'], flush=True)
res['nvd_2026_to_sep15'] = nvd('2026-09-01', '2026-09-15')['totalResults']
OUT.write_text(json.dumps(res, indent=1), encoding='utf-8')

res['kev_cohorts'] = {}
for y in (2025, 2026):
    for q in (1, 2, 3):
        s, e = qrange(y, q)
        r = nvd(s, e, '&hasKev', per_page=2000)
        res['kev_cohorts'][f'{y}Q{q}'] = [{'id': v['cve']['id'], 'published': v['cve']['published'][:10], 'kevAdded': v['cve'].get('cisaExploitAdd'), 'kevDue': v['cve'].get('cisaActionDue')} for v in r['vulnerabilities']]
        print('cohort', y, q, len(res['kev_cohorts'][f'{y}Q{q}']), flush=True)
res['cvss_v3_severity_param'] = {}
for y in (2025, 2026):
    s, e = qrange(y, 3)
    for sev in ('HIGH', 'CRITICAL'):
        res['cvss_v3_severity_param'][f'{y}Q3_{sev}'] = nvd(s, e, f'&cvssV3Severity={sev}')['totalResults']
OUT.write_text(json.dumps(res, indent=1), encoding='utf-8')

res['nvd_quarterly'] = {}
for y in range(2017, 2027):
    for q in (1, 2, 3, 4):
        if (y, q) > (2026, 3): continue
        s, e = qrange(y, q)
        res['nvd_quarterly'][f'{y}Q{q}'] = nvd(s, e)['totalResults']
        print(y, q, res['nvd_quarterly'][f'{y}Q{q}'], flush=True)
OUT.write_text(json.dumps(res, indent=1), encoding='utf-8')
print('done')
