"""
Utility to autogenerate generic HAL headers.

Usage::

    python3 gd32headers.py [-p /path/to/HAL] [-o /path/to/output_dir]

Copyright (c) 2022 Teslabs Engineering S.L.

SPDX-License-Identifier: Apache-2.0
"""

import argparse
from pathlib import Path
import re
import shutil


REPO_ROOT = Path(__file__).absolute().parents[1]
"""Repository root (used for input/output default folders)."""


def main(hal_path, output):
    """Entry point.

    Args:
        hal_path: HAL repository path.
        output: Output directory.
    """

    # obtain all available APIs for each series
    apis = dict()
    for entry in sorted(hal_path.iterdir()):
        if not entry.is_dir() or not entry.name.startswith("gd32"):
            continue

        # obtain series API headers
        series_headers = entry / "standard_peripheral" / "include"
        for header in series_headers.iterdir():
            m = re.match(r"^gd32[a-z0-9]+_([a-z0-9]+)\.h$", header.name)
            if not m:
                continue

            api = m.group(1)

            # ignore libopt (not an API)
            if api == "libopt":
                continue

            if api not in apis:
                apis[api] = list()
            apis[api].append(entry.name)

    if output.exists():
        shutil.rmtree(output)
    output.mkdir(parents=True)

    for api, all_series in apis.items():
        header_file = output / ("gd32_" + api + ".h")
        with open(header_file, "w") as f:
            f.write("/*\n")
            f.write(" * NOTE: Autogenerated file using gd32headers.py\n")
            f.write(" *\n")
            f.write(" * SPDX-License-Identifier: Apache-2.0\n")
            f.write(" */\n\n")

            for i, series in enumerate(all_series):
                f.write("#if" if i == 0 else "#elif")
                f.write(f" defined(CONFIG_SOC_SERIES_{series.upper()})\n")
                f.write(f"#include <{series}_{api}.h>\n")
            f.write("#endif\n")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-p",
        "--hal-path",
        type=Path,
        default=REPO_ROOT,
        help="Path to the HAL repository root",
    )
    parser.add_argument(
        "-o",
        "--output",
        type=Path,
        default=REPO_ROOT / "common_include",
        help="Output directory",
    )
    args = parser.parse_args()

    main(args.hal_path, args.output)
