import sys
from pathlib import Path

curpath = Path(__file__).parents[3].resolve()
module_path = str(curpath.joinpath("./modules"))
print(f"Module path: {module_path}")
sys.path.insert(0, module_path)

from tree_parsing import treeparsing_utils


SERIALIZATION_TYPE = "preorder_dfs_nodeleaf_toks"
DEFAULT_DATA_FORMAT = "trees"


def postprocess_text(preds, labels):
    preds = [pred.strip() for pred in preds]
    labels = [[label.strip()] for label in labels]
    return preds, labels


def convert_treestr_to_code(trees, serialization_type, tgtlang):
    def _convert_(treestr):
        node = treeparsing_utils.deserialize(treestr, serialization_type)
        code = treeparsing_utils.convert_tree_to_code(node, tgtlang)
        return code

    if isinstance(trees, str):
        return _convert_(trees)
    elif isinstance(trees, list):
        return [_convert_(x) for x in trees]


def parsecode(code, lang, add_cls):
    try:
        root = treeparsing_utils.create_TS_tree(code, lang, add_cls)
        croot = treeparsing_utils.create_custom_tree(root, lang)
        tstr = treeparsing_utils.serialize(croot, SERIALIZATION_TYPE)
    except Exception as err:
        return None
    else:
        return tstr
