File size: 43,170 Bytes
b16e4fc
 
 
 
 
 
 
 
 
 
 
fbcaabd
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
3ce01e2
 
 
 
 
 
 
 
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30ea689
 
 
 
 
 
 
 
 
 
 
 
 
 
b16e4fc
30ea689
 
b16e4fc
 
 
 
 
 
30ea689
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
30ea689
 
 
 
 
 
 
 
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8ac6b3
b16e4fc
 
c8ac6b3
 
 
 
 
 
 
 
 
 
 
 
 
 
b16e4fc
 
 
 
 
 
 
 
 
 
c8ac6b3
 
 
 
 
 
943fe07
b16e4fc
 
 
 
 
 
 
c8ac6b3
 
 
b16e4fc
 
943fe07
 
 
 
 
b16e4fc
c8ac6b3
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8ac6b3
 
 
 
 
b16e4fc
943fe07
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbcaabd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1f344e
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30ea689
 
 
 
 
 
 
 
 
 
 
b16e4fc
 
 
 
30ea689
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8ac6b3
 
 
b16e4fc
943fe07
 
b16e4fc
 
 
 
 
 
943fe07
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
943fe07
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1f344e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ce01e2
 
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ce01e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b16e4fc
 
 
 
3ce01e2
 
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
3ce01e2
b16e4fc
 
 
 
 
 
 
 
 
 
 
3ce01e2
 
 
 
b16e4fc
 
 
 
 
3ce01e2
b16e4fc
 
 
 
 
b1f344e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1f344e
 
 
 
 
 
b16e4fc
b1f344e
 
 
 
 
 
 
b16e4fc
 
 
b1f344e
 
b16e4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
"""
Marshall's Plasma Design Studio.

Pipeline: client reference image -> auto-trace -> dimensioned vector -> DXF/SVG
for the plasma table.
"""
from __future__ import annotations

import base64
import io
import math
import os
import uuid
from collections import OrderedDict
from pathlib import Path

import ezdxf
import numpy as np
from flask import Flask, jsonify, request, send_file, send_from_directory
from PIL import Image, ImageOps
from potrace import Bitmap, POTRACE_TURNPOLICY_MINORITY
from scipy.ndimage import distance_transform_edt, label

STATIC_DIR = Path(__file__).parent / "static"
app = Flask(__name__, static_folder=str(STATIC_DIR), static_url_path="/static")

MAX_IMAGE_DIM = 4200  # pixels; downscale large uploads before tracing/segmentation
# 1200 was sized for a client photo traced onto a two-foot sign.  On a ten
# foot fence panel it lands at ~9 px/inch, which is one pixel per 0.105" and
# destroys fine linework (snow cracks, treeline needles, a fly line) on
# import, before the trace ever runs.
MAX_PANEL_PX = 6000  # cap composed-panel pixel dimensions to keep tracing snappy
# Raising MAX_IMAGE_DIM alone does nothing: this cap independently throttles
# a 120" panel to 18 px/inch.  At 6000 a 120" panel holds the full 40 px/inch
# (0.025"/px), which is finer than any plasma kerf.

MASK_CACHE_LIMIT = 8  # most recent composed/traced masks kept for /analyze
_mask_cache: "OrderedDict[str, np.ndarray]" = OrderedDict()

IMAGE_CACHE_LIMIT = 32  # most recent uploaded images, keyed by token
_image_cache: "OrderedDict[str, Image.Image]" = OrderedDict()

LAYER_MASK_CACHE_LIMIT = 64  # cache per-layer masks, keyed by (token + mode + params hash)
_layer_mask_cache: "OrderedDict[str, np.ndarray]" = OrderedDict()


def _cache_mask(mask: np.ndarray) -> str:
    token = uuid.uuid4().hex
    _mask_cache[token] = mask
    while len(_mask_cache) > MASK_CACHE_LIMIT:
        _mask_cache.popitem(last=False)
    return token


def _cache_image(img: Image.Image) -> str:
    token = uuid.uuid4().hex
    _image_cache[token] = img
    while len(_image_cache) > IMAGE_CACHE_LIMIT:
        _image_cache.popitem(last=False)
    return token


def _cache_layer_mask(key: str, mask: np.ndarray) -> None:
    _layer_mask_cache[key] = mask
    _layer_mask_cache.move_to_end(key)
    while len(_layer_mask_cache) > LAYER_MASK_CACHE_LIMIT:
        _layer_mask_cache.popitem(last=False)


def _otsu_threshold(arr: np.ndarray) -> int:
    """Otsu's method: pick the threshold that maximizes inter-class variance."""
    hist, _ = np.histogram(arr, bins=256, range=(0, 256))
    total = arr.size
    if total == 0:
        return 128
    sum_total = float((np.arange(256) * hist).sum())
    sum_b = 0.0
    w_b = 0
    var_max = 0.0
    threshold = 128
    for t in range(256):
        w_b += int(hist[t])
        if w_b == 0:
            continue
        w_f = total - w_b
        if w_f == 0:
            break
        sum_b += t * float(hist[t])
        m_b = sum_b / w_b
        m_f = (sum_total - sum_b) / w_f
        var_between = w_b * w_f * (m_b - m_f) ** 2
        if var_between > var_max:
            var_max = var_between
            threshold = t
    return threshold


def _open_resized(file_storage, mode: str = "RGB") -> Image.Image:
    img = Image.open(file_storage.stream).convert(mode)
    img = ImageOps.exif_transpose(img)
    if max(img.size) > MAX_IMAGE_DIM:
        scale = MAX_IMAGE_DIM / max(img.size)
        new_size = (int(img.size[0] * scale), int(img.size[1] * scale))
        img = img.resize(new_size, Image.LANCZOS)
    return img


