#!/usr/bin/env python3

import json
import precis_i18n as precis

from collections import defaultdict

# Create a "free" profile that will NFC normalize the string.
free = precis.profile.Profile(precis.get_profile('FreeFormClass'), 'free')

profiles = defaultdict(lambda: free, {
    "UsernameCasePreserved": precis.get_profile('UsernameCasePreserved'),
    "UsernameCaseMapped": precis.get_profile('UsernameCaseMapped:ToLower'),
    "OpaqueString": precis.get_profile('OpaqueString'),
    "Nickname": precis.get_profile('NicknameCasePreserved'),
})

if __name__ == "__main__":
    with open('machinetests.json') as json_tests:
        tests = json.load(json_tests)

    # Enforcement tests
    for g in tests["enforce"]:  # Minor group (eg. "Nickname")
        i = 0
        for test in g["Cases"]:  # Specific test case
            p = profiles[g["Name"]]
            try:
                enforced = p.enforce(test["Input"])
                if test["Err"]:
                    # We didn't raise an exception, but the test was
                    # supposed to error.
                    print("Expected error on enforce/" +
                          g["Name"] + "/" + str(i))
                elif enforced.decode('utf-8') != test["Output"]:
                    print("want: '" + test["Output"] + "'; got: '" + enforced.decode('utf-8') + "' on enforce/" +
                          g["Name"] + "/" + str(i))
            except UnicodeEncodeError:
                if not test["Err"]:
                    # We raised an exception but weren't expecting it.
                    print("Did not expect error on enforce/" +
                          g["Name"] + "/" + str(i))
            i += 1

        # Comparison tests
        # TODO: The python library doesn't look like it does comparison separately for profiles that have rules that
        # only apply during comparison.
