import json
from pathlib import Path

root = Path('.')
ref_path = root / 'en_us.json'
if not ref_path.exists():
    print('Reference en_us.json not found')

with ref_path.open('r', encoding='utf-8') as f:
    ref = json.load(f)

# compute prefix (everything up to first space) for each key in en_us
prefixes = {}
for k, v in ref.items():
    if isinstance(v, str) and k.startswith('color'):
        prefixes[k] = v[:2]
    elif isinstance(v, str) and (k.startswith('enchantment.level') or k.startswith('potion.potency')):
        prefixes[k] = v
    elif isinstance(v, str) and k == 'filled_map.level':
        prefixes[k] = "   "
    elif isinstance(v, str) and k.startswith('item.minecraft.firework_star') and v[3]!=" "and v[2]!=" " and v[1]!=" ":
        prefixes[k] = v[:2]
    elif isinstance(v, str) and ' ' in v:
        prefixes[k] = v.split(' ', 1)[0] + " "
    else:
        prefixes[k] = v + " "

changed_files = []
processed = 0
for p in sorted(root.glob('*.json')):
    if p.name == 'en_us.json':
        continue
    processed += 1
    try:
        with p.open('r', encoding='utf-8') as f:
            data = json.load(f)
    except Exception as e:
        print(f'Failed to load {p}: {e}')
        continue
    if not isinstance(data, dict):
        print(f'Skipping non-dict JSON: {p}')
        continue
    new = {}
    changed = False
    for k, val in data.items():
        if not isinstance(val, str):
            new[k] = val
            continue
        # strip existing leading segment up to first space to get the "actual text"
        rest = val.lstrip()
        pref = prefixes.get(k, '')
        if pref and (k.startswith('enchantment.level') or k.startswith('potion.potency')):
            new_val = pref
        elif pref:
            new_val = pref + rest
        else:
            new_val = val
        if new_val != val:
            changed = True
        new[k] = new_val
    if changed:
        with p.open('w', encoding='utf-8') as f:
            json.dump(new, f, ensure_ascii=False, indent=2)
            f.write('\n')
        changed_files.append(p.name)
        print(f'Updated {p.name}')
    else:
        print(f'Unchanged {p.name}')

print('\nSummary:')
print(f'Total files processed: {processed}')
print(f'Files changed: {len(changed_files)}')
for name in changed_files:
    print('-', name)
