#! python

import re
import os
import json


STATA_MAPPINGS_COMMENT = """//
// Header with configuration for model:
//    {}
//
// Automatically generated by Waf, do not change!
//
// Adjust model parameters in:
//    {}
// (or the original file).
//\n\n\n"""


def convert_mapping_json_to_stata(task):
    """Convert a JSON model specification in ``source[0]`` to a Stata
    do-file, storing dictionary entries in globals.

    Require the JSON file to contain a single, non-nested, dictionary in column format
    for better readability.

    Simply write its entries as Stata globals to the target file.

    """

    mappings = json.load(open(task.inputs[0].abspath()), encoding="utf-8")
    mappings_name = os.path.splitext(task.inputs[0].name)[0]

    tgt_content = STATA_MAPPINGS_COMMENT.format(mappings_name, task.inputs[0].abspath())

    for key, val in sorted(mappings.items()):
        if key.startswith("XXX"):
            continue
        # Adjust for Stata string notation
        elif isinstance(val, (list)):
            val_as_str = " ".join(val)
        elif isinstance(val, (dict)):
            assert mappings_name == "professions_kldb1988_iab"
            val_as_str = " ".join(sorted(val.keys()))
        tgt_content += 'global {k} "{v}"\n'.format(k=key, v=val_as_str)
    return task.outputs[0].write(tgt_content)


def build(ctx):

    ctx(
        rule=convert_mapping_json_to_stata,
        source="professions_kldb1988_iab.json",
        target="professions_kldb1988_iab.do",
    )
