# -*- coding: utf-8 -*-
"""Builds the four article figures as SVG from the data files. No dependencies.
Usage: python charts.py   ->  ../img/fig-*.svg
"""
import json, collections, statistics as st
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
snap = json.loads((ROOT / 'data' / 'nvd_kev_snapshot.json').read_text(encoding='utf-8'))
lag = json.loads((ROOT / 'data' / 'kev_lag.json').read_text(encoding='utf-8'))
fc = json.loads((ROOT / 'data' / 'forecast.json').read_text(encoding='utf-8'))
NM = snap['nvd_monthly']; KM = collections.Counter(r['kevAdded'][:7] for r in lag['rows'])
INK, LIME, TEAL, GREEN, PALE, BG, GRID, MUTE = '#0f3b27', '#b9f55a', '#93dad5', '#4cae3c', '#d9e8c8', '#fbfaf3', '#dcdccf', '#5b6f62'
FONT = 'system-ui, -apple-system, &quot;Segoe UI&quot;, sans-serif'
W = 760
num = lambda v, d=0: f'{v:,.{d}f}'
esc = lambda s: s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')

class Fig:
    def __init__(self, name, title, sub, src, h=420, left=62, right=28, top=96, bottom=62):
        self.name, self.h = name, h
        self.x0, self.x1, self.y0, self.y1 = left, W - right, top, h - bottom
        self.p = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {h}" width="{W}" height="{h}" role="img" aria-label="{esc(title)}" font-family="{FONT}">',
                  f'<title>{esc(title)}</title><desc>{esc(sub)}</desc>',
                  f'<rect x="1.5" y="1.5" width="{W - 3}" height="{h - 3}" rx="12" fill="{BG}" stroke="{INK}" stroke-width="2"/>',
                  f'<text x="24" y="36" font-size="17" font-weight="700" fill="{INK}">{esc(title)}</text>',
                  f'<text x="24" y="57" font-size="12.5" fill="{MUTE}">{esc(sub)}</text>',
                  f'<text x="24" y="{h - 16}" font-size="10.5" fill="{MUTE}">{esc(src)}</text>']
    def axis(self, ymax, ticks, fmt):
        self.ymax = ymax
        for t in ticks:
            y = self.y(t)
            self.p.append(f'<line x1="{self.x0}" x2="{self.x1}" y1="{y:.1f}" y2="{y:.1f}" stroke="{INK if t == 0 else GRID}" stroke-width="1"/>')
            self.p.append(f'<text x="{self.x0 - 8}" y="{y + 4:.1f}" font-size="11" fill="{MUTE}" text-anchor="end">{esc(fmt(t))}</text>')
    def y(self, v): return self.y1 - v / self.ymax * (self.y1 - self.y0)
    def cx(self, i, n): return self.x0 + (self.x1 - self.x0) / n * (i + 0.5)
    def bar(self, x, w, v0, v1, color, tip=''):
        ya, yb = self.y(v1), self.y(v0)
        self.p.append(f'<rect x="{x:.1f}" y="{ya:.1f}" width="{w:.1f}" height="{max(yb - ya, 0):.1f}" fill="{color}" stroke="{INK}" stroke-width="1.2"><title>{esc(tip)}</title></rect>')
    def text(self, x, y, s, size=11.5, weight=400, anchor='middle', fill=INK):
        self.p.append(f'<text x="{x:.1f}" y="{y:.1f}" font-size="{size}" font-weight="{weight}" fill="{fill}" text-anchor="{anchor}">{esc(s)}</text>')
    def legend(self, items, y=80):
        x = 24
        for color, label in items:
            self.p.append(f'<rect x="{x}" y="{y - 10}" width="12" height="12" fill="{color}" stroke="{INK}" stroke-width="1.2"/>')
            self.text(x + 18, y, label, 12, anchor='start'); x += 18 + len(label) * 6.6 + 22
    def save(self):
        self.p.append('</svg>'); (ROOT / 'img' / self.name).write_text('\n'.join(self.p), encoding='utf-8'); print('saved', self.name)

def months(a, b):
    y, m = map(int, a.split('-')); r = []
    while f'{y}-{m:02d}' <= b:
        r.append(f'{y}-{m:02d}'); m += 1
        if m == 13: y, m = y + 1, 1
    return r
MS = months('2025-01', '2026-11')
MLAB = {'2025-01': 'Jan 25', '2025-04': 'Apr', '2025-07': 'Jul', '2025-10': 'Oct', '2026-01': 'Jan 26', '2026-04': 'Apr', '2026-07': 'Jul', '2026-10': 'Oct'}

def fig_monthly(name, title, sub, src, series, ymax, ticks, fmt, avg, avg_label, labels_for):
    f = Fig(name, title, sub, src); f.axis(ymax, ticks, fmt); n = len(MS)
    f.legend([(PALE, '2025'), (GREEN, '2026')])
    f.p.append(f'<line x1="150" x2="174" y1="76" y2="76" stroke="{INK}" stroke-width="1.6" stroke-dasharray="5 3"/>'); f.text(180, 80, avg_label, 12, anchor='start')
    for i, m in enumerate(MS):
        f.bar(f.cx(i, n) - 10, 20, 0, series[m], PALE if m < '2026' else GREEN, f'{m}: {num(series[m])}')
        if m in MLAB: f.text(f.cx(i, n), f.y1 + 18, MLAB[m], 11, fill=MUTE)
        if m in labels_for: f.text(f.cx(i, n), f.y(series[m]) - 6, num(series[m]), 11.5, 700)
    ya = f.y(avg); f.p.append(f'<line x1="{f.x0}" x2="{f.x1}" y1="{ya:.1f}" y2="{ya:.1f}" stroke="{INK}" stroke-width="1.6" stroke-dasharray="5 3"/>')
    f.save()