def load_and_prepare(file_storage, threshold: int, invert: bool, blur: float,
                     auto_threshold: bool = False) -> np.ndarray:
    img = _open_resized(file_storage, mode="L")
    if blur and blur > 0:
        from PIL import ImageFilter
        img = img.filter(ImageFilter.GaussianBlur(radius=blur))
    arr = np.array(img)
    if auto_threshold:
        threshold = _otsu_threshold(arr)
    # potracer's Bitmap traces False regions when True touches the array edge.
    # For a dark subject on light background, mark light pixels True so the
    # dark subject is what gets outlined (no phantom outer hull).
    mask = arr >= threshold if not invert else arr < threshold
    return mask, int(threshold)


def subject_mask(file_storage, alpha_cutoff: int = 50, invert: bool = False) -> np.ndarray:
    """Use rembg (U-2-Net) to extract foreground; return mask in our convention
    (True = background, False = subject) so trace outlines the subject."""
    img = _open_resized(file_storage, mode="RGBA")
    return subject_mask_from_image(img, alpha_cutoff=alpha_cutoff, invert=invert)


def subject_mask_from_image(img: Image.Image, alpha_cutoff: int = 50,
                            invert: bool = False) -> np.ndarray:
    from rembg import remove
    rgba = img.convert("RGBA")
    buf = io.BytesIO()
    rgba.save(buf, format="PNG")
    out_bytes = remove(buf.getvalue())
    out = Image.open(io.BytesIO(out_bytes))
    arr = np.array(out)
    alpha = arr[:, :, 3]
    is_subject = alpha > alpha_cutoff
    if invert:
        is_subject = ~is_subject
    return ~is_subject  # True for background


def threshold_mask_from_image(img: Image.Image, threshold: int, invert: bool,
                              blur: float, auto_threshold: bool) -> tuple[np.ndarray, int]:
    gray = img.convert("L")
    if blur and blur > 0:
        from PIL import ImageFilter
        gray = gray.filter(ImageFilter.GaussianBlur(radius=blur))
    arr = np.array(gray)
    if auto_threshold:
        threshold = _otsu_threshold(arr)
    mask = arr >= threshold if not invert else arr < threshold
    return mask, int(threshold)


def _crop_tuple(params: dict) -> tuple[int, int, int, int] | None:
    crop = params.get("crop")
    if not crop:
        return None
    try:
        x0 = int(crop["x0"]); y0 = int(crop["y0"])
        x1 = int(crop["x1"]); y1 = int(crop["y1"])
    except (KeyError, TypeError, ValueError):
        return None
    if x1 <= x0 or y1 <= y0:
        return None
    return (x0, y0, x1, y1)


def _layer_mask_key(image_token: str, mode: str, params: dict) -> str:
    crop = _crop_tuple(params)
    crop_str = f"c={crop}" if crop else "c=none"
    canon = (
        f"{image_token}|{mode}|"
        f"t={int(params.get('threshold', 128))}|"
        f"b={float(params.get('blur', 0)):.3f}|"
        f"i={bool(params.get('invert', False))}|"
        f"a={int(params.get('alpha_cutoff', 50))}|"
        f"auto={bool(params.get('auto_threshold', False))}|"
        f"{crop_str}"
    )
    return canon


def compute_layer_mask(image_token: str, mode: str, params: dict) -> np.ndarray:
    """Return mask in our convention: True=background, False=subject."""
    if image_token not in _image_cache:
        raise KeyError(f"unknown image_token: {image_token}")
    key = _layer_mask_key(image_token, mode, params)
    if key in _layer_mask_cache:
        _layer_mask_cache.move_to_end(key)
        return _layer_mask_cache[key]
    img = _image_cache[image_token]
    crop = _crop_tuple(params)
    if crop:
        # Clamp the crop to the image bounds and crop the source.
        x0, y0, x1, y1 = crop
        x0 = max(0, min(img.width, x0))
        y0 = max(0, min(img.height, y0))
        x1 = max(x0 + 1, min(img.width, x1))
        y1 = max(y0 + 1, min(img.height, y1))
        img = img.crop((x0, y0, x1, y1))
    if mode == "subject":
        mask = subject_mask_from_image(
            img,
            alpha_cutoff=int(params.get("alpha_cutoff", 50)),
            invert=bool(params.get("invert", False)),
        )
    elif mode in ("auto", "manual"):
        mask, _ = threshold_mask_from_image(
            img,
            threshold=int(params.get("threshold", 128)),
            invert=bool(params.get("invert", False)),
            blur=float(params.get("blur", 0)),
            auto_threshold=(mode == "auto"),
        )
    else:
        raise ValueError(f"unknown mask mode: {mode}")
    _cache_layer_mask(key, mask)
    return mask


