"""Season totals from HURDAT2 (Atlantic): named storms (TS/SS/HU at any time),
hurricanes (HU), major hurricanes (HU with >=96 kt), ACE (1e-4 kt^2 over 00/06/12/18Z
fixes with status TS/SS/HU and wind>=34). Writes ../data/season_counts.csv."""
import csv, collections, sys
src = sys.argv[1] if len(sys.argv) > 1 else '../data/hurdat2-1851-2025-092326.txt'
rows = collections.defaultdict(lambda: dict(ns=0, h=0, mh=0, ace=0.0, ace_trop=0.0))
lines = open(src).read().splitlines()
i = 0
while i < len(lines):
    hdr = [x.strip() for x in lines[i].split(',')]
    sid, n = hdr[0], int(hdr[2]); yr = int(sid[4:8])
    fixes = [[x.strip() for x in l.split(',')] for l in lines[i+1:i+1+n]]
    i += 1 + n
    st = [f[3] for f in fixes]; w = [int(f[6]) for f in fixes]
    named = any(s in ('TS', 'SS', 'HU') for s in st)
    hur = any(s == 'HU' for s in st)
    major = any(s == 'HU' and v >= 96 for s, v in zip(st, w))
    r = rows[yr]
    r['ns'] += named; r['h'] += hur; r['mh'] += major
    for f, s, v in zip(fixes, st, w):
        if f[1] in ('0000', '0600', '1200', '1800') and s in ('TS', 'SS', 'HU') and v >= 34:
            r['ace'] += v * v / 1e4
            if s != 'SS': r['ace_trop'] += v * v / 1e4
with open('../data/season_counts.csv', 'w', newline='') as fh:
    wr = csv.writer(fh); wr.writerow(['year', 'ns', 'h', 'mh', 'ace', 'ace_trop'])
    for y in sorted(rows):
        r = rows[y]; wr.writerow([y, r['ns'], r['h'], r['mh'], round(r['ace'], 1), round(r['ace_trop'], 1)])