m25 = st.mean(NM[m] for m in months('2025-01', '2025-12')); k25 = st.mean(KM[m] for m in months('2025-01', '2025-12'))
fig_monthly('fig-1-cve-monthly.svg', 'New CVE records per month: four times the 2025 pace since September',
            'CVE records published in NVD, rejected records excluded, January 2025 - November 2026.',
            'Source: NVD API 2.0 (published date, noRejected), read 1 December 2026.',
            NM, 20000, [0, 5000, 10000, 15000, 20000], lambda t: '0' if t == 0 else f'{t // 1000}k', m25, f'2025 monthly average: {num(m25)}', ('2026-08', '2026-11'))
fig_monthly('fig-2-kev-monthly.svg', 'CISA KEV additions per month: twice the 2025 pace since September',
            'New entries in the CISA Known Exploited Vulnerabilities catalog by date added, January 2025 - November 2026.',
            'Source: CISA KEV JSON feed, catalog version ' + lag['catalogVersion'] + '.',
            KM, 50, [0, 10, 20, 30, 40, 50], str, k25, f'2025 monthly average: {num(k25, 1)}', ('2026-09', '2026-10', '2026-11'))

# ---- Fig 3: publication -> KEV lag by year
def lag_rows(y):
    return sorted(r['lagDays'] for r in lag['rows'] if f'{y}-01-01' <= r['kevAdded'] <= f'{y}-11-30' and r['cvePublished'] >= f'{y - 1}-01-01')
f = Fig('fig-3-kev-lag.svg', 'Fresh KEV entries: half are listed within one to two weeks of the CVE, with no clear trend',
        'Days from CVE publication to KEV listing; entries added January-November, CVEs published since 1 January of the prior year.',
        'Sources: CISA KEV (dateAdded), CVE.org cvelistV5 (datePublished). Own calculation.', h=440, bottom=78)
f.axis(100, [0, 25, 50, 75, 100], lambda t: f'{t}%')
BUCKETS = [('on or before CVE day', lambda x: x <= 0, INK), ('1-7 days', lambda x: 1 <= x <= 7, GREEN), ('8-30 days', lambda x: 8 <= x <= 30, LIME), ('over 30 days', lambda x: x > 30, PALE)]
f.legend([(c, l) for l, _, c in BUCKETS])
years = [2023, 2024, 2025, 2026]
for i, y in enumerate(years):
    L = lag_rows(y); n = len(L); base = 0
    for label, cond, color in BUCKETS:
        share = 100 * sum(1 for x in L if cond(x)) / n
        f.bar(f.cx(i, 4) - 48, 96, base, base + share, color, f'{y}, {label}: {share:.1f}%')
        if share > 7: f.text(f.cx(i, 4), f.y(base + share / 2) + 4, f'{share:.0f}%', 12, 700, fill='#ffffff' if color == INK else INK)
        base += share
    f.text(f.cx(i, 4), f.y1 + 20, str(y), 13, 700)
    f.text(f.cx(i, 4), f.y1 + 37, f'median {st.median(L):g} days, n = {n}', 11, fill=MUTE)
f.save()

# ---- Fig 4: forecast intervals
c = fc['results']['pooled']; b = fc['baselines']
f = Fig('fig-4-forecast.svg', 'Calls 1 and 2 for 1 December 2026 - 30 November 2027',
        'Bar: the published 90% interval. Tick: median of the pooled simulation. Dashed line: the last 12 months.',
        "Source: scripts/forecast.py (seeded simulation, three weight sets pooled). The weights are the author's judgment.", h=290, left=24, top=84, bottom=40)
rows = [('New CVE records in NVD', dict(c['nvd_fy27'], p05=140000, p95=325000), b['fy26_nvd'], 360000, lambda v: f'{v / 1000:.0f}k'),
        ('Additions to CISA KEV', dict(c['kev_fy27'], p05=260, p95=700), b['fy26_kev'], 800, lambda v: f'{v:.0f}')]
xa, xb = 250, W - 60
for i, (label, qd, last, xmax, fm) in enumerate(rows):
    y = 124 + i * 74; X = lambda v: xa + (xb - xa) * v / xmax
    f.text(24, y + 5, label, 13.5, 700, anchor='start')
    f.p.append(f'<line x1="{xa}" x2="{xb}" y1="{y}" y2="{y}" stroke="{GRID}" stroke-width="2"/>')
    f.p.append(f'<rect x="{X(qd["p05"]):.1f}" y="{y - 13}" width="{X(qd["p95"]) - X(qd["p05"]):.1f}" height="26" rx="5" fill="{LIME}" stroke="{INK}" stroke-width="2"/>')
    f.p.append(f'<line x1="{X(qd["p50"]):.1f}" x2="{X(qd["p50"]):.1f}" y1="{y - 18}" y2="{y + 18}" stroke="{INK}" stroke-width="3.5"/>')
    f.p.append(f'<line x1="{X(last):.1f}" x2="{X(last):.1f}" y1="{y - 22}" y2="{y + 22}" stroke="{INK}" stroke-width="1.6" stroke-dasharray="4 3"/>')
    f.text(X(qd['p05']), y + 31, fm(qd['p05']), 11.5); f.text(X(qd['p95']), y + 31, fm(qd['p95']), 11.5)
    f.text(X(qd['p50']), y + 31, 'median ' + fm(qd['p50']), 12, 700); f.text(X(last), y - 27, 'last 12 months: ' + fm(last), 11, fill=MUTE)
f.save()
