# Path: tlfp/tools/common.py
# def open_json(dirpath, filename=None):
#     if filename:
#         path = os.path.join(dirpath, filename)
#     else:
#         path = dirpath
#     try:
#         with open(path, 'r') as f:
#             return json.load(f)
#     except Exception as e:
#         print(type(e), e, file=sys.stderr)
#         sys.stderr.write("ERROR: Could not open file %s" % (path,))
#         raise e
# 
# def print_json(dico, filename=None):
#     jdump = json.dumps(dico, ensure_ascii=False, sort_keys=True, indent=2)
#     if filename:
#         # create parent directories if necessary
#         dirname = os.path.dirname(filename)
#         if dirname:
#             os.makedirs(dirname, exist_ok=True)
# 
#         try:
#             with open("%s.tmp" % filename, 'w') as f:
#                 f.write(jdump)
#             if os.path.exists(filename):
#                 os.remove(filename)
#             os.rename("%s.tmp" % filename, filename)
#         except Exception as e:
#             print(type(e), e, file=sys.stderr)
#             sys.stderr.write("ERROR: Could not write in file %s" % filename)
#             raise e
#     else:
#         print(jdump)


import sys, re
import metslesliens
from .common import open_json, print_json
            continue
        dos["textes_cites"] = [] # only keep the latest version
        for data in articles:
            if data["type"] == "article":
                data['liens'] = []
                for i in range(len(data["alineas"])):
                    text = data["alineas"]["%03d" % (i+1)]
                    for candidat in metslesliens.donnelescandidats(text, 'structuré'):
                        if 'texte' in candidat and 'relatif' not in candidat['texte']:
                            code = get_code(candidat)
                            if code and code not in dos["textes_cites"]:
                                dos["textes_cites"].append(code)

                            link_text = text[candidat['index'][0]:candidat['index'][1]]
                            link_text = re.sub(r'^(aux?|les?|la|du|des)(dite?s?)? ', '', link_text, 0, re.I)
                            link_text = re.sub(r"^l'", '', link_text, 0, re.I)
                            if not re.search(r'(même|présente?|précédente?) ', link_text ) and link_text not in data['liens']:
                                """
                                link = {
                                    'texte': link_text
                                }
                                if 'eli_alias' in candidat:
                                    link['url'] = "https://www.legifrance.gouv.fr/" + candidat['eli_alias']
                                """
                                data['liens'].append(link_text)
        dos["textes_cites"].sort()
    return dos


if __name__ == '__main__':

# Path: tlfp/tools/common.py
# def open_json(dirpath, filename=None):
#     if filename:
#         path = os.path.join(dirpath, filename)
#     else:
#         path = dirpath
#     try:
#         with open(path, 'r') as f:
#             return json.load(f)
#     except Exception as e:
#         print(type(e), e, file=sys.stderr)
#         sys.stderr.write("ERROR: Could not open file %s" % (path,))
#         raise e
# 
# def print_json(dico, filename=None):
#     jdump = json.dumps(dico, ensure_ascii=False, sort_keys=True, indent=2)
#     if filename:
#         # create parent directories if necessary
#         dirname = os.path.dirname(filename)
#         if dirname:
#             os.makedirs(dirname, exist_ok=True)
# 
#         try:
#             with open("%s.tmp" % filename, 'w') as f:
#                 f.write(jdump)
#             if os.path.exists(filename):
#                 os.remove(filename)
#             os.rename("%s.tmp" % filename, filename)
#         except Exception as e:
#             print(type(e), e, file=sys.stderr)
#             sys.stderr.write("ERROR: Could not write in file %s" % filename)
#             raise e
#     else:
#         print(jdump)


# Path: tlfp/tools/add_links.py
import sys, re
import metslesliens
from .common import open_json, print_json

            continue
        dos["textes_cites"] = [] # only keep the latest version
        for data in articles:
            if data["type"] == "article":
                data['liens'] = []
                for i in range(len(data["alineas"])):
                    text = data["alineas"]["%03d" % (i+1)]
                    for candidat in metslesliens.donnelescandidats(text, 'structuré'):
                        if 'texte' in candidat and 'relatif' not in candidat['texte']:
                            code = get_code(candidat)
                            if code and code not in dos["textes_cites"]:
                                dos["textes_cites"].append(code)

                            link_text = text[candidat['index'][0]:candidat['index'][1]]
                            link_text = re.sub(r'^(aux?|les?|la|du|des)(dite?s?)? ', '', link_text, 0, re.I)
                            link_text = re.sub(r"^l'", '', link_text, 0, re.I)
                            if not re.search(r'(même|présente?|précédente?) ', link_text ) and link_text not in data['liens']:
                                """
                                link = {
                                    'texte': link_text
                                }
                                if 'eli_alias' in candidat:
                                    link['url'] = "https://www.legifrance.gouv.fr/" + candidat['eli_alias']
                                """
                                data['liens'].append(link_text)
        dos["textes_cites"].sort()
    return dos


if __name__ == '__main__':

    print_json(process(open_json(sys.argv[1])))