#!/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


CHAPTER_PAT_STR = r'.+"head-ltitle"\>[-\.\w]+\((?P<chap>\d)\)'
CHAPTER_PAT = re.compile(CHAPTER_PAT_STR)


def get_args():
    pars = argparse.ArgumentParser()
    for arg in [{
            "flags": ["--html-manuals"],
            "nargs": "+",
            "required": True,
            "type": pathlib.Path,
    }, {
            "flags": ["--man-html-dir"],
            "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_manual(man, man_html_dir):
    record = {
        "title": re.sub("litani-", "litani ", man.stem),
        "anchor": man.stem,
        "body": [],
        "chapter": get_chapter(man_html_dir / man.name),
    }
    with open(man) as handle:
        for line in handle:
            record["body"].append(line.rstrip())
    return record


def get_chapter(man_html):
    with open(man_html) as handle:
        for line in handle:
            m = CHAPTER_PAT.match(line)
            if m:
                return int(m["chap"])
    raise UserWarning(
        f"No line of man html output '{man_html}' matched chapter pattern "
        f"'{CHAPTER_PAT_STR}'")


def get_manuals(html_manuals, man_html_dir):
    ret = []
    for man in html_manuals:
        ret.append(get_manual(man, man_html_dir))
    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, args.man_html_dir)

    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()
