"""Parse Karak 2026 (arXiv:2604.16183v2) Table 1 text into a CSV.
Input: ../lit/karak2026_table1.txt (pdftotext of the table). Output: karak_table1.csv
Columns: row, citation, first_author, year, value_str, value, err_plus, err_minus, method
Values are as listed by Karak (not converted; Karak says pre-2015 values are v1 and scales them by 1.43 for figures)."""
import re, csv, os
HERE = os.path.dirname(os.path.abspath(__file__))
lines = open(os.path.join(HERE, '..', 'lit', 'karak2026_table1.txt'), encoding='utf-8').read().splitlines()
# join the Labonville split line
out, skip = [], {'Publications Predicted Method', 'sunspot', 'number'}
buf = []
for ln in lines[1:]:
    ln = ln.strip()
    if not ln or ln in skip or ln.startswith('Solar Cycle Prediction:') or re.match(r'^\d+ Bidya', ln) or ln.startswith('Conflict'):
        continue
    if re.match(r'^[−-]\d', ln) and buf:   # continuation like "−14 Dynamo with ..."
        buf[-1] = buf[-1] + ' ' + ln
        continue
    buf.append(ln)
pat = re.compile(r'^(?P<cit>.+?\((?P<year>\d{4})[a-z]?\))\s+(?P<val>\S+(?:\s*[−-]\d+(?:\.\d+)?)?)\s+(?P<method>.*)$')
rows = []
for i, ln in enumerate(buf):
    ln2 = ln.replace('Cycle 24', 'Cycle_24').replace('Cycle 23', 'Cycle_23')
    m = pat.match(ln2)
    if not m:
        print('UNPARSED:', ln); continue
    v = m['val']; val = ep = em = ''
    if re.match(r'^[\d.]+±[\d.]+$', v):
        a, b = v.split('±'); val, ep, em = a, b, b
    elif re.match(r'^[\d.]+\+[\d.]+\s*[−-][\d.]+$', v):
        a, rest = v.split('+'); b, c = re.split(r'\s*[−-]', rest); val, ep, em = a, b, c
    elif re.match(r'^[\d.]+$', v):
        val = v
    cit = m['cit']
    first = re.split(r'\s+(?:and|et al\.)\s+|\s+\(', cit)[0]
    rows.append(dict(row=i + 1, citation=cit, first_author=first, year=m['year'], value_str=v.replace('_', ' '),
                     value=val, err_plus=ep, err_minus=em, method=m['method'].replace('_', ' ')))
with open(os.path.join(HERE, 'karak_table1.csv'), 'w', newline='', encoding='utf-8') as f:
    w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)
print(len(rows), 'rows;', sum(1 for r in rows if r['value']), 'numeric;', sum(1 for r in rows if r['err_plus']), 'with error')
