import os, glob, argparse, xml.etree.ElementTree as ET
from PIL import Image, ImageDraw

def svg_to_silhouette(svg_path, raster=1024):
    tree = ET.parse(svg_path)
    root = tree.getroot()
    # 读取 viewBox 以把 SVG 坐标映射到像素
    vb = root.get("viewBox")
    if vb:
        minx, miny, w, h = map(float, vb.split())
    else:
        # 没有 viewBox 时退化到宽高
        w = float(root.get("width", "1000"))
        h = float(root.get("height","1000"))
        minx = miny = 0.0

    img = Image.new("L", (raster, raster), 255)
    draw = ImageDraw.Draw(img)

    def map_pt(x, y):
        px = int(round((x - minx) / w * (raster - 1)))
        py = int(round((y - miny) / h * (raster - 1)))
        return (px, py)

    # 找所有 polygon（Tangram 文件就是 7 个 polygon）
    for poly in root.iter():
        if poly.tag.endswith("polygon") and poly.get("points"):
            pts = []
            for p in poly.get("points").strip().split():
                if "," in p:
                    x, y = map(float, p.split(","))
                    pts.append(map_pt(x, y))
            if len(pts) >= 3:
                draw.polygon(pts, fill=0)

    return img

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--in_dir", required=True)   # tangrams-svg 目录
    ap.add_argument("--out_dir", required=True)  # 输出轮廓目录
    ap.add_argument("--raster", type=int, default=1024)
    ap.add_argument("--ids_txt", type=str, help="可选，仅处理清单里的 id（每行一个，如 page1-1）")
    ap.add_argument("--recursive", action="store_true")
    args = ap.parse_args()

    os.makedirs(args.out_dir, exist_ok=True)
    allow = None
    if args.ids_txt and os.path.exists(args.ids_txt):
        allow = set(x.strip() for x in open(args.ids_txt, "r", encoding="utf-8") if x.strip())

    pattern = "**/*.svg" if args.recursive else "*.svg"
    svgs = sorted(glob.glob(os.path.join(args.in_dir, pattern), recursive=args.recursive))
    kept = 0
    for sp in svgs:
        stem = os.path.splitext(os.path.basename(sp))[0]
        if allow and stem not in allow:
            continue
        try:
            img = svg_to_silhouette(sp, raster=args.raster)
            img.save(os.path.join(args.out_dir, f"{stem}.png"))
            kept += 1
        except Exception as e:
            print(f"[SKIP] {stem}: {e}")
    print(f"[DONE] wrote {kept} outline(s) -> {args.out_dir}")

if __name__ == "__main__":
    main()