def compose_panel(panel_w_in: float, panel_h_in: float, layers: list,
                  intent: str = "cutouts",
                  px_per_inch: float = 40.0) -> tuple[np.ndarray, float]:
    """Rasterize each visible layer onto a panel-sized binary canvas.

    Panel convention: True = kept steel (panel/background), False = cut.
    Starting state depends on global intent:
      - "cutouts":   panel starts all-steel; layers default to SUBTRACT.
      - "silhouette": panel starts all-cut; layers default to ADD.

    Each layer can override its default polarity via mask_params.polarity in
    {"add", "subtract"}, which is how Marshall composes things like
    "wolf-as-steel with text holes punched inside" (wolf ADD, text SUBTRACT)
    or "panel with moon hole and eagle steel inside the moon" (moon SUBTRACT,
    eagle ADD). Later layers override earlier ones on the pixels they touch.

    Returns (mask, in_per_px).
    """
    panel_w_px = int(round(panel_w_in * px_per_inch))
    panel_h_px = int(round(panel_h_in * px_per_inch))
    longest = max(panel_w_px, panel_h_px)
    if longest > MAX_PANEL_PX:
        scale = MAX_PANEL_PX / longest
        panel_w_px = int(round(panel_w_px * scale))
        panel_h_px = int(round(panel_h_px * scale))
        px_per_inch = px_per_inch * scale
    in_per_px = 1.0 / px_per_inch

    # Panel always starts as all-steel (True). Per-layer polarity does the work:
    # SUBTRACT cuts the layer's subject out, ADD asserts steel (useful for
    # restoring steel inside an already-cut region — e.g. an eagle inside a
    # moon hole). Global intent is kept for the analyzer only.
    panel = np.ones((panel_h_px, panel_w_px), dtype=bool)
    default_polarity = "subtract"
    skipped: list = []

    for layer in layers:
        if not layer.get("visible", True):
            continue
        token = layer.get("image_token")
        mode = layer.get("mask_mode", "subject")
        params = layer.get("mask_params", {}) or {}
        polarity = layer.get("polarity") or params.get("polarity") or default_polarity
        if polarity not in ("add", "subtract"):
            polarity = default_polarity
        try:
            mask = compute_layer_mask(token, mode, params)
        except (KeyError, ValueError) as e:
            # Silently skipping renders an empty panel and explains nothing.
            # The in-memory image cache dies on every restart, so this is the
            # normal failure, not an exotic one.
            skipped.append({"image_token": token, "reason": str(e)})
            continue
        # mask True=background; subject pixels are False.
        subject = (~mask).astype(np.uint8) * 255  # 0 or 255
        layer_img = Image.fromarray(subject, mode="L")
        layer_w_in = float(layer.get("scale_in", min(panel_w_in, panel_h_in) * 0.5))
        if layer_w_in <= 0:
            continue
        aspect = layer_img.height / max(layer_img.width, 1)
        layer_w_px = max(int(round(layer_w_in * px_per_inch)), 1)
        layer_h_px = max(int(round(layer_w_px * aspect)), 1)
        if layer_w_px < 1 or layer_h_px < 1:
            continue
        layer_img_r = layer_img.resize((layer_w_px, layer_h_px), Image.NEAREST)
        cx_in = float(layer.get("x_in", panel_w_in / 2))
        cy_in = float(layer.get("y_in", panel_h_in / 2))
        cx_px = int(round(cx_in * px_per_inch))
        cy_px = int(round(cy_in * px_per_inch))
        x0 = cx_px - layer_w_px // 2
        y0 = cy_px - layer_h_px // 2
        x1 = x0 + layer_w_px
        y1 = y0 + layer_h_px
        sx0, sy0 = max(0, -x0), max(0, -y0)
        dx0, dy0 = max(0, x0), max(0, y0)
        dx1, dy1 = min(panel_w_px, x1), min(panel_h_px, y1)
        if dx0 >= dx1 or dy0 >= dy1:
            continue
        sub = np.array(layer_img_r)[sy0:sy0 + (dy1 - dy0), sx0:sx0 + (dx1 - dx0)]
        is_subject = sub > 127
        # ADD sets subject -> True (steel); SUBTRACT sets subject -> False (cut).
        if polarity == "add":
            panel[dy0:dy1, dx0:dx1] |= is_subject
        else:  # subtract
            panel[dy0:dy1, dx0:dx1] &= ~is_subject

    return panel, in_per_px, skipped


def trace_to_paths(mask: np.ndarray, turdsize: int, alphamax: float, opttolerance: float):
    """Return list of paths. Each path is a list of subpaths (curves).
    Each subpath has a 'start' [x, y] and 'segments' list with type 'C' (corner)
    or 'B' (bezier) plus their control/end points.
    """
    bmp = Bitmap(mask)
    path = bmp.trace(
        turdsize=turdsize,
        turnpolicy=POTRACE_TURNPOLICY_MINORITY,
        alphamax=alphamax,
        opticurve=True,
        opttolerance=opttolerance,
    )
    out = []
    for curve in path:
        sp = curve.start_point
        sub = {"start": [float(sp.x), float(sp.y)], "segments": []}
        for seg in curve.segments:
            ep = seg.end_point
            if seg.is_corner:
                c = seg.c
                sub["segments"].append({
                    "type": "C",
                    "c": [float(c.x), float(c.y)],
                    "end": [float(ep.x), float(ep.y)],
                })
            else:
                c1, c2 = seg.c1, seg.c2
                sub["segments"].append({
                    "type": "B",
                    "c1": [float(c1.x), float(c1.y)],
                    "c2": [float(c2.x), float(c2.y)],
                    "end": [float(ep.x), float(ep.y)],
                })
        out.append(sub)
    return out


def paths_to_svg_d(paths) -> list[str]:
    """Convert internal path data into SVG 'd' attribute strings (one per closed subpath)."""
    out = []
    for sub in paths:
        sx, sy = sub["start"]
        d = [f"M {sx:.3f} {sy:.3f}"]
        for seg in sub["segments"]:
            ex, ey = seg["end"]
            if seg["type"] == "C":
                cx, cy = seg["c"]
                d.append(f"L {cx:.3f} {cy:.3f} L {ex:.3f} {ey:.3f}")
            else:
                c1x, c1y = seg["c1"]
                c2x, c2y = seg["c2"]
                d.append(f"C {c1x:.3f} {c1y:.3f} {c2x:.3f} {c2y:.3f} {ex:.3f} {ey:.3f}")
        d.append("Z")
        out.append(" ".join(d))
    return out


