import onnx
import os

# The path to the ONNX model that failed to load
# This is generated by the failing `Test_GPT::test_gpt`
MODEL_FILENAME = "docs/onnx/examples/gpt/gpt.onnx"


def find_empty_name_in_model(model_path):
    """
    Loads an ONNX model and inspects its functions to find
    any inputs or outputs with an illegal empty name.
    """
    if not os.path.exists(model_path):
        print(f"❌ Error: Model file not found at '{model_path}'")
        print("Please run the failing test first to generate the model file.")
        return

    print(f"🔎 Loading and inspecting model: {model_path}\n")

    try:
        # Load the ONNX model from the file
        model = onnx.load(model_path)

        # Iterate through all the functions defined in the model
        for func in model.functions:
            # We are looking for the specific function mentioned in the error
            if "GPTTransformerStack" in func.name:
                print(f"--- Examining Function: {func.name} ---")

                found_error = False

                # Check all inputs for an empty string name
                for i, input_name in enumerate(func.input):
                    if not input_name:  # This checks for ""
                        print(f"  [INPUT {i}] 🔴 ERROR: Found empty input name!")
                        found_error = True
                    else:
                        print(f"  [INPUT {i}] '{input_name}'")

                # Check all outputs for an empty string name
                for i, output_name in enumerate(func.output):
                    if not output_name:  # This checks for ""
                        print(f"  [OUTPUT {i}] 🔴 ERROR: Found empty output name!")
                        found_error = True
                    else:
                        print(f"  [OUTPUT {i}] '{output_name}'")

                if found_error:
                    print(
                        "\n✅ Diagnosis confirmed: The converter produced a function with an empty name, violating the ONNX schema."
                    )
                    return
                else:
                    print("  ✅ No empty names found in this function's signature.")

    except Exception as e:
        print("\n❌ An error occurred while trying to load or parse the ONNX model.")
        print(f"   Error: {e}")
        print(
            "   This can happen if the model is severely corrupted, but the error message you saw"
        )
        print(
            "   '!(it.GetName().empty())' strongly suggests the model was created but is invalid."
        )


if __name__ == "__main__":
    find_empty_name_in_model(MODEL_FILENAME)
