"""Normalize T814's complex displays without changing component intervals.

python3 canonicalize.py [computed.json] [entries.json]
Input comes from compute.py; exact zero components only are omitted.
No decimal, digit or uncertainty is changed.
"""
import json
import re
import sys
from pathlib import Path


def canonical(text):
    match = re.fullmatch(r'(.+) \+ i \* (.+)', text)
    if not match:
        return text
    real, imag = match.groups()
    if imag == '0':
        return real
    negative = imag.startswith('-')
    coefficient = imag[1:] if negative else imag
    term = 'i * ' + coefficient
    if real == '0':
        return ('-' if negative else '') + term
    return real + (' - ' if negative else ' + ') + term


if __name__ == '__main__':
    source = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name('computed.json')
    target = Path(sys.argv[2]) if len(sys.argv) > 2 else source.with_name('entries.json')
    rows = json.loads(source.read_text())
    for row in rows:
        row['number'] = canonical(row['number'])
    target.write_text(json.dumps(rows, indent=2) + '\n')
    print('Canonicalized', len(rows), 'entries; exact zeros', sum(r['number'] == '0' for r in rows))