def flatten_paths(paths, bezier_steps: int = 24):
    """Convert paths to lists of (x, y) polylines for DXF export."""
    polylines = []
    for sub in paths:
        pts = []
        x, y = sub["start"]
        pts.append((x, y))
        for seg in sub["segments"]:
            if seg["type"] == "C":
                cx, cy = seg["c"]
                ex, ey = seg["end"]
                pts.append((cx, cy))
                pts.append((ex, ey))
                x, y = ex, ey
            else:
                c1x, c1y = seg["c1"]
                c2x, c2y = seg["c2"]
                ex, ey = seg["end"]
                px, py = x, y
                for i in range(1, bezier_steps + 1):
                    t = i / bezier_steps
                    bx = (1 - t) ** 3 * px + 3 * (1 - t) ** 2 * t * c1x + 3 * (1 - t) * t ** 2 * c2x + t ** 3 * ex
                    by = (1 - t) ** 3 * py + 3 * (1 - t) ** 2 * t * c1y + 3 * (1 - t) * t ** 2 * c2y + t ** 3 * ey
                    pts.append((bx, by))
                x, y = ex, ey
        polylines.append(pts)
    return polylines


def fit_transform(paths, target_w: float, target_h: float, units_in_inches: bool):
    """Compute scale and offset so the path bbox fits target dimensions, preserving aspect.
    Returns (scale, dx, dy, fitted_w, fitted_h)."""
    xs, ys = [], []
    for sub in paths:
        xs.append(sub["start"][0]); ys.append(sub["start"][1])
        for seg in sub["segments"]:
            if seg["type"] == "C":
                xs.append(seg["c"][0]); ys.append(seg["c"][1])
            else:
                xs.append(seg["c1"][0]); ys.append(seg["c1"][1])
                xs.append(seg["c2"][0]); ys.append(seg["c2"][1])
            xs.append(seg["end"][0]); ys.append(seg["end"][1])
    if not xs:
        return 1.0, 0.0, 0.0, 0.0, 0.0
    minx, maxx = min(xs), max(xs)
    miny, maxy = min(ys), max(ys)
    src_w = maxx - minx
    src_h = maxy - miny
    if src_w == 0 or src_h == 0:
        return 1.0, -minx, -miny, src_w, src_h
    scale = min(target_w / src_w, target_h / src_h)
    fitted_w = src_w * scale
    fitted_h = src_h * scale
    dx = -minx * scale + (target_w - fitted_w) / 2
    dy = -miny * scale + (target_h - fitted_h) / 2
    return scale, dx, dy, fitted_w, fitted_h


def transform_polylines(polylines, scale, dx, dy, flip_y_height=None):
    out = []
    for pts in polylines:
        new = []
        for x, y in pts:
            nx = x * scale + dx
            ny = y * scale + dy
            if flip_y_height is not None:
                ny = flip_y_height - ny
            new.append((nx, ny))
        out.append(new)
    return out


@app.get("/")
def root():
    return send_from_directory(str(STATIC_DIR), "index.html")


# --- Gemini image generation ---

GEMINI_FLASH_MODEL = "gemini-3.1-flash-image-preview"  # "Nano Banana 2"
PLASMA_STYLE_SUFFIX = (
    " High-contrast black silhouette on a pure white background. "
    "Bold simple shapes, clean outlines, no shading or gradients, no text. "
    "Designed to be cut from steel on a plasma table."
)

_gemini_client = None


def get_gemini_client():
    global _gemini_client
    if _gemini_client is None:
        api_key = os.environ.get("GEMINI_API_KEY")
        if not api_key:
            raise RuntimeError(
                "GEMINI_API_KEY is not set. On HF Spaces, add it under "
                "Settings → Variables and secrets. Locally, set it in your shell."
            )
        from google import genai
        _gemini_client = genai.Client(api_key=api_key)
    return _gemini_client


def _gemini_generate_image(prompt: str, size: str = "1K") -> Image.Image:
    from google.genai import types
    client = get_gemini_client()
    resp = client.models.generate_content(
        model=GEMINI_FLASH_MODEL,
        contents=[prompt],
        config=types.GenerateContentConfig(
            image_config=types.ImageConfig(image_size=size),
        ),
    )
    # Find the first image part in the response
    for cand in (resp.candidates or []):
        for part in (cand.content.parts or []):
            inline = getattr(part, "inline_data", None)
            if inline and inline.data:
                return Image.open(io.BytesIO(inline.data)).convert("RGBA")
    raise RuntimeError("Gemini returned no image data")


@app.post("/generate")
def generate():
    data = request.get_json(force=True) or {}
    prompt = (data.get("prompt") or "").strip()
    if not prompt:
        return jsonify({"error": "prompt required"}), 400
    plasma_style = bool(data.get("plasma_style", True))
    size = data.get("size", "1K")
    if size not in ("1K", "2K", "4K"):
        size = "1K"
    full_prompt = prompt + (PLASMA_STYLE_SUFFIX if plasma_style else "")
    try:
        img = _gemini_generate_image(full_prompt, size=size)
    except RuntimeError as e:
        return jsonify({"error": str(e)}), 503
    except Exception as e:
        return jsonify({"error": f"generation failed: {e}"}), 502
    # Downscale to fit our pipeline expectations
    if max(img.size) > MAX_IMAGE_DIM:
        scale = MAX_IMAGE_DIM / max(img.size)
        img = img.resize((int(img.width * scale), int(img.height * scale)), Image.LANCZOS)
    token = _cache_image(img)
    thumb = img.copy()
    thumb.thumbnail((160, 160), Image.LANCZOS)
    buf = io.BytesIO()
    thumb.convert("RGB").save(buf, format="JPEG", quality=80)
    thumb_b64 = base64.b64encode(buf.getvalue()).decode("ascii")
    # Echo the source PNG as a base64 data URL so the frontend can use it for
    # crop modal display (same as if the user had uploaded the file directly).
    src_buf = io.BytesIO()
    img.save(src_buf, format="PNG")
    src_b64 = base64.b64encode(src_buf.getvalue()).decode("ascii")
    return jsonify({
        "image_token": token,
        "width": img.width,
        "height": img.height,
        "thumbnail": f"data:image/jpeg;base64,{thumb_b64}",
        "source_data_url": f"data:image/png;base64,{src_b64}",
        "name": prompt[:40] + ("…" if len(prompt) > 40 else ""),
        "used_prompt": full_prompt,
    })


