#!/usr/bin/env python3
"""SVG polygons + circles -> DXF R12, for laser cutters.

Usage: svg2dxf.py input.svg output.dxf
Polygons become closed POLYLINEs; circles become CIRCLE entities.
Y is flipped using the viewBox height (SVG y-down -> DXF y-up).
"""
import re
import sys


def parse_svg(svg_text):
    polys, circles = [], []
    for m in re.finditer(r'<polygon[^>]*points="([^"]+)"', svg_text):
        pts = []
        for pair in m.group(1).split():
            x, y = pair.split(",")
            pts.append((float(x), float(y)))
        polys.append(pts)
    for m in re.finditer(r'<circle\b([^>]*)/?>', svg_text):
        attrs = m.group(1)
        cx = re.search(r'cx="([-\d.]+)"', attrs)
        cy = re.search(r'cy="([-\d.]+)"', attrs)
        r = re.search(r'r="([\d.]+)"', attrs)
        if cx and cy and r:
            circles.append((float(cx.group(1)), float(cy.group(1)),
                            float(r.group(1))))
    return polys, circles


def svg_to_dxf(svg_path, dxf_path):
    with open(svg_path, encoding="utf-8") as f:
        text = f.read()

    vb = re.search(r'viewBox="0 0 ([\d.]+) ([\d.]+)"', text)
    h = float(vb.group(2)) if vb else 0.0

    polys, circles = parse_svg(text)
    if not polys and not circles:
        sys.exit("no <polygon> or <circle> found")

    out = ["0", "SECTION", "2", "HEADER", "9", "$INSUNITS", "70", "4",
           "0", "ENDSEC", "0", "SECTION", "2", "ENTITIES"]

    for pts in polys:                       # closed polyline
        out += ["0", "POLYLINE", "8", "0", "66", "1", "70", "1"]
        for x, y in pts:
            out += ["0", "VERTEX", "8", "0",
                    "10", f"{x:.4f}", "20", f"{h - y:.4f}"]
        out += ["0", "SEQEND"]

    for cx, cy, r in circles:               # circle entity
        out += ["0", "CIRCLE", "8", "0",
                "10", f"{cx:.4f}", "20", f"{h - cy:.4f}", "40", f"{r:.4f}"]

    out += ["0", "ENDSEC", "0", "EOF"]

    with open(dxf_path, "w", encoding="utf-8") as f:
        f.write("\n".join(out))
    print(f"OK: {len(polys)} polylines + {len(circles)} circles -> {dxf_path}")


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit("usage: svg2dxf.py input.svg output.dxf")
    svg_to_dxf(sys.argv[1], sys.argv[2])
