#!/usr/bin/env python3
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import sys
from pathlib import Path

ROOT = Path(__file__).parent.parent

PY_GEN_DIR = 'python/dazl/_gen'
REWRITE = '_build/python/rewrite_pb2.py'


def main():
    generate(sys.argv[1])


def generate(manifest_file):
    import json
    from collections import defaultdict
    manifest = defaultdict(set)
    manifest[''].add('init')

    with Path(manifest_file).open() as f:
        for k, v in json.load(f).items():
            manifest[k] = set(v)
        
    sources = []

    # enrich the manifest with 'init' entries for all directories, so that
    # everything generated exists in a Python package
    new_packages = set()
    for proto_package in list(manifest):
        # split the string on slash, and grab everything in the front
        components = proto_package.split('/')[:-1]
        while components:
            pkg = '/'.join(components)
            manifest[pkg].add('init')
            components.pop()

    for p, types in manifest.items():
        if 'init' in types:
            sources.append(f'{p}/__init__.py')
        if 'pb' in types:
            sources.append(f'{p}_pb2.py')
        if 'grpc' in types:
            sources.append(f'{p}_pb2_grpc.py')

    print(f'# THIS FILE IS AUTOMATICALLY GENERATED. DO NOT MODIFY.')
    print(f'py_gen_dir := {PY_GEN_DIR}')
    print(f'py_gen_src := \\')
    for i, p in enumerate(sorted(sources)):
        if i < (len(sources) - 1):
            print(f'  $(py_gen_dir)/{p} \\')
        else:
            print(f'  $(py_gen_dir)/{p}')
    print(f'_py_gen_tmp_dir := $(cache_dir)/python')
    print(f'_py_rewrite := {REWRITE}')
    print()
    print('.PHONY: gen-python')
    print('gen-python: $(py_gen_src)')

    for p, types in manifest.items():
        # init packages are directories that merely have a copyright file as
        # their lone comment
        if 'init' in types:
            s = f'/{p}' if (p or p != '/') else ''
            print()
            print(f'$(py_gen_dir){s}/__init__.py: COPYRIGHT')
            print('\t@mkdir -p $(@D)')
            print("\tsed -e 's/^/# /' < $< > $@")

        # Protobuf files are firstly the raw output from grpc_tools; then they
        # get their copyright notices added and absolute imports rewritten as
        # relative imports
        if 'pb' in types and 'grpc' not in types:
            print()
            print(f'$(py_gen_dir)/{p}_pb2.py: $(_py_gen_tmp_dir)/{p}_pb2.py COPYRIGHT')
            print('\t@mkdir -p $(@D)')
            print('\t$(python) $(_py_rewrite) $< .cache/python COPYRIGHT > $@')
            print()
            print(f'$(_py_gen_tmp_dir)/{p}_pb2.py: $(proto_dir)/{p}.proto')
            print('\t@mkdir -p $(_py_gen_tmp_dir)')
            print('\t$(python) -m grpc_tools.protoc -I$(proto_dir) --python_out=$(_py_gen_tmp_dir) $<')

        if 'grpc' in types:
            print()
            print(f'$(py_gen_dir)/{p}_pb2.py: $(_py_gen_tmp_dir)/{p}_pb2.py COPYRIGHT')
            print('\t@mkdir -p $(@D)')
            print('\t$(python) $(_py_rewrite) $< .cache/python COPYRIGHT > $@')
            print()
            print(f'$(py_gen_dir)/{p}_pb2_grpc.py: $(_py_gen_tmp_dir)/{p}_pb2_grpc.py COPYRIGHT')
            print('\t@mkdir -p $(@D)')
            print('\t$(python) $(_py_rewrite) $< .cache/python COPYRIGHT > $@')
            print()
            print(f'$(_py_gen_tmp_dir)/{p}_pb2.py $(_py_gen_tmp_dir)/{p}_pb2_grpc.py: $(proto_dir)/{p}.proto COPYRIGHT')
            print('\t@mkdir -p $(_py_gen_tmp_dir)')
            print('\t$(python) -m grpc_tools.protoc -I$(proto_dir) --python_out=$(_py_gen_tmp_dir) --grpc_python_out=$(_py_gen_tmp_dir) $<')


if __name__ == '__main__':
    main()