@app.post("/upload")
def upload():
    if "image" not in request.files:
        return jsonify({"error": "no image uploaded"}), 400
    f = request.files["image"]
    img = _open_resized(f, mode="RGBA")
    token = _cache_image(img)
    # Encode a thumbnail dataURL for the layer panel.
    thumb = img.copy()
    thumb.thumbnail((160, 160), Image.LANCZOS)
    buf = io.BytesIO()
    thumb.convert("RGB").save(buf, format="JPEG", quality=80)
    thumb_b64 = base64.b64encode(buf.getvalue()).decode("ascii")
    return jsonify({
        "image_token": token,
        "width": img.width,
        "height": img.height,
        "thumbnail": f"data:image/jpeg;base64,{thumb_b64}",
        "name": getattr(f, "filename", "image") or "image",
        "is_line_art": bool(is_line_art(img)),
    })


@app.post("/layer/preview")
def layer_preview():
    """Return the layer's binary mask as a transparent PNG, sized to the source
    image. Used for rendering a clean cutout preview on the canvas while the
    user adjusts position/scale."""
    data = request.get_json(force=True)
    token = data.get("image_token")
    mode = data.get("mask_mode", "subject")
    params = data.get("mask_params", {}) or {}
    if not token or token not in _image_cache:
        return jsonify({"error": "unknown image_token"}), 400
    try:
        mask = compute_layer_mask(token, mode, params)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    # mask: True = background (transparent), False = subject (cream)
    h, w = mask.shape
    rgba = np.zeros((h, w, 4), dtype=np.uint8)
    subject = ~mask
    rgba[subject] = [247, 243, 234, 255]  # cream
    rgba[~subject] = [0, 0, 0, 0]
    img = Image.fromarray(rgba, mode="RGBA")
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    b64 = base64.b64encode(buf.getvalue()).decode("ascii")
    # Subject bbox in source-image pixels — frontend converts to inches
    # using the layer's panel width and aspect ratio.
    bbox = None
    ys, xs = np.where(subject)
    if xs.size:
        bbox = {
            "x0": int(xs.min()),
            "y0": int(ys.min()),
            "x1": int(xs.max()),
            "y1": int(ys.max()),
        }
    return jsonify({
        "mask_png": f"data:image/png;base64,{b64}",
        "width": int(w),
        "height": int(h),
        "subject_bbox": bbox,
        "subject_pixels": int(subject.sum()),
    })


@app.post("/compose")
def compose():
    """Compose all visible layers into a single panel mask, trace it, and cache
    the result for /analyze and /export."""
    data = request.get_json(force=True)
    try:
        panel_w_in = float(data["panel_w_in"])
        panel_h_in = float(data["panel_h_in"])
    except (KeyError, ValueError, TypeError):
        return jsonify({"error": "panel_w_in and panel_h_in required"}), 400
    if panel_w_in <= 0 or panel_h_in <= 0:
        return jsonify({"error": "panel dimensions must be > 0"}), 400
    layers = data.get("layers") or []
    if not isinstance(layers, list) or not layers:
        return jsonify({"error": "layers array required"}), 400

    turdsize = int(data.get("turdsize", 8))
    alphamax = float(data.get("alphamax", 1.0))
    opttolerance = float(data.get("opttolerance", 0.4))
    intent = data.get("intent", "cutouts")
    if intent not in ("cutouts", "silhouette"):
        intent = "cutouts"

    panel_mask, in_per_px, skipped_layers = compose_panel(
        panel_w_in, panel_h_in, layers, intent=intent)
    if (~panel_mask).sum() == 0:
        return jsonify({
            "paths": [], "svg_d": [], "width": int(panel_mask.shape[1]),
            "height": int(panel_mask.shape[0]), "token": None,
            "in_per_px": in_per_px, "panel_w_in": panel_w_in,
            "panel_h_in": panel_h_in, "empty": True,
            "skipped_layers": skipped_layers,
        })

    paths = trace_to_paths(panel_mask, turdsize=turdsize, alphamax=alphamax,
                            opttolerance=opttolerance)
    h, w = panel_mask.shape
    token = _cache_mask(panel_mask)
    return jsonify({
        "width": int(w),
        "height": int(h),
        "paths": paths,
        "svg_d": paths_to_svg_d(paths),
        "token": token,
        "in_per_px": in_per_px,
        "panel_w_in": panel_w_in,
        "panel_h_in": panel_h_in,
        "empty": False,
        "skipped_layers": skipped_layers,
    })


@app.post("/trace")
def trace():
    if "image" not in request.files:
        return jsonify({"error": "no image uploaded"}), 400
    f = request.files["image"]
    threshold = int(request.form.get("threshold", 128))
    invert = request.form.get("invert", "false").lower() == "true"
    blur = float(request.form.get("blur", 0))
    turdsize = int(request.form.get("turdsize", 8))
    alphamax = float(request.form.get("alphamax", 1.0))
    opttolerance = float(request.form.get("opttolerance", 0.4))
    extract_subject = request.form.get("extract_subject", "false").lower() == "true"
    auto_threshold = request.form.get("auto_threshold", "false").lower() == "true"

    used_threshold = threshold
    if extract_subject:
        try:
            mask = subject_mask(f, invert=invert)
        except Exception as e:
            return jsonify({"error": f"subject extraction failed: {e}"}), 500
    else:
        mask, used_threshold = load_and_prepare(
            f, threshold=threshold, invert=invert, blur=blur,
            auto_threshold=auto_threshold,
        )
    paths = trace_to_paths(mask, turdsize=turdsize, alphamax=alphamax, opttolerance=opttolerance)
    h, w = mask.shape
    token = _cache_mask(mask)
    return jsonify({
        "width": int(w),
        "height": int(h),
        "paths": paths,
        "svg_d": paths_to_svg_d(paths),
        "token": token,
        "used_threshold": int(used_threshold),
        "mode": "subject" if extract_subject else ("auto" if auto_threshold else "manual"),
    })


