#!/usr/bin/env python3
"""Merge a builder's prediction file (_tools/coord/pred/<weapon>.md) into RATINGS.md (as COORD-PREDICTED) and put its
REPLACE keys into COORD_REPLACE in _tools/replace58_gen.py. Usage: python3 _tools/merge_pred.py <weapon>. Coordinator only."""
import re, sys, json, os, subprocess
w = sys.argv[1]; H = os.path.dirname(os.path.abspath(__file__))
src = open(os.path.join(H, 'coord', 'pred', w + '.md')).read()
rows = []
for l in src.splitlines():
    m = re.match(r'\|\s*([a-z0-9]+\.[a-z0-9.\-]+)\s*\|\s*([^|]+?)\s*\|\s*(good|ok but|ok|replace)\s*\|\s*([^|]*?)\s*\|\s*([^|]*?)\s*\|\s*$', l, re.I)
    if m:
        k, n, r, note, why = m.groups(); r = r.lower().replace('ok but', 'ok')
        rows.append((k, n, r, note, why))
P = os.path.join(H, 'coord', 'RATINGS.md'); txt = open(P).read()
head = '## %s (COORD-PREDICTED' % w.upper()
body = '\n'.join('| 28 Oct | %s | %s | %s | %s | %s [COORD-PREDICTED: %s] |' % (w, k, n, r, note, why.replace('|', '/')) for k, n, r, note, why in rows)
if head in txt:
    i = txt.find(head); j = txt.find('\n## ', i + 5)
    txt = txt[:i] + '%s; merged from pred/%s.md)\n| date | weapon | key | name | rating | note |\n|---|---|---|---|---|---|\n%s\n' % (head, w, body) + (txt[j:] if j != -1 else '')
else:
    txt = txt.rstrip('\n') + '\n\n%s; merged from pred/%s.md)\n| date | weapon | key | name | rating | note |\n|---|---|---|---|---|---|\n%s\n' % (head, w, body)
open(P, 'w').write(txt)
G = os.path.join(H, 'replace58_gen.py'); g = open(G).read()
reps = [(k, n) for k, n, r, _, _ in rows if r == 'replace']
add = ''.join('  %s: (%s, %s),\n' % (json.dumps(k), json.dumps(w), json.dumps(n)) for k, n in reps if json.dumps(k) not in g)
if add: g = g.replace('COORD_REPLACE = {\n', 'COORD_REPLACE = {\n' + add, 1); open(G, 'w').write(g)
print(w, len(rows), 'rows; REPLACE:', [k for k, _ in reps])
subprocess.run([sys.executable, G])
