# -*- coding: utf-8 -*-
"""Merge part specs -> _r379_specs/<id>.json, normalise spaces."""
import io, json, os

d = []
for p in ['_r379_specs_part1.json', '_r379_specs_part2.json', '_r379_specs_part3.json']:
    d += json.load(io.open(p, encoding='utf-8'))
os.makedirs('_r379_specs', exist_ok=True)


def fix(s):
    if isinstance(s, str):
        return s.replace('NIH  grant', 'NIH grant').replace('  ', ' ')
    if isinstance(s, list):
        return [fix(x) for x in s]
    if isinstance(s, dict):
        return {k: fix(v) for k, v in s.items()}
    return s


for s in d:
    s = fix(s)
    p = os.path.join('_r379_specs', s['id'] + '.json')
    json.dump(s, io.open(p, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
    print(p, 'cards', len(s['cards']), 'rows', sum(len(c.get('rows', [])) for c in s['cards']))
