import json
from typing import Dict
from pathlib import Path
from codegen.datatypes import CDataType, CStruct
from codegen.constants import WAPP_REPO_ROOT, DBL_LIST_DATA
from codegen.dbl_list.make_dbl_list import DblListData, make_dbl_list


def main(types_file: Path | None):
    dbl_list_datatypes: Dict[CDataType, DblListData] = {}

    if types_file is not None and types_file.is_file() and "json" in types_file.suffix.lower():
        with types_file.open("r") as infile:
            datatypes = json.load(infile)
            dbl_list_data = datatypes.get(DBL_LIST_DATA)

            if dbl_list_data is not None and isinstance(dbl_list_data, dict):
                dbl_list_datatypes = {k: DblListData.from_dict(v) for k, v in dbl_list_data.items()}

    make_dbl_list(dbl_list_datatypes)

    # Save example types file
    custom_struct = CStruct(name="custom_type", cargs=[], typedef_name="CustomType")
    example = {
        DBL_LIST_DATA: {
            "CustomType": DblListData(
                node_typename="CustomTypeNode",
                list_typename="CustomTypeList",
                hdr_decl_types=[custom_struct],
            ).to_dict()
        },
    }

    example_file = WAPP_REPO_ROOT / "codegen_custom_data_example.json"
    with example_file.open("w") as outfile:
        json.dump(example, outfile, indent=2)


if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser()
    parser.add_argument("-f", "--types-file", type=Path, help="JSON file containing custom types for codegen")

    args = parser.parse_args()

    main(args.types_file)
