#!/usr/bin/env python3
"""CCRR 2027 chart generation. Data values as documented in 10_CHART_INDEX.md."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.rcParams.update({"font.size": 11, "axes.spines.top": False, "axes.spines.right": False})
OUT = "/home/claude/ccrr2027/charts/"
NAVY, TEAL, GRAY = "#12355b", "#1b7f8e", "#8a9bb0"

# CH-01: CA IC3 complaints 2022-2025
yrs = ["2022", "2023", "2024", "2025"]
comp = [80766, 77271, 96265, 116414]
fig, ax = plt.subplots(figsize=(7, 4.2))
b = ax.bar(yrs, comp, color=[GRAY, GRAY, GRAY, NAVY])
for r, v in zip(b, comp):
    ax.text(r.get_x()+r.get_width()/2, v+1500, f"{v:,}", ha="center", fontsize=10)
ax.set_title("Internet crime complaints filed by Californians, 2022-2025", loc="left", fontweight="bold")
ax.set_ylabel("IC3 complaints")
ax.set_ylim(0, 130000)
fig.text(0.01, 0.01, "Source: FBI IC3 annual reports 2022-2025. Chart: intSignal Research.", fontsize=8, color="#555")
fig.tight_layout(rect=[0, 0.04, 1, 1]); fig.savefig(OUT+"CH-01_ca_ic3_complaints.png", dpi=200); plt.close(fig)

# CH-02: CA IC3 losses 2023-2025
yrs2 = ["2023", "2024", "2025"]
loss = [2.16, 2.539, 3.675]
fig, ax = plt.subplots(figsize=(7, 4.2))
b = ax.bar(yrs2, loss, color=[GRAY, GRAY, NAVY])
for r, v in zip(b, loss):
    ax.text(r.get_x()+r.get_width()/2, v+0.06, f"${v:,.2f}B", ha="center", fontsize=10)
ax.set_title("Reported cybercrime losses by Californians, 2023-2025", loc="left", fontweight="bold")
ax.set_ylabel("Reported losses (USD billions)")
ax.set_ylim(0, 4.2)
fig.text(0.01, 0.01, "Source: FBI IC3 annual reports 2023-2025. Chart: intSignal Research.", fontsize=8, color="#555")
fig.tight_layout(rect=[0, 0.04, 1, 1]); fig.savefig(OUT+"CH-02_ca_ic3_losses.png", dpi=200); plt.close(fig)

# CH-03: AG register notification lag distribution (2024-2026 YTD, n=1,442)
# Buckets computed from raw capture via analyze_ag_register variant below.
import csv, statistics
from datetime import datetime, date
rows = []
with open("/home/claude/ccrr2027/raw-data/ca_ag_breach_register_capture.csv", newline='') as f:
    r = csv.reader(f); next(r)
    for org, bd, rep in r:
        try: repd = datetime.strptime(rep.strip(), "%m/%d/%Y").date()
        except: continue
        bs = []
        for x in bd.split(","):
            try: bs.append(datetime.strptime(x.strip(), "%m/%d/%Y").date())
            except: pass
        bs = [b for b in bs if b <= repd]
        if bs: rows.append((repd - min(bs)).days)
buckets = [("0-30", 0, 30), ("31-60", 31, 60), ("61-90", 61, 90), ("91-180", 91, 180),
           ("181-365", 181, 365), ("366+", 366, 10**6)]
vals = [sum(1 for l in rows if lo <= l <= hi) for _, lo, hi in buckets]
fig, ax = plt.subplots(figsize=(7, 4.2))
cols = [TEAL]*4 + ["#c0392b", "#7b241c"]
b = ax.bar([b[0] for b in buckets], vals, color=cols)
for r, v in zip(b, vals):
    ax.text(r.get_x()+r.get_width()/2, v+8, f"{v}\n({100*v/len(rows):.0f}%)", ha="center", fontsize=9)
ax.set_title("Days from breach occurrence to California AG notification\n(notices reported Jan 2024 - Aug 2026, n=%d)" % len(rows), loc="left", fontweight="bold")
ax.set_xlabel("Days elapsed"); ax.set_ylabel("Notices")
ax.set_ylim(0, max(vals)*1.25)
fig.text(0.01, 0.01, "Source: intSignal Research analysis of CA AG data breach register (accessed 2026-08-25).", fontsize=8, color="#555")
fig.tight_layout(rect=[0, 0.04, 1, 1]); fig.savefig(OUT+"CH-03_ag_notification_lag.png", dpi=200); plt.close(fig)
print("bucket values:", dict(zip([b[0] for b in buckets], vals)), "n=", len(rows), "median=", statistics.median(rows))
print("charts written")
