import os

def parse_stl(file_path):
    """
    Parses an ASCII STL file and extracts the vertices of each facet.
    
    :param file_path: Path to the STL file.
    :return: List of facets, where each facet is a list of three vertices.
    """
    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()
    except FileNotFoundError:
        raise FileNotFoundError(f"STL file not found: {file_path}")
    except IOError:
        raise IOError(f"Error reading file: {file_path}")

    facets = []
    current_facet = []

    for line in lines:
        stripped_line = line.strip()
        if stripped_line.startswith('vertex'):
            parts = stripped_line.split()
            try:
                vertex = [float(parts[1]), float(parts[2]), float(parts[3])]
            except (ValueError, IndexError):
                raise ValueError(f"Invalid vertex format: {stripped_line}")
            current_facet.append(vertex)
            if len(current_facet) == 3:
                facets.append(current_facet)
                current_facet = []

    return facets

def generate_openscad_code(facets, sphere_radius=1):
    """
    Generates OpenSCAD code to plot spheres at each vertex of the facets and hull the spheres.

    :param facets: List of facets, where each facet is a list of three vertices.
    :param sphere_radius: Radius of the spheres to be plotted at each vertex.
    :return: String containing the OpenSCAD code.
    """
    openscad_code = []

    for i, facet in enumerate(facets):
        openscad_code.append(f"// Facet {i + 1}")
        openscad_code.append("hull() {")
        for vertex in facet:
            x, y, z = vertex
            openscad_code.append(f"    translate([{x}, {y}, {z}])")
            openscad_code.append(f"        sphere(r = {sphere_radius});")
        openscad_code.append("}")
        openscad_code.append("")

    return "\n".join(openscad_code)

def main():
    stl_file_path = "P:\Docs\openscad\\brokeasctestcubes.stl"
   
    output_file_path = "P:\Docs\openscad\\brokeasctestscad"
    sphere_radius = 1

    if not os.path.isfile(stl_file_path):
        print(f"Error: STL file does not exist at the specified path: {stl_file_path}")
        return

    try:
        facets = parse_stl(stl_file_path)
        openscad_code = generate_openscad_code(facets, sphere_radius)

        with open(output_file_path, 'w') as file:
            file.write(openscad_code)
        
        print(f"OpenSCAD code successfully written to {output_file_path}")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    main()
