import json, os

def is_target_subjson(item):
    """Check if the item contains IfcMappedItem."""
    if item.get("type") == "IfcShapeRepresentation":
        if item.get("items"):
            for sub_item in item["items"]:
                if sub_item.get("type") == "IfcBooleanClippingResult":
                    return True
    return False

def process_json_data(data):
    identified_subjsons = []
    remaining_data = []

    for item in data:
        if is_target_subjson(item):
            identified_subjsons.append(item)
        else:
            remaining_data.append(item)

    return identified_subjsons, remaining_data

def main(input_file, identified_output_file, remaining_output_file):
    # Read the input JSON file
    with open(input_file, 'r') as f:
        json_data = json.load(f)

    # Process the data
    identified_subjsons, remaining_data = process_json_data(json_data["data"])

    # Create the new JSON structures
    json_with_identified_subjsons = {
        "type": json_data["type"],
        "version": json_data["version"],
        "schemaIdentifier": json_data["schemaIdentifier"],
        "originatingSystem": json_data["originatingSystem"],
        "preprocessorVersion": json_data["preprocessorVersion"],
        "timeStamp": json_data["timeStamp"],
        "data": identified_subjsons
    }

    json_with_remaining_data = {
        "type": json_data["type"],
        "version": json_data["version"],
        "schemaIdentifier": json_data["schemaIdentifier"],
        "originatingSystem": json_data["originatingSystem"],
        "preprocessorVersion": json_data["preprocessorVersion"],
        "timeStamp": json_data["timeStamp"],
        "data": remaining_data
    }

    # Write the new JSON files
    with open(identified_output_file, 'w') as f:
        json.dump(json_with_identified_subjsons, f, indent=4)

    with open(remaining_output_file, 'w') as f:
        json.dump(json_with_remaining_data, f, indent=4)

    print(f"Processing completed. New JSON files created: '{identified_output_file}' and '{remaining_output_file}'")


if __name__ == "__main__":
    input_file = 'rimond_model_madrid_v3_beautified.json'  # Replace with the path to your input JSON file
    identified_output_file = 'helper_json_2.json'
    remaining_output_file = 'rimond_model_madrid_v3_beautified.json'

    main(input_file, identified_output_file, remaining_output_file)