def is_line_art(img: Image.Image, extreme_frac: float = 0.88) -> bool:
    """True when an image is already black-and-white artwork rather than a photo.

    This matters more than it looks.  The default mask mode is rembg subject
    extraction, which is a photo segmentation net: fed a line drawing it fills
    the fine white gaps between the lines and hands back a few large blobs.
    Measured on a real 120x28 panel drawing, subject extraction composed to 28
    contours where a plain threshold gave 322.  The drawing is destroyed before
    anything downstream gets a look at it.

    Test: a line drawing puts nearly all of its pixels at the two ends of the
    histogram.  A photograph does not.
    """
    g = img.convert("L")
    if max(g.size) > 900:                      # sampling is plenty for this
        g = g.copy()
        g.thumbnail((900, 900), Image.NEAREST)
    h = g.histogram()
    total = sum(h) or 1
    dark = sum(h[:31])
    light = sum(h[225:])
    return (dark + light) / total >= extreme_frac


def _bbox_of_mask_component(component_mask: np.ndarray) -> list[int]:
    ys, xs = np.where(component_mask)
    return [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())]


@app.post("/analyze")
def analyze():
    data = request.get_json(force=True)
    token = data.get("token")
    if not token or token not in _mask_cache:
        return jsonify({"error": "missing or expired token; re-trace first"}), 400
    mask = _mask_cache[token]

    try:
        width_in = float(data["width_in"])
        height_in = float(data["height_in"])
    except (KeyError, TypeError, ValueError):
        return jsonify({"error": "width_in and height_in required"}), 400
    if width_in <= 0 or height_in <= 0:
        return jsonify({"error": "panel dimensions must be > 0"}), 400

    intent = data.get("intent", "cutouts")
    if intent not in ("cutouts", "silhouette"):
        intent = "cutouts"
    kerf_in = float(data.get("kerf_in", 0.06))
    min_feature_in = float(data.get("min_feature_in", max(kerf_in * 1.5, 0.1)))
    # Largest ball allowed through any opening. 0 disables the check.
    max_gap_in = float(data.get("max_gap_in", 0.0))
    gap_min_in2 = float(data.get("gap_min_in2", 0.05))
    # Below these real-world thresholds, regions are considered noise (not real
    # cuttability problems). Tunable via request.
    island_min_in2 = float(data.get("island_min_in2", 0.25))
    thin_cluster_min_in2 = float(data.get("thin_cluster_min_in2", 0.005))

    h, w = mask.shape
    # mask = True for light pixels (background); design = dark shapes = ~mask.
    # Apply binary opening to suppress single-pixel antialiasing jaggies that
    # would otherwise dominate the thin-feature count on photo-traced images.
    from scipy.ndimage import binary_opening
    design_raw = ~mask
    design = binary_opening(design_raw, iterations=1)

    xs, ys = np.where(design)
    if xs.size == 0:
        return jsonify({"warnings": [], "islands": [], "overlay_png_b64": None,
                        "summary": {"design_pixels": 0}})

    # Real-world scale: prefer caller-provided in_per_px (composed panel) over
    # bbox-fit derivation (single-image trace).
    explicit_in_per_px = data.get("in_per_px")
    if explicit_in_per_px is not None and float(explicit_in_per_px) > 0:
        in_per_px = float(explicit_in_per_px)
    else:
        bb_x0, bb_x1 = int(xs.min()), int(xs.max())
        bb_y0, bb_y1 = int(ys.min()), int(ys.max())
        bbox_w_px = max(bb_x1 - bb_x0, 1)
        bbox_h_px = max(bb_y1 - bb_y0, 1)
        in_per_px = min(width_in / bbox_w_px, height_in / bbox_h_px)

    # --- Minimum feature width: distance transform of the design ---
    # distance_transform_edt: distance from each True pixel to nearest False pixel.
    # Local feature width at a pixel = 2 * distance.
    distance_px = distance_transform_edt(design)
    feature_width_in = 2.0 * distance_px * in_per_px
    too_thin = design & (feature_width_in < min_feature_in) & (feature_width_in > 0)
    too_thin_count = int(too_thin.sum())

    warnings = []
    if too_thin_count > 0:
        # cluster too-thin pixels into connected components for reporting
        thin_labeled, thin_n = label(too_thin)
        thin_components = []
        cluster_min_px = max(int(thin_cluster_min_in2 / max(in_per_px ** 2, 1e-9)), 3)
        for i in range(1, thin_n + 1):
            comp = thin_labeled == i
            csize = int(comp.sum())
            if csize < cluster_min_px:
                continue
            min_w = float((feature_width_in[comp]).min())
            thin_components.append({
                "size_px": csize,
                "area_in2": round(csize * (in_per_px ** 2), 4),
                "min_width_in": round(min_w, 4),
                "bbox": _bbox_of_mask_component(comp),
            })
        thin_components.sort(key=lambda c: c["min_width_in"])
        if thin_components:
            narrowest = thin_components[0]["min_width_in"]
            warnings.append({
                "kind": "thin_feature",
                "severity": "high" if narrowest < min_feature_in * 0.6 else "medium",
                "count": len(thin_components),
                "narrowest_in": round(narrowest, 4),
                "min_required_in": round(min_feature_in, 4),
                "message": (
                    f"{len(thin_components)} thin region(s); narrowest is "
                    f"{narrowest:.3f}\" (minimum {min_feature_in:.3f}\")"
                ),
                "regions": thin_components[:20],
            })

    # --- Floating islands (silhouette mode only) ---
    islands_payload = []
    if intent == "silhouette":
        labeled, n = label(design)
        if n > 1:
            # treat the largest component as the "main" piece
            sizes = np.bincount(labeled.ravel())
            sizes[0] = 0  # background
            main_id = int(sizes.argmax())
            island_min_px = max(int(island_min_in2 / max(in_per_px ** 2, 1e-9)), 1)
            for comp_id in range(1, n + 1):
                if comp_id == main_id:
                    continue
                comp = labeled == comp_id
                csize = int(comp.sum())
                if csize < island_min_px:
                    continue
                area_in2 = csize * (in_per_px ** 2)
                islands_payload.append({
                    "size_px": csize,
                    "area_in2": round(area_in2, 3),
                    "bbox": _bbox_of_mask_component(comp),
                })
            islands_payload.sort(key=lambda i: -i["area_in2"])
            if islands_payload:
                warnings.append({
                    "kind": "floating_island",
                    "severity": "high",
                    "count": len(islands_payload),
                    "message": (
                        f"{len(islands_payload)} steel piece(s) not connected to the "
                        f"main piece; will fall out unless bridged"
                    ),
                })

    # --- Gap test: will a ball of max_gap_in pass through any opening? ---
    # The guard/pool rule Marsh's client is working to.  A sphere is stopped by
    # the NARROWEST clearance, so the test is the largest circle that fits
    # inside an opening: distance transform of the CUT area, doubled.
    #
    # Only openings enclosed by steel are measured.  On a composed panel every
    # cut is enclosed by the border, which is what we want.  On a bare traced
    # image the surrounding background touches the image edge and is not a cut,
    # so excluding edge-touching regions keeps it from being reported.
    gaps_payload = []
    gap_mask = np.zeros_like(design, dtype=bool)
    if max_gap_in > 0:
        cut = ~design
        cut_lab, cut_n = label(cut)
        if cut_n:
            edge_ids = set(cut_lab[0, :]) | set(cut_lab[-1, :]) \
                | set(cut_lab[:, 0]) | set(cut_lab[:, -1])
            edge_ids.discard(0)
            enclosed = cut & ~np.isin(cut_lab, list(edge_ids))
            if enclosed.any():
                gap_dist_in = 2.0 * distance_transform_edt(cut) * in_per_px
                over = enclosed & (gap_dist_in >= max_gap_in)
                min_px = max(int(gap_min_in2 / max(in_per_px ** 2, 1e-9)), 1)
                if over.any():
                    over_lab, over_n = label(over)
                    for i in range(1, over_n + 1):
                        comp = over_lab == i
                        if int(comp.sum()) < min_px:
                            continue
                        widest = float(gap_dist_in[comp].max())
                        yy, xx = np.where(comp)
                        gaps_payload.append({
                            "bbox": _bbox_of_mask_component(comp),
                            "center_px": [int(xx.mean()), int(yy.mean())],
                            "widest_in": round(widest, 3),
                            "area_in2": round(float(comp.sum()) * in_per_px ** 2, 3),
                        })
                        gap_mask |= comp
                    gaps_payload.sort(key=lambda g: -g["widest_in"])
        if gaps_payload:
            worst = gaps_payload[0]["widest_in"]
            warnings.append({
                "kind": "gap_too_large",
                "severity": "high",
                "count": len(gaps_payload),
                "worst_in": worst,
                "max_allowed_in": round(max_gap_in, 3),
                "message": (
                    f"{len(gaps_payload)} opening(s) pass a {max_gap_in:.2f}\" ball; "
                    f"the widest fits {worst:.2f}\""
                ),
                "regions": gaps_payload[:20],
            })

    # --- Build a warning overlay PNG for the canvas ---
    overlay = np.zeros((h, w, 4), dtype=np.uint8)
    if too_thin_count > 0:
        overlay[too_thin] = [255, 60, 60, 220]
    if gap_mask.any():
        # openings that pass the ball, in blue
        overlay[gap_mask] = [40, 130, 255, 190]
    if islands_payload:
        # mark islands in orange
        labeled, _ = label(design)
        sizes = np.bincount(labeled.ravel())
        sizes[0] = 0
        main_id = int(sizes.argmax())
        for island in islands_payload:
            x0, y0, x1, y1 = island["bbox"]
            sub_labels = labeled[y0:y1 + 1, x0:x1 + 1]
            island_pixels = (sub_labels != main_id) & (sub_labels != 0)
            yy, xx = np.where(island_pixels)
            overlay[yy + y0, xx + x0] = [255, 145, 0, 200]

    overlay_b64 = None
    if too_thin_count > 0 or islands_payload or gap_mask.any():
        img = Image.fromarray(overlay, mode="RGBA")
        buf = io.BytesIO()
        img.save(buf, format="PNG")
        overlay_b64 = base64.b64encode(buf.getvalue()).decode("ascii")

    summary = {
        "design_pixels": int(design.sum()),
        "in_per_px": round(in_per_px, 5),
        "min_feature_in": min_feature_in,
        "kerf_in": kerf_in,
        "intent": intent,
        "max_gap_in": max_gap_in,
        "px_per_inch": round(1.0 / in_per_px, 2) if in_per_px else None,
        "gap_count": len(gaps_payload),
        "worst_gap_in": (gaps_payload[0]["widest_in"] if gaps_payload else None),
    }

    return jsonify({
        "warnings": warnings,
        "islands": islands_payload,
        "gaps": gaps_payload,
        "overlay_png_b64": overlay_b64,
        "summary": summary,
    })


