import re
import os

def extract_svg_path_coordinates(svg_file):
    with open(svg_file, 'r', encoding='utf-8') as file:
        svg_content = file.read()
    
    # Find the path data
    path_match = re.search(r'<path d="(.*?)"', svg_content, re.DOTALL)
    if not path_match:
        raise ValueError("No path data found in SVG file")
    
    path_data = path_match.group(1).strip()
    
    # Extract coordinates (M and L commands)
    coordinates = []
    for match in re.finditer(r'([ML])\s*([\d.-]+),([\d.-]+)', path_data):
        x, y = float(match.group(2)), float(match.group(3))
        coordinates.append([x, y])
    
    return coordinates

def export_to_openscad(coords, output_file):
    with open(output_file, 'w', encoding='utf-8') as file:
        file.write(f"polygon(points={coords});\n")

def main():
    # Using raw strings for file paths to avoid escape sequence issues
    svg_file = r"P:\Docs\openscad\testpoly.svg"
    output_file = r"P:\Docs\openscad\testpolyop.scad"
    
    if not os.path.isfile(svg_file):
        print(f"Error: File '{svg_file}' not found.")
        return
    
    try:
        coords = extract_svg_path_coordinates(svg_file)
        export_to_openscad(coords, output_file)
        print(f"Exported {len(coords)} points to {output_file}")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    main()
