import itertools
import json
import sys
import numpy as np
import uuid

debug = False

# Load file
obj = json.load(open(sys.argv[1]))

# New file
model = {}

def show_nodes():
    for item in obj:
        if item == "header":
            if debug: print("HEADER")
            model["header"] = {}
            for data in obj[item]:
                if debug: print(" ", data, ":", obj[item][data])
                model["header"][data] = obj[item][data]
        elif item == "imports":
            if debug: print("IMPORTS")
            model["imports"] = {}
            lst = []
            for data in obj[item]:
                if debug: print(" ", data)
                lst.append(obj[item][1])
            model["imports"] = obj[item]
        elif item == "schemas":
            model["schemas"] = obj[item]
            if debug: print("SCHEMAS")
            for data in obj[item]:
                if debug: print(" ", data)
        elif item == "data":
            if debug: print("DATA")
            for data in obj[item]:
                #print(" ", data)
                for d in data:
                    if d == "attributes":
                        #print(d,data[d])
                        pass
        else:
            print(item)

def add_site(childrens):
    ref = str(uuid.uuid4())
    site = {
        "path" : ref,
        "children" : childrens
    }
    return site,ref

def add_plane():

    ref = str(uuid.uuid4())
    mesh = {
        "faceVertexIndices" : [0,1,2,0,2,3],
        "points" : [
            [0,0,0],
            [10,0,0],
            [10,10,0],
            [0,10,0],
        ]
    }

    plane = {
        "path" : ref,
        "attributes" : {
            "usd::usdgeom::mesh": mesh
        }
    }

    return plane,ref

def add_obj(path):

    ref = str(uuid.uuid4())
    vertices = []
    faces = []

    with open(path, "r") as f:
        for line in f:
            if line.startswith("v "):
                parts = line.strip().split()
                vertices.append(parts[1:4])

            elif line.startswith("f "):
                parts = line.strip().split()[1:]
                face_indices = [p.split("/")[0] for p in parts]
                faces.append(face_indices)

    f = [int(x) for sub in faces for x in sub]
    v = [[float(x) for x in sub] for sub in vertices]

    mesh = {
        "faceVertexIndices" : f,
        "points" : v
    }

    obj = {
        "path" : ref,
        "attributes" : {
            "usd::usdgeom::mesh": mesh
        }
    }

    return obj, ref


# Example usage:
# export_obj_raw("model.obj")


def generate():
    ostream = None
    try:
        ostream = open(sys.argv[2], 'w')
    except: 
        ostream = sys.stdout

    items = []

    plane, plane_id = add_plane()
    items.append(plane)

    obj, obj_id = add_obj("sphere.obj")
    items.append(obj)

    childrens = {
        "Site" : plane_id,
        "Obj" : obj_id

    }

    site, site_id = add_site(childrens)
    items.append(site)

    model["data"] = items

    json.dump(model, ostream, indent=2)

    if debug: print("MODEL")
    if debug: print(model)


def show_meshes():
    for d in [d for d in list(obj['data']) if d.get('attributes', {}).get('usd::usdgeom::mesh')]:
        mesh = d['attributes']['usd::usdgeom::mesh']
        print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
        print("FACES")
        print(mesh['faceVertexIndices'])
        print("VERTICES")
        print(mesh['points'])


show_nodes()
generate()
#show_meshes()

