# converter.py
# A Python script for use with FreeCAD's command-line interface.
# Converts a mesh file (like STL) into a solid model and exports it to STEP.

import sys
import FreeCAD
import Part
import Mesh

# --- Argument Validation ---
# The script name is sys.argv[0], followed by FreeCAD's internal args.
# The actual script arguments start after that. We expect two: input and output files.
# FreeCAD adds its own arguments, so we find our files at the end of the list.
if len(sys.argv) < 3:
    print("Converter script usage: <input_file> <output_file>")
    sys.exit(1)

input_file_path = sys.argv[-2]
output_file_path = sys.argv[-1]

print(f"Input file: {input_file_path}")
print(f"Output file: {output_file_path}")

# --- Conversion Logic ---
try:
    # 1. Load the mesh from the input STL file
    mesh = Mesh.read(input_file_path)

    # 2. Split the mesh into its separate, unconnected components (shells)
    components = mesh.getSeparateComponents()
    print(f"Found {len(components)} separate components in the mesh.")

    # 3. Convert each component mesh into a solid shape
    solids = []
    for i, component_mesh in enumerate(components):
        try:
            # Create a shape from the mesh component
            shape = Part.Shape()
            shape.makeShapeFromMesh(component_mesh.Topology, 0.1)

            # Use a more robust method to ensure the shape is a solid
            # This can fix minor issues and is more reliable than direct conversion.
            if not shape.isNull() and shape.Faces:
                solid = Part.Solid(Part.Shell(shape.Faces))
                if solid.Volume > 0:
                    solids.append(solid)
                else:
                    # If creating a solid fails, try refining it first.
                    refined_shape = shape.removeSplitter()
                    if not refined_shape.isNull() and refined_shape.Faces:
                        solid = Part.Solid(Part.Shell(refined_shape.Faces))
                        if solid.Volume > 0:
                            solids.append(solid)
                        else:
                             print(f"Warning: Component {i+1} could not be converted to a solid after refining.")
                    else:
                        print(f"Warning: Component {i+1} became null after refining.")
            else:
                 print(f"Warning: Component {i+1} could not be converted to a shape.")

        except Exception as ex:
             print(f"Warning: An exception occurred while processing component {i+1}: {ex}")

    if not solids:
        print("Error: No valid solids could be created from the mesh.")
        sys.exit(1)

    # 4. Combine all solids into a single compound part for export
    if len(solids) > 1:
        result_shape = Part.Compound(solids)
    else:
        result_shape = solids[0]

    # 5. Export the final shape to a STEP file
    result_shape.exportStep(output_file_path)

    print("STEP export completed successfully.")
    sys.exit(0)

except Exception as e:
    print(f"An error occurred during FreeCAD conversion: {e}")
    sys.exit(1) 