"""Parse published data as literals; never execute the Maple program."""
import ast, re, json, os, hashlib
from pathlib import Path
W=Path(os.environ['NUMBERDB_WORKDIR'])
text=(W/'horton-output.txt').read_text()
atom_text=text.split('The set of elements is',1)[1].split('The  Splitting table',1)[0]
atoms=[''.join(map(str,a)) for a in ast.literal_eval(atom_text.strip())]
assert len(atoms)==len(set(atoms))==92
part=text.split('table([',1)[1].split('The  Abundance table',1)[0]
aliases={}
for m in re.finditer(r'%(\d+)\s*:=\s*([\d,\s]+)(?=%|The|$)',part):
    aliases[m[1]]=','.join(re.findall(r'\d+',m[2]))
assert len(aliases)==6
for k,v in aliases.items():part=part.replace('%'+k,v)
table=part.split('])',1)[0]
decays={}
pat=r'(\([\d,\s]+\)|(?<![\d,])\d(?:[\d,\s]*\d)?)\s*=\s*'
for match in re.finditer(pat,table):
    key=''.join(re.findall(r'\d',match[1]))
    start=match.end();assert table[start]=='['
    depth=0
    for end in range(start,len(table)):
        depth+=(table[end]=='[')-(table[end]==']')
        if depth==0:break
    rhs=ast.literal_eval(table[start:end+1])
    decays[key]=[''.join(map(str,a)) for a in rhs]
assert set(decays)==set(atoms),(len(decays),set(atoms)-set(decays))
assert all(a in atoms for rhs in decays.values() for a in rhs)
data={'source':'https://sites.math.rutgers.edu/~zeilberg/tokhniot/oPTlam',
      'source_sha256':hashlib.sha256((W/'horton-output.txt').read_bytes()).hexdigest(),
      'atoms':atoms,'decays':decays,
      'ternary_atoms':{'E':'10','M':'1110','D':'2110','B':'22110','U':'110','S':'122110','T':'222110','C':'11222110'},
      'ternary_decays':{'E':['M'],'M':['E','U'],'D':['S'],'B':['T'],'U':['D'],'S':['C'],'T':['E','B'],'C':['D','B']},
      'ternary_matrix_columns_are_parents':[[0,1,0,0,0,0,1,0],[1,0,0,0,0,0,0,0],[0,0,0,0,1,0,0,1],[0,0,0,0,0,0,1,1],[0,1,0,0,0,0,0,0],[0,0,1,0,0,0,0,0],[0,0,0,1,0,0,0,0],[0,0,0,0,0,1,0,0]]}
(W/'transition-data.json').write_text(json.dumps(data,indent=2))
print('Parsed',len(atoms),'atoms and',len(decays),'ordered published decays; six Maple abbreviations expanded.')
