"""Per-storm table from HURDAT2: first datetime as named (TS/SS/HU), as HU, as major (HU>=96 kt),
ACE by fix date. Writes ../data/storms.csv and ../data/ace_fixes.csv (date, ace contribution)."""
import csv, sys
src = '../data/hurdat2-1851-2025-092326.txt'
lines = open(src).read().splitlines(); i = 0; storms = []; fixes_out = []
while i < len(lines):
    hdr = [x.strip() for x in lines[i].split(',')]; sid, name, n = hdr[0], hdr[1], int(hdr[2])
    fx = [[x.strip() for x in l.split(',')] for l in lines[i+1:i+1+n]]; i += 1 + n
    t_ns = t_h = t_mh = ''; vmax = 0
    for f in fx:
        dt = f[0] + f[1]; s = f[3]; v = int(f[6])
        if s in ('TS', 'SS', 'HU') and not t_ns: t_ns = dt
        if s == 'HU' and not t_h: t_h = dt
        if s == 'HU' and v >= 96 and not t_mh: t_mh = dt
        if s in ('TS', 'SS', 'HU'): vmax = max(vmax, v)
        if f[1] in ('0000', '0600', '1200', '1800') and s in ('TS', 'SS', 'HU') and v >= 34:
            fixes_out.append((sid, f[0], v * v / 1e4))
    storms.append(dict(sid=sid, name=name, year=int(sid[4:8]), t_ns=t_ns, t_h=t_h, t_mh=t_mh, vmax=vmax))
with open('../data/storms.csv', 'w', newline='') as fh:
    w = csv.DictWriter(fh, storms[0].keys()); w.writeheader(); w.writerows(storms)
with open('../data/ace_fixes.csv', 'w', newline='') as fh:
    w = csv.writer(fh); w.writerow(['sid', 'date', 'ace']); w.writerows(fixes_out)
pre = [s for s in storms if s['t_ns'] and s['year'] >= 2001 and s['t_ns'][4:8] < '0601']
post = [s for s in storms if s['t_ns'] and s['year'] >= 2001 and s['t_ns'][4:8] > '1130']
print('pre-season named:', [(s['year'], s['name'], s['t_ns'][:8]) for s in pre])
print('post-season named:', [(s['year'], s['name'], s['t_ns'][:8]) for s in post])