def simplify_polyline(pts, tol):
    """Douglas-Peucker. Drops collinear-enough vertices without moving the
    outline more than `tol`."""
    n = len(pts)
    if n < 3 or tol <= 0:
        return pts
    keep = [False] * n
    keep[0] = keep[-1] = True
    stack = [(0, n - 1)]
    while stack:
        i, j = stack.pop()
        if j <= i + 1:
            continue
        x1, y1 = pts[i]
        x2, y2 = pts[j]
        ddx, ddy = x2 - x1, y2 - y1
        seg = (ddx * ddx + ddy * ddy) ** 0.5
        best, bi = -1.0, -1
        for k in range(i + 1, j):
            x0, y0 = pts[k]
            if seg > 0:
                d = abs(ddy * x0 - ddx * y0 + x2 * y1 - y2 * x1) / seg
            else:
                d = ((x0 - x1) ** 2 + (y0 - y1) ** 2) ** 0.5
            if d > best:
                best, bi = d, k
        if best > tol and bi > 0:
            keep[bi] = True
            stack.append((i, bi))
            stack.append((bi, j))
    return [q for q, k in zip(pts, keep) if k]


def _parse_export_payload():
    data = request.get_json(force=True)
    paths = data.get("paths") or []
    width_in = float(data.get("width_in", 0))
    height_in = float(data.get("height_in", 0))
    units = data.get("units", "inches")
    in_per_px = data.get("in_per_px")
    in_per_px = float(in_per_px) if in_per_px else None
    if width_in <= 0 or height_in <= 0:
        raise ValueError("width_in and height_in must be > 0")
    return paths, width_in, height_in, units, in_per_px


