#!/usr/bin/env python3
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.


import argparse
import pathlib
import re

import jinja2


def get_args():
    pars = argparse.ArgumentParser()
    for arg in [{
            "flags": ["--html-manuals"],
            "nargs": "+",
            "required": True,
            "type": pathlib.Path,
    }, {
            "flags": ["--template-dir"],
            "required": True,
            "type": pathlib.Path,
    }, {
            "flags": ["--out-file"],
            "required": True,
            "type": pathlib.Path,
    }]:
        flags = arg.pop("flags")
        pars.add_argument(*flags, **arg)
    return pars.parse_args()


def get_manuals(html_manuals):
    ret = []
    for man in html_manuals:
        record = {
            "title": re.sub("litani-", "litani ", man.stem),
            "anchor": man.stem,
            "body": [],
        }
        with open(man) as handle:
            for line in handle:
                record["body"].append(line.rstrip())
        ret.append(record)
    return ret


def main():
    args = get_args()
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(str(args.template_dir)),
        autoescape=jinja2.select_autoescape(
            enabled_extensions=('html'),
            default_for_string=True))
    manuals = get_manuals(args.html_manuals)

    templ = env.get_template("index.jinja.html")
    page = templ.render(manuals=manuals)

    with open(args.out_file, "w") as handle:
        print(page, file=handle)



if __name__ == "__main__":
    main()
