#!/usr/bin/env python3

import os
import xml
from xml.etree import ElementTree
from ament_index_python import (
    get_package_share_path,
    PackageNotFoundError,
    get_search_paths,
)

from kalman_bringup.utils import get_arg_decls


def capitalize_module_name(name: str) -> str:
    words = name.split("_")
    word = [w.capitalize() for w in words]
    return "".join(word)


def get_pkg_desc(pkg: str) -> str:
    try:
        pkg_path = get_package_share_path(pkg)
    except PackageNotFoundError:
        return ""
    try:
        pkg_xml = pkg_path / "package.xml"
        with open(pkg_xml, "r") as f:
            pkg_xml = f.read()
        pkg_xml = ElementTree.fromstring(pkg_xml)
        text = pkg_xml.find("description").text
        text = text.replace("\n", " ").replace("\t", " ")
        while "  " in text:
            text = text.replace("  ", " ")
        return text
    except Exception as e:
        print(e)
        return ""


if __name__ == "__main__":
    paths = [
        p
        for p in get_search_paths()
        if ("/opt/ros/" not in p and "kalman_bringup" not in p)
    ]
    module_pkgs = [(x.split("/")[-1]) for x in paths]
    module_pkgs = sorted(module_pkgs)

    launch_args = (
        {}
    )  # module_name -> [(arg1_name, arg1_desc, arg1_choices), (arg2_name, ...]

    for pkg in module_pkgs:
        module_name = pkg if not pkg.startswith("kalman_") else pkg[7:]
        try:
            launch_path = str(
                get_package_share_path(f"{pkg}") / "launch" / f"{module_name}.launch.py"
            )
        except PackageNotFoundError:
            print(f'"{pkg}" is not a kalman_ module.')
            continue

        if os.path.exists(launch_path):
            launch_args[module_name] = get_arg_decls(launch_path)
            if len(launch_args[module_name]) == 0:
                launch_args[module_name] = []

    print("# AUTO-GENERATED FILE. DO NOT EDIT.")
    print("# SEE: kalman_bringup/tools/gen_type_hints")
    print()
    print("from typing import Literal, TypedDict\n\n")

    launch_args_items = sorted(launch_args.items(), key=lambda x: x[0])
    for module_name, args in launch_args_items:
        print(f"class {capitalize_module_name(module_name)}(TypedDict):")
        if args:
            for arg_name, desc, choices in args:
                if choices:
                    print(f"    {arg_name}: Literal{sorted(choices)}".replace("'", '"'))
                else:
                    print(f"    {arg_name}: str")
                print(f'    "{desc}"')
        else:
            print("    pass")
        print("\n")

    print("class BringupConfig(TypedDict):")
    launch_args_keys = sorted(launch_args.keys())
    for module_name in launch_args_keys:
        print(f"    {module_name}: {capitalize_module_name(module_name)}")
        desc = get_pkg_desc(f"kalman_{module_name}")
        if desc:
            print(f'    "{desc}"')