def _export_transform(paths, w_in, h_in, in_per_px):
    """Return (scale, dx, dy). When in_per_px is given (composed panel), the
    paths are already in panel pixel coords; just scale by in_per_px. Otherwise
    fall back to bbox-fit-into-panel."""
    if in_per_px and in_per_px > 0:
        return in_per_px, 0.0, 0.0, w_in, h_in
    scale, dx, dy, fw, fh = fit_transform(paths, w_in, h_in, True)
    return scale, dx, dy, fw, fh


@app.post("/export/svg")
def export_svg():
    try:
        paths, w_in, h_in, units, in_per_px = _parse_export_payload()
    except ValueError as e:
        return jsonify({"error": str(e)}), 400

    scale, dx, dy, fw, fh = _export_transform(paths, w_in, h_in, in_per_px)

    parts = [
        f'<?xml version="1.0" encoding="UTF-8"?>',
        f'<svg xmlns="http://www.w3.org/2000/svg" '
        f'width="{w_in}in" height="{h_in}in" '
        f'viewBox="0 0 {w_in} {h_in}">',
        f'<g fill="black" stroke="none" fill-rule="evenodd">',
    ]
    for sub in paths:
        sx = sub["start"][0] * scale + dx
        sy = sub["start"][1] * scale + dy
        d = [f"M {sx:.4f} {sy:.4f}"]
        for seg in sub["segments"]:
            ex = seg["end"][0] * scale + dx
            ey = seg["end"][1] * scale + dy
            if seg["type"] == "C":
                cx = seg["c"][0] * scale + dx
                cy = seg["c"][1] * scale + dy
                d.append(f"L {cx:.4f} {cy:.4f} L {ex:.4f} {ey:.4f}")
            else:
                c1x = seg["c1"][0] * scale + dx
                c1y = seg["c1"][1] * scale + dy
                c2x = seg["c2"][0] * scale + dx
                c2y = seg["c2"][1] * scale + dy
                d.append(f"C {c1x:.4f} {c1y:.4f} {c2x:.4f} {c2y:.4f} {ex:.4f} {ey:.4f}")
        d.append("Z")
        parts.append(f'<path d="{" ".join(d)}"/>')
    parts.append("</g></svg>")
    svg = "\n".join(parts).encode("utf-8")
    return send_file(
        io.BytesIO(svg),
        mimetype="image/svg+xml",
        as_attachment=True,
        download_name="plasma-design.svg",
    )


@app.post("/export/dxf")
def export_dxf():
    try:
        paths, w_in, h_in, units, in_per_px = _parse_export_payload()
    except ValueError as e:
        return jsonify({"error": str(e)}), 400

    scale, dx, dy, fw, fh = _export_transform(paths, w_in, h_in, in_per_px)
    polylines = flatten_paths(paths, bezier_steps=32)
    # DXF uses Y-up; bitmap traces are Y-down. Flip so the design isn't mirrored.
    polylines = transform_polylines(polylines, scale, dx, dy, flip_y_height=h_in)

    doc = ezdxf.new(dxfversion="R2010", units=ezdxf.units.IN if units == "inches" else ezdxf.units.MM)
    doc.header["$INSUNITS"] = 1 if units == "inches" else 4
    msp = doc.modelspace()
    doc.layers.add(name="CUT", color=1)

    # Flattening beziers at 32 steps is far finer than a torch can follow, and
    # at 40 px/inch on a 120" panel it produced a 34MB DXF that CAM software
    # will not thank anyone for. 0.01" is well inside a plasma kerf, so this is
    # invisible on the part.
    simplify_in = float(request.get_json(force=True).get("simplify_in", 0.01))
    kept = dropped = 0
    for pts in polylines:
        if len(pts) < 2:
            continue
        before = len(pts)
        if simplify_in > 0:
            pts = simplify_polyline(pts, simplify_in)
        kept += len(pts)
        dropped += before - len(pts)
        if len(pts) < 2:
            continue
        msp.add_lwpolyline(pts, close=True, dxfattribs={"layer": "CUT"})
    app.logger.info("dxf export: %d vertices kept, %d dropped (simplify %.3fin)",
                    kept, dropped, simplify_in)

    buf = io.StringIO()
    doc.write(buf)
    data = buf.getvalue().encode("utf-8")
    return send_file(
        io.BytesIO(data),
        mimetype="application/dxf",
        as_attachment=True,
        download_name="plasma-design.dxf",
    )


if __name__ == "__main__":
    import os
    port = int(os.environ.get("PORT", 5174))
    host = os.environ.get("HOST", "127.0.0.1")
    app.run(host=host, port=port, debug=False)