"""
Michael Murtaugh
Following Charles Hayden's 1990's interpretation implemented in Java
(C) 2018 and released under the Free Art License 1.3
See LICENSE.txt and http://artlibre.org/licence/lal/en/

For use with eliza.js
Usage:

    python3 eliza_script_to_json.py < doctor.txt > doctor.json

"""
import sys, json

output = {}
output['pre'] = pre = []
output['post'] = post = []
output['synon'] = synon = []
output['quit'] = quit = []
output['keywords'] = keys = []
for line in sys.stdin:
    line = line.strip()
    if line.startswith("#") or not line:
        continue
    cmd, rest = line.split(" ", 1)
    cmd = cmd.strip()
    rest = rest.strip()
    if cmd == "initial:":
        output['initial'] = rest
    elif cmd == "final:":
        output['final'] = rest
    elif cmd == "pre:":
        pre.append(rest)
    elif cmd == "post:":
        post.append(rest)
    elif cmd == "synon:":
        synon.append(rest)
    elif cmd == "key:":
        try:
            token, weight = rest.split()
        except ValueError:
            token = rest.strip()
            weight = 0
        print ("key", token, int(weight), file=sys.stderr)
        keys.append({"token": token.strip(), "weight": int(weight), "rules": []})
    elif line.startswith("decomp:"):
        _, pattern = line.split(" ", 1)
        pattern = pattern.strip()
        if pattern.startswith("$"):
            decomp = {"decomp": pattern[1:].strip(), "reasmb": [], "save": True}
        else:
            decomp = {"decomp": pattern, "reasmb": []}
        print ("decomp", decomp, file=sys.stderr)
        keys[-1]['rules'].append(decomp)
    elif line.startswith("reasmb:"):
        _, pattern = line.split(" ", 1)
        print ("reasmb", pattern, file=sys.stderr)
        keys[-1]['rules'][-1]['reasmb'].append(pattern.strip())

print (json.dumps(output, indent=2))
