"""NOAA Eastern Pacific May outlook ranges from Wikipedia Pacific season articles (raw/wiki_YYYY.txt).
Takes, per year, the first table row in the 'Seasonal forecasts' section that names NOAA/CPC (not
'Central') and has a date plus three 'a–b' ranges. Writes noaa_epac.csv."""
import re, glob, csv
R = r'(\d{1,2})\s*[–\-]\s*(\d{1,2})'
out = []
for fn in sorted(glob.glob('raw/wiki_*.txt')):
    y = int(re.search(r'(\d{4})', fn).group(1)); t = open(fn).read()
    i = t.find('Seasonal forecast'); sec = t[i:i + 15000] if i >= 0 else t[:30000]
    sec = re.sub(r'<ref[^>]*/>', '', sec); sec = re.sub(r'<ref[^>]*>.*?</ref>', '', sec, flags=re.S)
    rows = re.split(r'\n\|-', sec)
    for row in rows:
        flat = re.sub(r'\s+', ' ', row)
        if not re.search(r'NOAA|CPC|Climate Prediction', flat) or re.search(r'Central', flat): continue
        if not re.search(r'(January|February|March|April|May|June|July|August)\s+\d{1,2},?\s+' + str(y), flat): continue
        rs = re.findall(R, flat)
        if len(rs) >= 3:
            d = re.search(r'((?:January|February|March|April|May|June|July|August)\s+\d{1,2},?\s+\d{4})', flat).group(1)
            out.append([y, d] + [f'{a}-{b}' for a, b in rs[:3]]); break
with open('noaa_epac.csv', 'w', newline='') as fh:
    w = csv.writer(fh); w.writerow(['year', 'issued', 'ns', 'h', 'mh']); w.writerows(out)
for r in out: print(*r)
print(len(out), 'years')
