from pymxs import runtime as mxs
from pathlib import Path
import os

def export_to_usd(file_path):
    # Make up the USD file name.
    usd_file_path = os.path.splitext(file_path)[0] + ".usd"
    usd_log_path = os.path.splitext(file_path)[0] + ".log"
    print(f"Exporting {file_path} to {usd_file_path}")

    # Open the .max file
    mxs.loadMaxFile(file_path)

    # Configure the export options
    export_options = mxs.USDExporter.createOptions()
    export_options.Meshes = True
    export_options.Lights = False
    export_options.Cameras = False
    export_options.Materials = False
    export_options.FileFormat = mxs.name("binary")
    export_options.UpAxis = mxs.name("y")
    export_options.LogLevel = mxs.name("info")
    export_options.LogPath = usd_log_path
    export_options.PreserveEdgeOrientation = True
    export_options.Normals = mxs.name("none")
    export_options.TimeMode = mxs.name("current")

    mxs.USDexporter.UIOptions = export_options

    result = mxs.USDExporter.ExportFile(usd_file_path, exportOptions=export_options)
    if result:
        print('export succeeded')
    else:
        print('export failed')


def process_files(directory):
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        if os.path.isdir(file_path):
            process_files(file_path)
        elif filename.lower().endswith(".max"):
            # Export to USD
            export_to_usd(file_path)


if __name__ == "__main__":
    source_dir = str(Path.cwd())
    print(f"Process folder {source_dir}")
    process_files(source_dir)
