import json
import glob
import regex as re

JSON_SCHEMA: dict = {"definitions": {}, "$ref": "#/definitions/solution-definition"}
files: dict = {}

# Get a list of all .json files in the directory
json_files = glob.glob("*.json")
for file_name in json_files:
    if file_name == "combined.schema.json":
        continue
    with open(file_name, "r") as f:
        txt = f.read()  # jc-web-view.schema.json
        # txt = txt.replace('"$schema": "http://json-schema.org/draft-07/schema#",', '')
        txt = re.sub(r"http://jigx.+schema[.]json#/", "#/", txt)
        data = json.loads(txt)
        files[file_name] = data

# print(len(files))  # 116

# Merge files
refs: dict = {}
for file_name, file_content in files.items():
    defs = file_content.get("definitions")
    if defs and len(defs) > 0:
        for key, value in defs.items():
            JSON_SCHEMA["definitions"][key] = value
        del file_content["definitions"]

    base_name = file_name.replace(
        ".schema.json", ""
    )  # jc-web-view.schema.json -> jc-web-view
    JSON_SCHEMA["definitions"][base_name] = file_content
    refs[f"http://jigx.com/schemas/{file_name}"] = f"#/definitions/{base_name}"


# Replace refs
txt = json.dumps(JSON_SCHEMA, indent=2)
for k, v in refs.items():
    txt = txt.replace(k, v)
JSON_SCHEMA = json.loads(txt)
JSON_SCHEMA["definitions"] = dict(sorted(JSON_SCHEMA["definitions"].items()))

# Fixups
val = JSON_SCHEMA["definitions"]["solution-definition"]["properties"]
val["datasources"] = JSON_SCHEMA["definitions"]["jig-default-specification"][
    "properties"
]["datasources"]


# Walk tree and remove noise
def elide_noise(parent_key, node):
    if isinstance(node, dict):
        for key, val in list(node.items()):
            if key == "$id":
                node[key] = f"#/definitions/{parent_key}"
            elif key == "definitions" and isinstance(val, dict) and len(val) == 0:
                del node[key]
            elif key in ["templateRef", "markdownDescription", "defaultSnippets"]:
                del node[key]
            # elif key.startswith("Nullable<alias"):
            #     del node[key]
            elif isinstance(val, dict):
                # depr = val.get("deprecated")
                # if depr is not None and isinstance(depr, str):
                #     depr = depr.lower()
                #     if "deprecated" in depr:  # or "experimental" in depr:
                #         del node[key]
                #         continue
                elide_noise(key, val)
            else:
                elide_noise(key, val)

    elif isinstance(node, list):
        for i in node:
            elide_noise(parent_key, i)


elide_noise("solution", JSON_SCHEMA)

# Walk the schema and validate refs
all_defs = set(JSON_SCHEMA["definitions"].keys())


def validate_refs(node):
    if isinstance(node, dict):
        for key, val in node.items():
            if key == "$ref":
                val.replace("#/definitions/", "") in all_defs
                # assert val.replace("#/definitions/", "") in all_defs, f"Invalid ref: {val}"
            else:
                validate_refs(val)

    elif isinstance(node, list):
        for i in node:
            validate_refs(i)


validate_refs(JSON_SCHEMA)

# Write to file
with open("combined.schema.json", "w") as f:
    json.dump(JSON_SCHEMA, f, indent=2)
