mmdflux 2.1.0

Render Mermaid diagrams as Unicode text, ASCII, SVG, and MMDS JSON.
Documentation
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
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
use std::collections::{BTreeSet, HashMap};
use std::fs;
use std::path::Path;

use crate::diagrams::flowchart::compile_to_graph;
use crate::engines::graph::EngineConfig;
use crate::engines::graph::algorithms::layered::{MeasurementMode, run_layered_layout};
use crate::engines::graph::contracts::{GraphEngine, GraphGeometryContract, GraphSolveRequest};
use crate::engines::graph::flux::FluxLayeredEngine;
use crate::format::{CornerStyle, Curve, RoutingStyle};
use crate::graph::Stroke;
use crate::graph::measure::default_proportional_text_metrics;
use crate::graph::routing::{EdgeRouting, route_graph_geometry};
use crate::mermaid::parse_flowchart;
use crate::render::graph::{render_svg_from_geometry, render_svg_from_routed_geometry};
use crate::simplification::PathSimplification;
use crate::{OutputFormat, RenderConfig, SvgThemeConfig};

fn render_svg(diagram: &crate::graph::Graph, config: &RenderConfig) -> String {
    let engine = FluxLayeredEngine::text();
    let request = GraphSolveRequest::new(
        MeasurementMode::Proportional(default_proportional_text_metrics()),
        GraphGeometryContract::Visual,
        config.geometry_level,
        config
            .routing_style
            .or_else(|| config.edge_preset.map(|preset| preset.expand().0)),
        Default::default(),
    );
    let result = engine
        .solve(
            diagram,
            &EngineConfig::Layered(config.layout.clone().into()),
            &request,
        )
        .expect("SVG render should succeed");

    let options = config.svg_render_options();
    if let Some(routed) = result.routed.as_ref() {
        render_svg_from_routed_geometry(diagram, routed, &options)
    } else {
        render_svg_from_geometry(diagram, &result.geometry, &options)
    }
}

fn solve_visual_geometry(
    diagram: &crate::graph::Graph,
    config: &RenderConfig,
) -> crate::graph::geometry::GraphGeometry {
    let engine = FluxLayeredEngine::text();
    let request = GraphSolveRequest::new(
        MeasurementMode::Proportional(default_proportional_text_metrics()),
        GraphGeometryContract::Visual,
        config.geometry_level,
        config
            .routing_style
            .or_else(|| config.edge_preset.map(|preset| preset.expand().0)),
        Default::default(),
    );
    engine
        .solve(
            diagram,
            &EngineConfig::Layered(config.layout.clone().into()),
            &request,
        )
        .expect("SVG render should succeed")
        .geometry
}

fn default_proportional_mode() -> MeasurementMode {
    MeasurementMode::Proportional(default_proportional_text_metrics())
}

fn routing_style_for(edge_routing: EdgeRouting) -> RoutingStyle {
    match edge_routing {
        EdgeRouting::DirectRoute => RoutingStyle::Direct,
        EdgeRouting::PolylineRoute => RoutingStyle::Polyline,
        EdgeRouting::EngineProvided | EdgeRouting::OrthogonalRoute => RoutingStyle::Orthogonal,
    }
}

/// Extract SVG node center x-coordinates by label text.
///
/// Scans the SVG for `<text ...>Label</text>` elements and returns a map of label -> x coordinate.
fn extract_node_x_positions(svg: &str) -> HashMap<String, f64> {
    let mut positions = HashMap::new();
    for line in svg.lines().map(str::trim) {
        if !line.contains("dominant-baseline") {
            continue;
        }
        let Some((x, _y, label)) = parse_svg_text_position_and_value(line) else {
            continue;
        };
        if !label.is_empty() {
            positions.insert(label, x);
        }
    }
    positions
}

fn edge_path_data(svg: &str) -> Vec<String> {
    svg.lines()
        .map(str::trim)
        .filter(|line| {
            line.starts_with("<path d=\"")
                && (line.contains("marker-end=") || line.contains("marker-start="))
        })
        .filter_map(|line| {
            let start = line.find("d=\"")?;
            let after = &line[start + 3..];
            let end = after.find('"')?;
            Some(after[..end].to_string())
        })
        .collect()
}

fn parse_svg_path_points(path_data: &str) -> Vec<(f64, f64)> {
    path_data
        .split_whitespace()
        .filter_map(|token| {
            let token = token.trim_start_matches(|c: char| c.is_ascii_alphabetic());
            let (x, y) = token.split_once(',')?;
            let x = x.parse::<f64>().ok()?;
            let y = y.parse::<f64>().ok()?;
            Some((x, y))
        })
        .collect()
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum SvgPathCommand {
    Move((f64, f64)),
    Line((f64, f64)),
    Cubic((f64, f64), (f64, f64), (f64, f64)),
}

type SvgPathSegment = ((f64, f64), (f64, f64), char);

fn parse_svg_path_command_sequence(path_data: &str) -> Vec<SvgPathCommand> {
    fn parse_point(token: &str) -> Option<(f64, f64)> {
        let token = token.trim();
        let (x, y) = token.split_once(',')?;
        Some((x.parse::<f64>().ok()?, y.parse::<f64>().ok()?))
    }

    let mut commands = Vec::new();
    let mut tokens = path_data.split_whitespace().peekable();
    while let Some(token) = tokens.next() {
        let token = token.trim();
        if token.is_empty() {
            continue;
        }
        let mut chars = token.chars();
        let Some(command) = chars.next() else {
            continue;
        };
        if !command.is_ascii_alphabetic() {
            continue;
        }
        let remainder = chars.as_str();
        match command {
            'M' | 'L' => {
                let point_token = if remainder.is_empty() {
                    tokens.next().unwrap_or("")
                } else {
                    remainder
                };
                let Some(point) = parse_point(point_token) else {
                    continue;
                };
                if command == 'M' {
                    commands.push(SvgPathCommand::Move(point));
                } else {
                    commands.push(SvgPathCommand::Line(point));
                }
            }
            'C' => {
                let first_token = if remainder.is_empty() {
                    tokens.next().unwrap_or("")
                } else {
                    remainder
                };
                let second_token = tokens.next().unwrap_or("");
                let third_token = tokens.next().unwrap_or("");
                let (Some(c1), Some(c2), Some(end)) = (
                    parse_point(first_token),
                    parse_point(second_token),
                    parse_point(third_token),
                ) else {
                    continue;
                };
                commands.push(SvgPathCommand::Cubic(c1, c2, end));
            }
            _ => {}
        }
    }
    commands
}

fn cubic_bezier_point(
    p0: (f64, f64),
    p1: (f64, f64),
    p2: (f64, f64),
    p3: (f64, f64),
    t: f64,
) -> (f64, f64) {
    let omt = 1.0 - t;
    let omt2 = omt * omt;
    let omt3 = omt2 * omt;
    let t2 = t * t;
    let t3 = t2 * t;
    (
        omt3 * p0.0 + 3.0 * omt2 * t * p1.0 + 3.0 * omt * t2 * p2.0 + t3 * p3.0,
        omt3 * p0.1 + 3.0 * omt2 * t * p1.1 + 3.0 * omt * t2 * p2.1 + t3 * p3.1,
    )
}

fn sample_svg_path_commands(commands: &[SvgPathCommand], cubic_steps: usize) -> Vec<(f64, f64)> {
    let mut sampled = Vec::new();
    let mut current = (0.0, 0.0);
    let mut has_current = false;

    for command in commands {
        match *command {
            SvgPathCommand::Move(point) => {
                current = point;
                has_current = true;
                sampled.push(point);
            }
            SvgPathCommand::Line(point) => {
                if !has_current {
                    current = point;
                    has_current = true;
                    sampled.push(point);
                    continue;
                }
                sampled.push(point);
                current = point;
            }
            SvgPathCommand::Cubic(c1, c2, end) => {
                if !has_current {
                    current = end;
                    has_current = true;
                    sampled.push(end);
                    continue;
                }
                let steps = cubic_steps.max(1);
                for step in 1..=steps {
                    let t = step as f64 / steps as f64;
                    sampled.push(cubic_bezier_point(current, c1, c2, end, t));
                }
                current = end;
            }
        }
    }

    sampled
}

fn svg_visible_line_run_from_start(path_data: &str) -> f64 {
    let commands = parse_svg_path_command_sequence(path_data);
    if commands.is_empty() {
        return 0.0;
    }

    let mut current = None;
    let mut first_axis = None;
    let mut run = 0.0;
    let mut saw_first_segment = false;

    for command in commands {
        match command {
            SvgPathCommand::Move(point) => current = Some(point),
            SvgPathCommand::Line(point) => {
                let Some(prev) = current else {
                    current = Some(point);
                    continue;
                };
                let axis = segment_axis(prev, point);
                let len = manhattan_segment_len(prev, point);
                if !saw_first_segment {
                    saw_first_segment = true;
                    first_axis = axis;
                    run += len;
                } else if axis == first_axis {
                    run += len;
                } else {
                    break;
                }
                current = Some(point);
            }
            SvgPathCommand::Cubic(_, _, _) => {
                if !saw_first_segment {
                    return 0.0;
                }
                break;
            }
        }
    }
    run
}

fn svg_visible_line_run_from_end(path_data: &str) -> f64 {
    let commands = parse_svg_path_command_sequence(path_data);
    if commands.is_empty() {
        return 0.0;
    }

    let mut segments: Vec<SvgPathSegment> = Vec::new();
    let mut current = None;

    for command in commands {
        match command {
            SvgPathCommand::Move(point) => current = Some(point),
            SvgPathCommand::Line(point) => {
                let Some(prev) = current else {
                    current = Some(point);
                    continue;
                };
                segments.push((prev, point, 'L'));
                current = Some(point);
            }
            SvgPathCommand::Cubic(_, _, end) => {
                let Some(prev) = current else {
                    current = Some(end);
                    continue;
                };
                segments.push((prev, end, 'C'));
                current = Some(end);
            }
        }
    }

    let Some((_, _, kind)) = segments.last().copied() else {
        return 0.0;
    };
    if kind != 'L' {
        return 0.0;
    }

    let mut run = 0.0;
    let mut axis = None;
    for (start, end, kind) in segments.into_iter().rev() {
        if kind != 'L' {
            break;
        }
        let seg_axis = segment_axis(start, end);
        let seg_len = manhattan_segment_len(start, end);
        if axis.is_none() {
            axis = seg_axis;
            run += seg_len;
            continue;
        }
        if seg_axis == axis {
            run += seg_len;
        } else {
            break;
        }
    }
    run
}

fn sampled_path_crosses_rect_interior(
    sampled_path: &[(f64, f64)],
    rect: (f64, f64, f64, f64),
    margin: f64,
) -> bool {
    sampled_path
        .iter()
        .any(|point| point_inside_rect_with_margin(*point, rect, margin))
}

fn parse_svg_text_position_and_value(line: &str) -> Option<(f64, f64, String)> {
    let line = line.trim();
    if !line.starts_with("<text") {
        return None;
    }
    let x = parse_attr_f64(line, "x")?;
    let y = parse_attr_f64(line, "y")?;
    let end = line.find("</text>")?;
    let before = &line[..end];
    let start = before.rfind('>')?;
    let value = before[start + 1..].to_string();
    Some((x, y, value))
}

fn extract_edge_label_positions(
    svg: &str,
    diagram: &crate::graph::Graph,
) -> Vec<(String, (f64, f64))> {
    let mut remaining: HashMap<String, usize> = HashMap::new();
    for edge in &diagram.edges {
        if let Some(label) = &edge.label {
            *remaining.entry(label.clone()).or_insert(0) += 1;
        }
    }

    let mut labels = Vec::new();
    for line in svg.lines() {
        let Some((x, y, value)) = parse_svg_text_position_and_value(line) else {
            continue;
        };
        let Some(count) = remaining.get_mut(&value) else {
            continue;
        };
        if *count == 0 {
            continue;
        }
        *count -= 1;
        labels.push((value, (x, y)));
    }
    labels
}

fn euclidean_distance(a: (f64, f64), b: (f64, f64)) -> f64 {
    ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt()
}

fn distance_point_to_svg_segment(point: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {
    let dx = b.0 - a.0;
    let dy = b.1 - a.1;
    let seg_len_sq = dx * dx + dy * dy;
    if seg_len_sq <= 0.000_001 {
        return euclidean_distance(point, a);
    }

    let projection = ((point.0 - a.0) * dx + (point.1 - a.1) * dy) / seg_len_sq;
    let t = projection.clamp(0.0, 1.0);
    let closest = (a.0 + t * dx, a.1 + t * dy);
    euclidean_distance(point, closest)
}

fn distance_point_to_svg_path(point: (f64, f64), path: &[(f64, f64)]) -> f64 {
    if path.is_empty() {
        return f64::INFINITY;
    }
    if path.len() == 1 {
        return euclidean_distance(point, path[0]);
    }
    path.windows(2)
        .map(|segment| distance_point_to_svg_segment(point, segment[0], segment[1]))
        .fold(f64::INFINITY, f64::min)
}

fn svg_label_drift_failures(
    svg: &str,
    diagram: &crate::graph::Graph,
    max_distance: f64,
) -> Vec<String> {
    let expected_labels = diagram
        .edges
        .iter()
        .filter(|edge| edge.label.is_some())
        .count();
    let label_positions = extract_edge_label_positions(svg, diagram);
    let paths: Vec<Vec<(f64, f64)>> = edge_path_data(svg)
        .iter()
        .map(|path| parse_svg_path_points(path))
        .collect();

    let mut failures = Vec::new();
    if label_positions.len() != expected_labels {
        failures.push(format!(
            "edge-label extraction mismatch: expected={expected_labels}, extracted={}",
            label_positions.len()
        ));
    }

    for (label, point) in label_positions {
        let drift = paths
            .iter()
            .map(|path| distance_point_to_svg_path(point, path))
            .fold(f64::INFINITY, f64::min);
        if drift > max_distance {
            failures.push(format!(
                "label {label:?} at ({:.2}, {:.2}) drift={drift:.2} exceeds {max_distance:.2}",
                point.0, point.1
            ));
        }
    }

    failures
}

fn total_svg_edge_segments(svg: &str) -> usize {
    edge_path_data(svg)
        .iter()
        .map(|d| parse_svg_path_points(d).len().saturating_sub(1))
        .sum()
}

fn svg_point_face(rect: (f64, f64, f64, f64), point: (f64, f64)) -> &'static str {
    let eps = 0.5;
    let (x, y, w, h) = rect;
    let left = x;
    let right = x + w;
    let top = y;
    let bottom = y + h;

    let on_right = (point.0 - right).abs() <= eps;
    let on_left = (point.0 - left).abs() <= eps;
    let on_top = (point.1 - top).abs() <= eps;
    let on_bottom = (point.1 - bottom).abs() <= eps;

    if on_right && point.1 > top + eps && point.1 < bottom - eps {
        "right"
    } else if on_left && point.1 > top + eps && point.1 < bottom - eps {
        "left"
    } else if on_top && point.0 > left + eps && point.0 < right - eps {
        "top"
    } else if on_bottom && point.0 > left + eps && point.0 < right - eps {
        "bottom"
    } else if on_right {
        "right"
    } else if on_left {
        "left"
    } else {
        "interior_or_corner"
    }
}

fn svg_terminal_approach_face(rect: (f64, f64, f64, f64), points: &[(f64, f64)]) -> &'static str {
    if points.is_empty() {
        return "interior_or_corner";
    }

    let end = *points.last().expect("path should have at least one point");
    let direct_face = svg_point_face(rect, end);
    if direct_face != "interior_or_corner" {
        return direct_face;
    }

    if points.len() < 2 {
        return direct_face;
    }

    let prev = points[points.len() - 2];
    let dx = end.0 - prev.0;
    let dy = end.1 - prev.1;
    let (x, y, w, h) = rect;
    let left = x;
    let right = x + w;
    let top = y;
    let bottom = y + h;
    const MARKER_PULLBACK_TOLERANCE: f64 = 6.0;

    // SVG marker pullback can leave the terminal path point just outside the
    // node border. Treat that as the attached face when the terminal tangent
    // points inward toward the node.
    if end.0 > right
        && end.0 - right <= MARKER_PULLBACK_TOLERANCE
        && end.1 >= top - MARKER_PULLBACK_TOLERANCE
        && end.1 <= bottom + MARKER_PULLBACK_TOLERANCE
        && dy.abs() <= 0.5
        && dx < 0.0
    {
        return "right";
    }
    if end.0 < left
        && left - end.0 <= MARKER_PULLBACK_TOLERANCE
        && end.1 >= top - MARKER_PULLBACK_TOLERANCE
        && end.1 <= bottom + MARKER_PULLBACK_TOLERANCE
        && dy.abs() <= 0.5
        && dx > 0.0
    {
        return "left";
    }
    if end.1 > bottom
        && end.1 - bottom <= MARKER_PULLBACK_TOLERANCE
        && end.0 >= left - MARKER_PULLBACK_TOLERANCE
        && end.0 <= right + MARKER_PULLBACK_TOLERANCE
        && dx.abs() <= 0.5
        && dy < 0.0
    {
        return "bottom";
    }
    if end.1 < top
        && top - end.1 <= MARKER_PULLBACK_TOLERANCE
        && end.0 >= left - MARKER_PULLBACK_TOLERANCE
        && end.0 <= right + MARKER_PULLBACK_TOLERANCE
        && dx.abs() <= 0.5
        && dy > 0.0
    {
        return "top";
    }

    if dx.abs() >= dy.abs() {
        if dx > 0.0 {
            "right"
        } else if dx < 0.0 {
            "left"
        } else {
            "interior_or_corner"
        }
    } else if dy > 0.0 {
        "bottom"
    } else if dy < 0.0 {
        "top"
    } else {
        "interior_or_corner"
    }
}

fn svg_terminal_approach_face_relaxed(
    rect: (f64, f64, f64, f64),
    points: &[(f64, f64)],
) -> &'static str {
    if points.is_empty() {
        return "interior_or_corner";
    }

    let end = *points.last().expect("path should have at least one point");
    let direct_face = svg_point_face(rect, end);
    if direct_face != "interior_or_corner" {
        return direct_face;
    }
    if points.len() < 2 {
        return direct_face;
    }

    let prev = points[points.len() - 2];
    let dx = end.0 - prev.0;
    let dy = end.1 - prev.1;
    let (x, y, w, h) = rect;
    let left = x;
    let right = x + w;
    let top = y;
    let bottom = y + h;
    const MARKER_PULLBACK_TOLERANCE: f64 = 6.0;

    if end.0 > right
        && end.0 - right <= MARKER_PULLBACK_TOLERANCE
        && end.1 >= top - MARKER_PULLBACK_TOLERANCE
        && end.1 <= bottom + MARKER_PULLBACK_TOLERANCE
        && dx < 0.0
    {
        return "right";
    }
    if end.0 < left
        && left - end.0 <= MARKER_PULLBACK_TOLERANCE
        && end.1 >= top - MARKER_PULLBACK_TOLERANCE
        && end.1 <= bottom + MARKER_PULLBACK_TOLERANCE
        && dx > 0.0
    {
        return "left";
    }
    if end.1 > bottom
        && end.1 - bottom <= MARKER_PULLBACK_TOLERANCE
        && end.0 >= left - MARKER_PULLBACK_TOLERANCE
        && end.0 <= right + MARKER_PULLBACK_TOLERANCE
        && dy < 0.0
    {
        return "bottom";
    }
    if end.1 < top
        && top - end.1 <= MARKER_PULLBACK_TOLERANCE
        && end.0 >= left - MARKER_PULLBACK_TOLERANCE
        && end.0 <= right + MARKER_PULLBACK_TOLERANCE
        && dy > 0.0
    {
        return "top";
    }

    svg_terminal_approach_face(rect, points)
}

fn svg_source_departure_face(rect: (f64, f64, f64, f64), points: &[(f64, f64)]) -> &'static str {
    if points.is_empty() {
        return "interior_or_corner";
    }

    let start = points[0];
    let direct_face = svg_point_face(rect, start);
    if direct_face != "interior_or_corner" {
        return direct_face;
    }
    if points.len() < 2 {
        return direct_face;
    }

    let next = points[1];
    let dx = next.0 - start.0;
    let dy = next.1 - start.1;
    if dx.abs() >= dy.abs() {
        if dx > 0.0 {
            "right"
        } else if dx < 0.0 {
            "left"
        } else {
            "interior_or_corner"
        }
    } else if dy > 0.0 {
        "bottom"
    } else if dy < 0.0 {
        "top"
    } else {
        "interior_or_corner"
    }
}

fn manhattan_segment_len(a: (f64, f64), b: (f64, f64)) -> f64 {
    (a.0 - b.0).abs() + (a.1 - b.1).abs()
}

fn horizontal_span(points: &[(f64, f64)]) -> f64 {
    if points.is_empty() {
        return 0.0;
    }
    let min_x = points.iter().map(|p| p.0).fold(f64::INFINITY, f64::min);
    let max_x = points.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max);
    max_x - min_x
}

fn segment_axis(a: (f64, f64), b: (f64, f64)) -> Option<char> {
    if (a.0 - b.0).abs() < 0.001 && (a.1 - b.1).abs() >= 0.001 {
        Some('V')
    } else if (a.1 - b.1).abs() < 0.001 && (a.0 - b.0).abs() >= 0.001 {
        Some('H')
    } else {
        None
    }
}

fn trailing_segment_run_len(points: &[(f64, f64)], segment_count: usize) -> f64 {
    if points.len() < 2 || segment_count == 0 {
        return 0.0;
    }
    points
        .windows(2)
        .rev()
        .take(segment_count)
        .map(|segment| manhattan_segment_len(segment[0], segment[1]))
        .sum()
}

fn terminal_collinear_run_len(points: &[(f64, f64)]) -> f64 {
    if points.len() < 2 {
        return 0.0;
    }
    let mut segments = points.windows(2).rev();
    let Some(last) = segments.next() else {
        return 0.0;
    };
    let Some(axis) = segment_axis(last[0], last[1]) else {
        return manhattan_segment_len(last[0], last[1]);
    };

    let mut run = manhattan_segment_len(last[0], last[1]);
    for segment in segments {
        if segment_axis(segment[0], segment[1]) != Some(axis) {
            break;
        }
        run += manhattan_segment_len(segment[0], segment[1]);
    }
    run
}

fn has_immediate_axis_backtrack(points: &[(f64, f64)]) -> bool {
    points.windows(3).any(|triple| {
        let a = triple[0];
        let b = triple[1];
        let c = triple[2];
        match (segment_axis(a, b), segment_axis(b, c)) {
            (Some('V'), Some('V')) => {
                let dy1 = b.1 - a.1;
                let dy2 = c.1 - b.1;
                dy1.abs() > 0.001 && dy2.abs() > 0.001 && dy1.signum() != dy2.signum()
            }
            (Some('H'), Some('H')) => {
                let dx1 = b.0 - a.0;
                let dx2 = c.0 - b.0;
                dx1.abs() > 0.001 && dx2.abs() > 0.001 && dx1.signum() != dx2.signum()
            }
            _ => false,
        }
    })
}

fn has_tiny_lateral_direction_reversal(points: &[(f64, f64)], max_lateral: f64) -> bool {
    const EPS: f64 = 0.001;
    if points.len() < 3 || max_lateral <= 0.0 {
        return false;
    }

    points.windows(3).any(|triple| {
        let a = triple[0];
        let b = triple[1];
        let c = triple[2];
        let dx1 = b.0 - a.0;
        let dx2 = c.0 - b.0;
        let dy1 = b.1 - a.1;
        let dy2 = c.1 - b.1;

        let x_reversal = dx1.abs() > EPS && dx2.abs() > EPS && dx1.signum() != dx2.signum();
        let y_reversal = dy1.abs() > EPS && dy2.abs() > EPS && dy1.signum() != dy2.signum();
        let mostly_vertical = (dy1.abs() + dy2.abs()) > (dx1.abs() + dx2.abs());
        let mostly_horizontal = (dx1.abs() + dx2.abs()) > (dy1.abs() + dy2.abs());

        (x_reversal && dx1.abs().min(dx2.abs()) < max_lateral && mostly_vertical)
            || (y_reversal && dy1.abs().min(dy2.abs()) < max_lateral && mostly_horizontal)
    })
}

fn has_primary_axis_backtrack(points: &[(f64, f64)], direction: crate::graph::Direction) -> bool {
    const EPS: f64 = 0.001;
    if points.len() < 2 {
        return false;
    }

    match direction {
        crate::graph::Direction::TopDown => points.windows(2).any(|seg| seg[1].1 < seg[0].1 - EPS),
        crate::graph::Direction::BottomTop => {
            points.windows(2).any(|seg| seg[1].1 > seg[0].1 + EPS)
        }
        crate::graph::Direction::LeftRight => {
            points.windows(2).any(|seg| seg[1].0 < seg[0].0 - EPS)
        }
        crate::graph::Direction::RightLeft => {
            points.windows(2).any(|seg| seg[1].0 > seg[0].0 + EPS)
        }
    }
}

#[derive(Debug)]
struct SvgStyleMonitorReport {
    scanned_styled_paths: usize,
    violations: Vec<String>,
    summary_line: String,
}

fn min_svg_segment_len(points: &[(f64, f64)]) -> f64 {
    points
        .windows(2)
        .map(|segment| {
            let dx = segment[1].0 - segment[0].0;
            let dy = segment[1].1 - segment[0].1;
            (dx * dx + dy * dy).sqrt()
        })
        .fold(f64::INFINITY, f64::min)
}

fn style_segment_monitor_report_for_svg(
    fixtures: &[&str],
    min_segment_threshold: f64,
) -> SvgStyleMonitorReport {
    let mut scanned_styled_paths = 0usize;
    let mut violations = Vec::new();

    for fixture in fixtures {
        let diagram = load_flowchart_fixture_diagram(fixture);
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);

        for line in svg.lines().map(str::trim) {
            if !line.starts_with("<path d=\"")
                || !(line.contains("marker-end=") || line.contains("marker-start="))
            {
                continue;
            }
            let is_styled =
                line.contains("stroke-dasharray") || line.contains("stroke-width=\"2.00\"");
            if !is_styled {
                continue;
            }

            let Some(start) = line.find("d=\"") else {
                continue;
            };
            let after = &line[start + 3..];
            let Some(end) = after.find('"') else {
                continue;
            };
            let points = parse_svg_path_points(&after[..end]);
            if points.len() < 2 {
                continue;
            }

            let min_segment = min_svg_segment_len(&points);
            scanned_styled_paths += 1;
            if min_segment < min_segment_threshold {
                violations.push(format!(
                    "{fixture} styled_path min_segment={min_segment:.2} threshold={min_segment_threshold:.2} path={points:?}"
                ));
            }
        }
    }

    SvgStyleMonitorReport {
        scanned_styled_paths,
        summary_line: format!(
            "style_monitor_svg scanned={} violations={} threshold={:.2}",
            scanned_styled_paths,
            violations.len(),
            min_segment_threshold
        ),
        violations,
    }
}

fn parse_attr_value<'a>(line: &'a str, attr: &str) -> Option<&'a str> {
    let marker = format!("{attr}=\"");
    let start = line.find(&marker)? + marker.len();
    let rest = &line[start..];
    let end = rest.find('"')?;
    Some(&rest[..end])
}

fn parse_attr_f64(line: &str, attr: &str) -> Option<f64> {
    parse_attr_value(line, attr)?.parse::<f64>().ok()
}

fn parse_svg_viewbox(svg: &str) -> Option<(f64, f64, f64, f64)> {
    let root = svg
        .lines()
        .find(|line| line.trim_start().starts_with("<svg"))?;
    let marker = "viewBox=\"";
    let start = root.find(marker)? + marker.len();
    let rest = &root[start..];
    let end = rest.find('"')?;
    let parts: Vec<f64> = rest[..end]
        .split_whitespace()
        .filter_map(|part| part.parse::<f64>().ok())
        .collect();
    if parts.len() == 4 {
        Some((parts[0], parts[1], parts[2], parts[3]))
    } else {
        None
    }
}

fn parse_svg_main_translate(svg: &str) -> Option<(f64, f64)> {
    let line = svg
        .lines()
        .map(str::trim)
        .find(|line| line.starts_with("<g transform=\"translate("))?;
    let marker = "transform=\"translate(";
    let start = line.find(marker)? + marker.len();
    let rest = &line[start..];
    let end = rest.find(")\"")?;
    let (x, y) = rest[..end].split_once(',')?;
    Some((x.parse::<f64>().ok()?, y.parse::<f64>().ok()?))
}

fn point_inside_rect_with_margin(
    point: (f64, f64),
    rect: (f64, f64, f64, f64),
    margin: f64,
) -> bool {
    let (x, y, w, h) = rect;
    point.0 > x + margin
        && point.0 < x + w - margin
        && point.1 > y + margin
        && point.1 < y + h - margin
}

fn node_rect_for_label(svg: &str, label: &str) -> Option<(f64, f64, f64, f64)> {
    let (text_x, text_y) = svg.lines().find_map(|line| {
        let (x, y, value) = parse_svg_text_position_and_value(line)?;
        (value == label).then_some((x, y))
    })?;

    svg.lines()
        .find_map(|line| {
            if !line.contains("<rect ")
                || !line.contains("stroke=\"#333\"")
                || !line.contains("fill=\"white\"")
            {
                return None;
            }
            let x = parse_attr_f64(line, "x")?;
            let y = parse_attr_f64(line, "y")?;
            let width = parse_attr_f64(line, "width")?;
            let height = parse_attr_f64(line, "height")?;
            let inside = text_x >= x && text_x <= x + width && text_y >= y && text_y <= y + height;
            if inside {
                Some((x, y, width, height))
            } else {
                None
            }
        })
        .or_else(|| {
            svg.lines().find_map(|line| {
                if !line.contains("<polygon ")
                    || !line.contains("stroke=\"#333\"")
                    || !line.contains("fill=\"white\"")
                {
                    return None;
                }
                let points = parse_attr_value(line, "points")?;
                let points: Vec<(f64, f64)> = points
                    .split_whitespace()
                    .filter_map(|point| {
                        let (x, y) = point.split_once(',')?;
                        Some((x.parse::<f64>().ok()?, y.parse::<f64>().ok()?))
                    })
                    .collect();
                if points.is_empty() {
                    return None;
                }
                let min_x = points.iter().map(|(x, _)| *x).fold(f64::INFINITY, f64::min);
                let max_x = points
                    .iter()
                    .map(|(x, _)| *x)
                    .fold(f64::NEG_INFINITY, f64::max);
                let min_y = points.iter().map(|(_, y)| *y).fold(f64::INFINITY, f64::min);
                let max_y = points
                    .iter()
                    .map(|(_, y)| *y)
                    .fold(f64::NEG_INFINITY, f64::max);
                let inside =
                    text_x >= min_x && text_x <= max_x && text_y >= min_y && text_y <= max_y;
                if inside {
                    Some((min_x, min_y, max_x - min_x, max_y - min_y))
                } else {
                    None
                }
            })
        })
}

fn axis_aligned_segment_crosses_rect_interior(
    a: (f64, f64),
    b: (f64, f64),
    rect: (f64, f64, f64, f64),
    margin: f64,
) -> bool {
    let (x, y, w, h) = rect;
    let left = x + margin;
    let right = x + w - margin;
    let top = y + margin;
    let bottom = y + h - margin;
    if left >= right || top >= bottom {
        return false;
    }

    let eps = 0.5;
    if (a.1 - b.1).abs() <= eps {
        let seg_y = a.1;
        if seg_y <= top || seg_y >= bottom {
            return false;
        }
        let seg_min_x = a.0.min(b.0);
        let seg_max_x = a.0.max(b.0);
        return seg_max_x > left && seg_min_x < right;
    }

    if (a.0 - b.0).abs() <= eps {
        let seg_x = a.0;
        if seg_x <= left || seg_x >= right {
            return false;
        }
        let seg_min_y = a.1.min(b.1);
        let seg_max_y = a.1.max(b.1);
        return seg_max_y > top && seg_min_y < bottom;
    }

    false
}

fn path_crosses_rect_interior(
    path: &[(f64, f64)],
    rect: (f64, f64, f64, f64),
    margin: f64,
) -> bool {
    path.windows(2).any(|segment| {
        axis_aligned_segment_crosses_rect_interior(segment[0], segment[1], rect, margin)
    })
}

fn segment_crosses_rect_interior_any(
    a: (f64, f64),
    b: (f64, f64),
    rect: (f64, f64, f64, f64),
    margin: f64,
) -> bool {
    fn axis_interval(a: f64, d: f64, min_v: f64, max_v: f64) -> Option<(f64, f64)> {
        const EPS: f64 = 1e-6;
        if d.abs() <= EPS {
            if a > min_v + EPS && a < max_v - EPS {
                Some((0.0, 1.0))
            } else {
                None
            }
        } else {
            let t1 = (min_v - a) / d;
            let t2 = (max_v - a) / d;
            let lo = t1.min(t2).max(0.0);
            let hi = t1.max(t2).min(1.0);
            if hi > lo + EPS { Some((lo, hi)) } else { None }
        }
    }

    let (x, y, w, h) = rect;
    let min_x = x + margin;
    let max_x = x + w - margin;
    let min_y = y + margin;
    let max_y = y + h - margin;
    if !(max_x > min_x && max_y > min_y) {
        return false;
    }

    let dx = b.0 - a.0;
    let dy = b.1 - a.1;
    let Some((tx_lo, tx_hi)) = axis_interval(a.0, dx, min_x, max_x) else {
        return false;
    };
    let Some((ty_lo, ty_hi)) = axis_interval(a.1, dy, min_y, max_y) else {
        return false;
    };

    let lo = tx_lo.max(ty_lo);
    let hi = tx_hi.min(ty_hi);
    hi > lo + 1e-6
}

fn path_crosses_rect_interior_any(
    path: &[(f64, f64)],
    rect: (f64, f64, f64, f64),
    margin: f64,
) -> bool {
    path.windows(2)
        .any(|segment| segment_crosses_rect_interior_any(segment[0], segment[1], rect, margin))
}

fn vertical_lane_x_at_y(path: &[(f64, f64)], probe_y: f64) -> Option<f64> {
    let eps = 0.5;
    path.windows(2).find_map(|segment| {
        let a = segment[0];
        let b = segment[1];
        if (a.0 - b.0).abs() > eps {
            return None;
        }
        let min_y = a.1.min(b.1);
        let max_y = a.1.max(b.1);
        if probe_y >= min_y - eps && probe_y <= max_y + eps {
            Some(a.0)
        } else {
            None
        }
    })
}

/// Find the midpoint y of the longest vertical segment in a path.
fn longest_vertical_segment_midpoint(path: &[(f64, f64)]) -> Option<f64> {
    let eps = 0.5;
    let mut best_len = 0.0_f64;
    let mut best_mid = None;
    for segment in path.windows(2) {
        let a = segment[0];
        let b = segment[1];
        if (a.0 - b.0).abs() > eps {
            continue;
        }
        let len = (b.1 - a.1).abs();
        if len > best_len {
            best_len = len;
            best_mid = Some((a.1 + b.1) / 2.0);
        }
    }
    best_mid
}

fn edge_path_for_svg_order(
    diagram: &crate::graph::Graph,
    svg: &str,
    edge_index: usize,
) -> Vec<(f64, f64)> {
    let mut visible_edge_indexes: Vec<usize> = diagram
        .edges
        .iter()
        .filter(|edge| edge.stroke != Stroke::Invisible)
        .map(|edge| edge.index)
        .collect();
    visible_edge_indexes.sort_unstable();

    let svg_position = visible_edge_indexes
        .iter()
        .position(|idx| *idx == edge_index)
        .expect("edge index should be visible in SVG");
    let paths = edge_path_data(svg);
    parse_svg_path_points(
        paths
            .get(svg_position)
            .expect("edge path should exist at visible edge position"),
    )
}

fn edge_path_d_for_svg_order(
    diagram: &crate::graph::Graph,
    svg: &str,
    edge_index: usize,
) -> String {
    let mut visible_edge_indexes: Vec<usize> = diagram
        .edges
        .iter()
        .filter(|edge| edge.stroke != Stroke::Invisible)
        .map(|edge| edge.index)
        .collect();
    visible_edge_indexes.sort_unstable();

    let svg_position = visible_edge_indexes
        .iter()
        .position(|idx| *idx == edge_index)
        .expect("edge index should be visible in SVG");
    edge_path_data(svg)
        .get(svg_position)
        .expect("edge path should exist at visible edge position")
        .to_string()
}

fn render_flux_svg_with_style(
    diagram: &crate::graph::Graph,
    edge_routing: EdgeRouting,
    routing_style: RoutingStyle,
    curve: Curve,
) -> String {
    debug_assert_eq!(routing_style, routing_style_for(edge_routing));
    let options = RenderConfig {
        routing_style: Some(routing_style_for(edge_routing)),
        curve: Some(curve),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    render_svg(diagram, &options)
}

fn render_flux_engine_svg_for_fixture_with_style(
    fixture_name: &str,
    routing_style: RoutingStyle,
    curve: Curve,
) -> String {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join(fixture_name);
    let input = fs::read_to_string(fixture).expect("fixture should load");
    crate::render_diagram(
        &input,
        OutputFormat::Svg,
        &RenderConfig {
            layout_engine: Some(
                crate::EngineAlgorithmId::parse("flux-layered")
                    .expect("flux-layered id should parse"),
            ),
            routing_style: Some(routing_style),
            curve: Some(curve),
            path_simplification: PathSimplification::None,
            ..RenderConfig::default()
        },
    )
    .expect("flux-layered SVG render should succeed")
}

fn svg_node_centers_by_id(diagram: &crate::graph::Graph, svg: &str) -> HashMap<String, (f64, f64)> {
    diagram
        .nodes
        .iter()
        .filter_map(|(id, node)| {
            let rect = node_rect_for_label(svg, &node.label)?;
            Some((id.clone(), (rect.0 + rect.2 / 2.0, rect.1 + rect.3 / 2.0)))
        })
        .collect()
}

fn assert_svg_node_centers_equal(
    left: &HashMap<String, (f64, f64)>,
    right: &HashMap<String, (f64, f64)>,
    tolerance: f64,
    context: &str,
) {
    let left_keys: BTreeSet<_> = left.keys().cloned().collect();
    let right_keys: BTreeSet<_> = right.keys().cloned().collect();
    assert_eq!(
        left_keys, right_keys,
        "{context}: node key sets should match between renders"
    );

    for node_id in left_keys {
        let left_center = left
            .get(&node_id)
            .unwrap_or_else(|| panic!("{context}: missing node {node_id} in left render"));
        let right_center = right
            .get(&node_id)
            .unwrap_or_else(|| panic!("{context}: missing node {node_id} in right render"));
        let dx = (left_center.0 - right_center.0).abs();
        let dy = (left_center.1 - right_center.1).abs();
        assert!(
            dx <= tolerance && dy <= tolerance,
            "{context}: node {node_id} center drift exceeded tolerance {tolerance}: left={left_center:?}, right={right_center:?}, delta=({dx:.3}, {dy:.3})"
        );
    }
}

fn strict_segment_interior_intersection(
    a0: (f64, f64),
    a1: (f64, f64),
    b0: (f64, f64),
    b1: (f64, f64),
) -> bool {
    let eps = 1.0e-6;
    let r = (a1.0 - a0.0, a1.1 - a0.1);
    let s = (b1.0 - b0.0, b1.1 - b0.1);
    let r_len_sq = r.0 * r.0 + r.1 * r.1;
    let s_len_sq = s.0 * s.0 + s.1 * s.1;
    if r_len_sq <= eps || s_len_sq <= eps {
        return false;
    }

    let cross = |u: (f64, f64), v: (f64, f64)| u.0 * v.1 - u.1 * v.0;
    let q_minus_p = (b0.0 - a0.0, b0.1 - a0.1);
    let denom = cross(r, s);
    if denom.abs() <= eps {
        // Treat parallel/collinear overlaps as non-crossing for this lock:
        // the regression target is strict interior X-crossing.
        return false;
    }

    let t = cross(q_minus_p, s) / denom;
    let u = cross(q_minus_p, r) / denom;
    t > eps && t < 1.0 - eps && u > eps && u < 1.0 - eps
}

fn paths_have_strict_interior_crossing(path_a: &[(f64, f64)], path_b: &[(f64, f64)]) -> bool {
    path_a.windows(2).any(|a_seg| {
        path_b.windows(2).any(|b_seg| {
            strict_segment_interior_intersection(a_seg[0], a_seg[1], b_seg[0], b_seg[1])
        })
    })
}

fn load_flowchart_fixture_diagram(name: &str) -> crate::graph::Graph {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join(name);
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    compile_to_graph(&flowchart)
}

/// Style tuple: (RoutingStyle, Curve)
/// Equivalents: SHARP = Polyline+Linear(Sharp), SMOOTH = Orthogonal+Basis, ROUNDED = Orthogonal+Linear(Rounded)
type StyleTuple = (RoutingStyle, Curve);
const SHARP: StyleTuple = (RoutingStyle::Polyline, Curve::Linear(CornerStyle::Sharp));
const SMOOTH: StyleTuple = (RoutingStyle::Orthogonal, Curve::Basis);
const ROUNDED: StyleTuple = (
    RoutingStyle::Orthogonal,
    Curve::Linear(CornerStyle::Rounded),
);

fn render_fixture_svg(
    diagram: &crate::graph::Graph,
    edge_routing: EdgeRouting,
    style: StyleTuple,
) -> String {
    let (_, curve) = style;
    let options = RenderConfig {
        routing_style: Some(routing_style_for(edge_routing)),
        curve: Some(curve),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    render_svg(diagram, &options)
}

fn edge_index(diagram: &crate::graph::Graph, from: &str, to: &str) -> usize {
    diagram
        .edges
        .iter()
        .find(|edge| edge.from == from && edge.to == to)
        .unwrap_or_else(|| panic!("expected edge {from} -> {to}"))
        .index
}

fn node_center_for_id(diagram: &crate::graph::Graph, node_id: &str) -> (f64, f64) {
    let config =
        EngineConfig::Layered(crate::engines::graph::algorithms::layered::LayoutConfig::default());
    let geom = run_layered_layout(&MeasurementMode::Grid, diagram, &config)
        .expect("layout should succeed for center lookup");
    let node = geom
        .nodes
        .get(node_id)
        .unwrap_or_else(|| panic!("expected node `{node_id}` in layout geometry"));
    (
        node.rect.x + node.rect.width / 2.0,
        node.rect.y + node.rect.height / 2.0,
    )
}

fn svg_node_rect_for_id(
    diagram: &crate::graph::Graph,
    svg: &str,
    node_id: &str,
) -> (f64, f64, f64, f64) {
    let config =
        EngineConfig::Layered(crate::engines::graph::algorithms::layered::LayoutConfig::default());
    let geom = run_layered_layout(&default_proportional_mode(), diagram, &config)
        .expect("layout should succeed for rect lookup");
    let node = geom
        .nodes
        .get(node_id)
        .unwrap_or_else(|| panic!("expected node `{node_id}` in layout geometry"));
    let (tx, ty) = parse_svg_main_translate(svg).unwrap_or((0.0, 0.0));
    (
        node.rect.x + tx,
        node.rect.y + ty,
        node.rect.width,
        node.rect.height,
    )
}

fn distance(a: (f64, f64), b: (f64, f64)) -> f64 {
    ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt()
}

#[test]
fn svg_direct_route_straight_uses_source_and_target_ports() {
    let diagram = load_flowchart_fixture_diagram("chain.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Direct),
        curve: Some(Curve::Linear(CornerStyle::Sharp)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let edge = diagram
        .edges
        .iter()
        .find(|edge| edge.stroke != Stroke::Invisible)
        .expect("chain fixture should contain at least one visible edge");
    let points = edge_path_for_svg_order(&diagram, &svg, edge.index);

    let source_label = &diagram
        .nodes
        .get(&edge.from)
        .expect("source node should exist")
        .label;
    let target_label = &diagram
        .nodes
        .get(&edge.to)
        .expect("target node should exist")
        .label;
    let source_rect =
        node_rect_for_label(&svg, source_label).expect("source rect should exist in rendered SVG");
    let target_rect =
        node_rect_for_label(&svg, target_label).expect("target rect should exist in rendered SVG");

    let source_face = svg_source_departure_face(source_rect, &points);
    let target_face = svg_terminal_approach_face_relaxed(target_rect, &points);

    assert_eq!(
        source_face, "bottom",
        "direct/straight source should depart from the TD bottom face: points={points:?}"
    );
    assert_eq!(
        target_face, "top",
        "direct/straight target should attach on the TD top face: points={points:?}"
    );
}

#[test]
fn svg_marker_offsets_preserve_terminal_faces_for_orthogonal_and_non_orthogonal_paths() {
    let diagram = load_flowchart_fixture_diagram("decision.mmd");
    let cases = [
        (
            "direct-sharp",
            EdgeRouting::DirectRoute,
            Curve::Linear(CornerStyle::Sharp),
        ),
        (
            "polyline-sharp",
            EdgeRouting::PolylineRoute,
            Curve::Linear(CornerStyle::Sharp),
        ),
        (
            "orthogonal-rounded",
            EdgeRouting::OrthogonalRoute,
            Curve::Linear(CornerStyle::Rounded),
        ),
    ];

    for (name, edge_routing, curve) in cases {
        let svg = render_svg(
            &diagram,
            &RenderConfig {
                routing_style: Some(routing_style_for(edge_routing)),
                curve: Some(curve),
                path_simplification: PathSimplification::None,
                ..Default::default()
            },
        );
        let points = edge_path_for_svg_order(&diagram, &svg, edge_index(&diagram, "A", "B"));
        let source_rect = svg_node_rect_for_id(&diagram, &svg, "A");
        let target_rect = svg_node_rect_for_id(&diagram, &svg, "B");

        assert_eq!(
            svg_source_departure_face(source_rect, &points),
            "bottom",
            "{name} source should keep bottom-face marker support on A->B: points={points:?}"
        );
        assert_eq!(
            svg_terminal_approach_face_relaxed(target_rect, &points),
            "top",
            "{name} target should keep top-face marker support on A->B: points={points:?}"
        );
    }
}

#[test]
fn svg_direct_route_double_skip_uses_avoidance_path_for_long_skip_edges() {
    let diagram = load_flowchart_fixture_diagram("double_skip.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Direct),
        curve: Some(Curve::Linear(CornerStyle::Sharp)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let skip_edge_index = edge_index(&diagram, "A", "D");
    let points = edge_path_for_svg_order(&diagram, &svg, skip_edge_index);
    assert!(
        points.len() > 2,
        "direct mode should preserve avoidance geometry when the straight skip edge would cut through intermediate nodes: points={points:?}"
    );
}

#[test]
fn svg_straight_direct_route_double_skip_avoids_tiny_lateral_shim() {
    let diagram = load_flowchart_fixture_diagram("double_skip.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Direct),
        curve: Some(Curve::Linear(CornerStyle::Sharp)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let skip_edge_index = edge_index(&diagram, "A", "D");
    let points = edge_path_for_svg_order(&diagram, &svg, skip_edge_index);
    assert!(
        !has_tiny_lateral_direction_reversal(&points, 3.0),
        "direct straight long skip should avoid tiny lateral reversal shims near bends; points={points:?}"
    );
}

#[test]
fn svg_curved_step_avoids_unrelated_node_interiors_for_double_skip_and_compat_invisible() {
    let cases = [
        (
            "compat_invisible_edge.mmd",
            vec![("A", "C", "B"), ("A", "B", "C")],
        ),
        (
            "double_skip.mmd",
            vec![("A", "C", "Step 1"), ("A", "D", "Step 2")],
        ),
    ];

    for (fixture_name, edge_specs) in cases {
        let diagram = load_flowchart_fixture_diagram(fixture_name);
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Basis),
            path_simplification: PathSimplification::Lossless,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);

        for (from, to, blocked_label) in edge_specs {
            let edge_idx = edge_index(&diagram, from, to);
            let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
            let blocked_rect = node_rect_for_label(&svg, blocked_label).unwrap_or_else(|| {
                panic!("missing blocked node rect for {fixture_name}:{blocked_label}")
            });
            assert!(
                !path_crosses_rect_interior(&points, blocked_rect, 1.0),
                "{fixture_name} curved-step edge {from}->{to} should avoid unrelated node {blocked_label} interior; points={points:?}, blocked_rect={blocked_rect:?}"
            );
        }
    }
}

#[derive(Clone, Copy)]
struct BasisStyleCase {
    name: &'static str,
    edge_routing: EdgeRouting,
}

const BASIS_STYLE_PRESET: BasisStyleCase = BasisStyleCase {
    name: "basis",
    edge_routing: EdgeRouting::PolylineRoute,
};

const CURVED_STEP_STYLE_PRESET: BasisStyleCase = BasisStyleCase {
    name: "curved-step",
    edge_routing: EdgeRouting::OrthogonalRoute,
};

fn render_basis_style_fixture_svg(
    diagram: &crate::graph::Graph,
    style: BasisStyleCase,
    path_simplification: PathSimplification,
) -> String {
    let options = RenderConfig {
        routing_style: Some(routing_style_for(style.edge_routing)),
        curve: Some(Curve::Basis),
        path_simplification,
        ..Default::default()
    };
    render_svg(diagram, &options)
}

#[test]
fn svg_stem_basis_backward_and_skip_edges_have_min_visible_terminal_runs() {
    let cases = [
        ("git_workflow.mmd", "Remote", "Working"),
        ("git_workflow_td.mmd", "Remote", "Working"),
        ("decision.mmd", "D", "A"),
        ("skip_edge_collision.mmd", "A", "D"),
    ];
    let styles = [BASIS_STYLE_PRESET, CURVED_STEP_STYLE_PRESET];

    for style in styles {
        for (fixture, from, to) in cases {
            let diagram = load_flowchart_fixture_diagram(fixture);
            let svg = render_basis_style_fixture_svg(&diagram, style, PathSimplification::None);
            let edge_idx = edge_index(&diagram, from, to);
            let d = edge_path_d_for_svg_order(&diagram, &svg, edge_idx);
            let start_run = svg_visible_line_run_from_start(&d);
            let end_run = svg_visible_line_run_from_end(&d);
            assert!(
                start_run >= 8.0,
                "{fixture} {from}->{to} {} should keep >=8px visible source stem in emitted SVG path commands, got {start_run:.2}; d={d}",
                style.name
            );
            assert!(
                end_run >= 8.0,
                "{fixture} {from}->{to} {} should keep >=8px visible terminal stem in emitted SVG path commands, got {end_run:.2}; d={d}",
                style.name
            );
        }
    }

    let lossless_cases = [
        ("git_workflow.mmd", "Remote", "Working"),
        ("skip_edge_collision.mmd", "A", "D"),
    ];
    for style in styles {
        for (fixture, from, to) in lossless_cases {
            let diagram = load_flowchart_fixture_diagram(fixture);
            let svg = render_basis_style_fixture_svg(&diagram, style, PathSimplification::Lossless);
            let edge_idx = edge_index(&diagram, from, to);
            let d = edge_path_d_for_svg_order(&diagram, &svg, edge_idx);
            let start_run = svg_visible_line_run_from_start(&d);
            let end_run = svg_visible_line_run_from_end(&d);
            assert!(
                start_run >= 8.0 && end_run >= 8.0,
                "{fixture} {from}->{to} {} lossless should keep >=8px source/terminal stems; start={start_run:.2}, end={end_run:.2}, d={d}",
                style.name
            );
        }
    }
}

#[test]
fn svg_stem_basis_backward_and_skip_edges_use_compact_visible_caps() {
    const MAX_VISIBLE_CAP_RUN: f64 = 40.0;
    let cases = [
        ("decision.mmd", "D", "A"),
        ("skip_edge_collision.mmd", "A", "D"),
        ("double_skip.mmd", "A", "D"),
    ];
    let styles = [BASIS_STYLE_PRESET];

    for style in styles {
        for (fixture, from, to) in cases {
            let diagram = load_flowchart_fixture_diagram(fixture);
            let svg = render_basis_style_fixture_svg(&diagram, style, PathSimplification::None);
            let edge_idx = edge_index(&diagram, from, to);
            let d = edge_path_d_for_svg_order(&diagram, &svg, edge_idx);
            let start_run = svg_visible_line_run_from_start(&d);
            let end_run = svg_visible_line_run_from_end(&d);
            assert!(
                start_run <= MAX_VISIBLE_CAP_RUN,
                "{fixture} {from}->{to} {} should keep source cap run compact (<= {MAX_VISIBLE_CAP_RUN}px) so basis stays curved; got {start_run:.2}; d={d}",
                style.name
            );
            assert!(
                end_run <= MAX_VISIBLE_CAP_RUN,
                "{fixture} {from}->{to} {} should keep terminal cap run compact (<= {MAX_VISIBLE_CAP_RUN}px) so basis stays curved; got {end_run:.2}; d={d}",
                style.name
            );
        }
    }
}

#[test]
fn svg_basis_reciprocal_backward_edges_keep_visible_terminal_stems() {
    let diagram = load_flowchart_fixture_diagram("diamond_backward.mmd");
    let edge_idx = edge_index(&diagram, "C", "B");
    let styles = [BASIS_STYLE_PRESET, CURVED_STEP_STYLE_PRESET];

    for style in styles {
        let svg = render_basis_style_fixture_svg(&diagram, style, PathSimplification::None);
        let d = edge_path_d_for_svg_order(&diagram, &svg, edge_idx);
        let start_run = svg_visible_line_run_from_start(&d);
        let end_run = svg_visible_line_run_from_end(&d);

        assert!(
            start_run >= 8.0,
            "diamond_backward C->B {} should keep >=8px visible source stem; got {start_run:.2}; d={d}",
            style.name
        );
        assert!(
            end_run >= 8.0,
            "diamond_backward C->B {} should keep >=8px visible terminal stem; got {end_run:.2}; d={d}",
            style.name
        );
    }
}

#[test]
fn svg_overlap_curved_basis_skip_and_backward_avoid_unrelated_node_interiors() {
    let cases = [
        (
            "skip_edge_collision.mmd",
            vec![("A", "D", "Step 1"), ("A", "D", "Step 2")],
        ),
        (
            "double_skip.mmd",
            vec![("A", "C", "Step 1"), ("A", "D", "Step 2")],
        ),
        (
            "decision.mmd",
            vec![("D", "A", "Debug"), ("D", "A", "Great!")],
        ),
    ];
    let styles = [BASIS_STYLE_PRESET, CURVED_STEP_STYLE_PRESET];

    for style in styles {
        for (fixture, edge_specs) in &cases {
            let diagram = load_flowchart_fixture_diagram(fixture);
            let svg = render_basis_style_fixture_svg(&diagram, style, PathSimplification::None);
            for (from, to, blocked_label) in edge_specs {
                let edge_idx = edge_index(&diagram, from, to);
                let d = edge_path_d_for_svg_order(&diagram, &svg, edge_idx);
                let commands = parse_svg_path_command_sequence(&d);
                let sampled = sample_svg_path_commands(&commands, 48);
                let blocked_rect = node_rect_for_label(&svg, blocked_label).unwrap_or_else(|| {
                    panic!("missing blocked node rect for {fixture}:{blocked_label}")
                });
                assert!(
                    !sampled_path_crosses_rect_interior(&sampled, blocked_rect, 1.0),
                    "{fixture} {from}->{to} {} should avoid unrelated node {blocked_label} interior in sampled curved geometry; sampled={sampled:?}, blocked_rect={blocked_rect:?}, d={d}",
                    style.name
                );
            }
        }
    }
}

#[test]
fn routing_overlap_skip_and_backward_orthogonal_paths_avoid_unrelated_node_interiors() {
    let cases = [
        (
            "skip_edge_collision.mmd",
            vec![("A", "D", "Step 1"), ("A", "D", "Step 2")],
        ),
        (
            "double_skip.mmd",
            vec![("A", "C", "Step 1"), ("A", "D", "Step 2")],
        ),
        (
            "decision.mmd",
            vec![("D", "A", "Debug"), ("D", "A", "Great!")],
        ),
    ];

    for (fixture, edge_specs) in cases {
        let diagram = load_flowchart_fixture_diagram(fixture);
        let measurement_mode = default_proportional_mode();
        let config = EngineConfig::Layered(
            crate::engines::graph::algorithms::layered::LayoutConfig::default(),
        );
        let geometry = run_layered_layout(&measurement_mode, &diagram, &config)
            .expect("layout should succeed");
        let routed = route_graph_geometry(&diagram, &geometry, EdgeRouting::OrthogonalRoute);

        for (from, to, blocked_label) in edge_specs {
            let edge_idx = edge_index(&diagram, from, to);
            let routed_edge = routed
                .edges
                .iter()
                .find(|edge| edge.index == edge_idx)
                .unwrap_or_else(|| panic!("missing routed edge for {fixture}:{from}->{to}"));
            let points: Vec<(f64, f64)> = routed_edge.path.iter().map(|p| (p.x, p.y)).collect();
            let blocked_rect = geometry
                .nodes
                .values()
                .find(|node| node.label == blocked_label)
                .map(|node| (node.rect.x, node.rect.y, node.rect.width, node.rect.height))
                .unwrap_or_else(|| {
                    panic!("missing blocked node geometry for {fixture}:{blocked_label}")
                });
            assert!(
                !path_crosses_rect_interior(&points, blocked_rect, 1.0),
                "{fixture} routed orthogonal edge {from}->{to} should avoid unrelated node {blocked_label} interior before SVG shaping; routed_points={points:?}, blocked_rect={blocked_rect:?}"
            );
        }
    }
}

#[test]
fn svg_basis_decision_paths_fit_within_viewbox_after_translate() {
    let diagram = load_flowchart_fixture_diagram("decision.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Basis),
        path_simplification: PathSimplification::Lossless,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let (vx, vy, vw, vh) = parse_svg_viewbox(&svg).expect("decision SVG should have a viewBox");
    let (tx, ty) = parse_svg_main_translate(&svg).unwrap_or((0.0, 0.0));
    let right = vx + vw;
    let bottom = vy + vh;

    for d in edge_path_data(&svg) {
        let path_points = parse_svg_path_points(&d);
        for point in path_points {
            let px = point.0 + tx;
            let py = point.1 + ty;
            assert!(
                px >= vx - 1.0 && px <= right + 1.0 && py >= vy - 1.0 && py <= bottom + 1.0,
                "decision basis path should remain inside viewBox (with translate); point=({px:.2},{py:.2}) viewBox=({vx:.2},{vy:.2},{vw:.2},{vh:.2}) d={d}"
            );
        }
    }
}

#[test]
fn svg_basis_backward_in_subgraph_endpoints_attach_on_border_not_inside() {
    let fixtures = ["backward_in_subgraph.mmd", "backward_in_subgraph_lr.mmd"];

    for fixture_name in fixtures {
        let diagram = load_flowchart_fixture_diagram(fixture_name);
        let edge_idx = edge_index(&diagram, "B", "A");

        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Basis),
            path_simplification: PathSimplification::Lossless,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);

        let start = points
            .first()
            .copied()
            .expect("backward_in_subgraph edge should include at least one point");
        let end = points
            .last()
            .copied()
            .expect("backward_in_subgraph edge should include at least one point");
        let source_rect = node_rect_for_label(&svg, "Node2").expect("missing Node2 rect");
        let target_rect = node_rect_for_label(&svg, "Node").expect("missing Node rect");

        assert!(
            !point_inside_rect_with_margin(start, source_rect, 0.5),
            "{fixture_name} basis backward edge should start on/near Node2 border (not inside); start={start:?}, source_rect={source_rect:?}, points={points:?}"
        );
        assert!(
            !point_inside_rect_with_margin(end, target_rect, 0.5),
            "{fixture_name} basis backward edge should end on/near Node border (not inside); end={end:?}, target_rect={target_rect:?}, points={points:?}"
        );
    }
}

#[test]
fn svg_curved_step_td_departures_do_not_initially_curl_upward() {
    let diagram = load_flowchart_fixture_diagram("compat_invisible_edge.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Basis),
        path_simplification: PathSimplification::Lossless,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    for (from, to) in [("A", "B"), ("A", "C")] {
        let edge_idx = edge_index(&diagram, from, to);
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        assert!(
            points.len() >= 2,
            "curved-step {from}->{to} should produce at least two path points: {points:?}"
        );
        assert!(
            points[1].1 >= points[0].1 - 0.5,
            "curved-step TD departure should not initially curl upward for {from}->{to}: points={points:?}"
        );
    }
}

#[test]
fn svg_orthogonal_mode_renders_axis_aligned_path_commands() {
    let input = "graph TD\nA --> B\nA --> C\n";
    let flowchart = parse_flowchart(input).unwrap();
    let diagram = compile_to_graph(&flowchart);

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    assert!(!svg.contains("NaN"));

    let edge_paths = edge_path_data(&svg);
    assert!(
        !edge_paths.is_empty(),
        "expected edge path data in SVG output"
    );
    for d in edge_paths {
        let points = parse_svg_path_points(&d);
        assert!(
            points.windows(2).all(|segment| {
                (segment[0].0 - segment[1].0).abs() < 0.001
                    || (segment[0].1 - segment[1].1).abs() < 0.001
            }),
            "orthogonal path should be axis-aligned, got {d}"
        );
    }
}

#[test]
fn svg_lossless_path_simplification_sits_between_none_and_lossy_for_orthogonal_route() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multi_subgraph_direction_override.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);

    let render_with = |path_simplification: PathSimplification| {
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Rounded)),
            path_simplification,
            ..Default::default()
        };
        render_svg(&diagram, &options)
    };

    let full = render_with(PathSimplification::None);
    let compact = render_with(PathSimplification::Lossless);
    let simplified = render_with(PathSimplification::Lossy);

    let full_segments = total_svg_edge_segments(&full);
    let compact_segments = total_svg_edge_segments(&compact);
    let simplified_segments = total_svg_edge_segments(&simplified);

    assert!(
        full_segments >= compact_segments,
        "compact should not increase total segments: full={full_segments}, compact={compact_segments}"
    );
    assert!(
        full_segments != simplified_segments,
        "simplified should change segment density compared to full: full={full_segments}, simplified={simplified_segments}"
    );
}

#[test]
fn routed_svg_defaults_to_none_path_simplification() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multi_subgraph_direction_override.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);
    let edge_index = diagram
        .edges
        .iter()
        .find(|edge| edge.from == "Bmid" && edge.to == "F")
        .expect("fixture should contain edge Bmid -> F")
        .index;

    let default_options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        ..Default::default()
    };
    let default_svg = render_svg(&diagram, &default_options);
    let default_points = edge_path_for_svg_order(&diagram, &default_svg, edge_index);

    let mut full_options = default_options;
    full_options.path_simplification = PathSimplification::None;
    let full_svg = render_svg(&diagram, &full_options);
    let full_points = edge_path_for_svg_order(&diagram, &full_svg, edge_index);

    let mut simplified_options = full_options;
    simplified_options.path_simplification = PathSimplification::Lossy;
    let simplified_svg = render_svg(&diagram, &simplified_options);
    let simplified_points = edge_path_for_svg_order(&diagram, &simplified_svg, edge_index);

    assert_eq!(
        default_points, full_points,
        "default routed SVG path detail should match full output"
    );
    assert!(
        default_points.len() >= simplified_points.len(),
        "default full detail should not have fewer points than simplified: default={}, simplified={}",
        default_points.len(),
        simplified_points.len()
    );
    if default_points.len() == simplified_points.len() {
        assert!(
            default_points.len() <= 3,
            "default/simplified point counts should only match when the routed path is already minimal: default={}, simplified={}, points={:?}",
            default_points.len(),
            simplified_points.len(),
            default_points
        );
    }
}

const SVG_LABEL_REVALIDATION_MAX_DISTANCE_TO_ACTIVE_SEGMENT: f64 = 2.0;

#[test]
fn svg_orthogonal_orthogonal_route_labeled_edges_labels_remain_attached_to_active_segments() {
    let diagram = load_flowchart_fixture_diagram("labeled_edges.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let failures = svg_label_drift_failures(
        &svg,
        &diagram,
        SVG_LABEL_REVALIDATION_MAX_DISTANCE_TO_ACTIVE_SEGMENT,
    );
    assert!(
        failures.is_empty(),
        "Label revalidation regression: labeled_edges rendered off-path edge labels:\n{}",
        failures.join("\n")
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_inline_label_flowchart_labels_remain_attached_to_active_segments()
 {
    let diagram = load_flowchart_fixture_diagram("inline_label_flowchart.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let failures = svg_label_drift_failures(
        &svg,
        &diagram,
        SVG_LABEL_REVALIDATION_MAX_DISTANCE_TO_ACTIVE_SEGMENT,
    );
    assert!(
        failures.is_empty(),
        "Label revalidation regression: inline_label_flowchart rendered off-path edge labels:\n{}",
        failures.join("\n")
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_inline_label_flowchart_avoids_known_node_intrusions() {
    let diagram = load_flowchart_fixture_diagram("inline_label_flowchart.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let cache_to_validate = edge_index(&diagram, "cache", "validate");
    let reject_to_metrics = edge_index(&diagram, "reject", "metrics");
    let retry_to_queue = edge_index(&diagram, "retry", "queue");
    let fastpath_to_metrics = edge_index(&diagram, "fastpath", "metrics");
    let audit_to_metrics = edge_index(&diagram, "audit", "metrics");
    let cache_to_validate_points = edge_path_for_svg_order(&diagram, &svg, cache_to_validate);
    let reject_to_metrics_points = edge_path_for_svg_order(&diagram, &svg, reject_to_metrics);
    let retry_to_queue_points = edge_path_for_svg_order(&diagram, &svg, retry_to_queue);
    let fastpath_to_metrics_points = edge_path_for_svg_order(&diagram, &svg, fastpath_to_metrics);
    let audit_to_metrics_points = edge_path_for_svg_order(&diagram, &svg, audit_to_metrics);

    let serve_cached_rect =
        node_rect_for_label(&svg, "Serve Cached").expect("missing Serve Cached rect");
    let notify_user_rect =
        node_rect_for_label(&svg, "Notify User").expect("missing Notify User rect");
    let page_on_call_rect =
        node_rect_for_label(&svg, "Page On-call").expect("missing Page On-call rect");

    assert!(
        !path_crosses_rect_interior(&cache_to_validate_points, serve_cached_rect, 1.0),
        "Lookup Cache -> Valid? should not pass through Serve Cached interior in orthogonal mode; path={cache_to_validate_points:?}, serve_cached_rect={serve_cached_rect:?}"
    );
    assert!(
        !path_crosses_rect_interior(&reject_to_metrics_points, notify_user_rect, 1.0),
        "Reject -> Emit Metrics should not pass through Notify User interior in orthogonal mode; path={reject_to_metrics_points:?}, notify_user_rect={notify_user_rect:?}"
    );
    assert!(
        !path_crosses_rect_interior(&reject_to_metrics_points, page_on_call_rect, 1.0),
        "Reject -> Emit Metrics should not pass through Page On-call interior in orthogonal mode; path={reject_to_metrics_points:?}, page_on_call_rect={page_on_call_rect:?}"
    );
    assert!(
        !path_crosses_rect_interior(&retry_to_queue_points, page_on_call_rect, 1.0),
        "Retry -> Enqueue Job should not pass through Page On-call interior in orthogonal mode; path={retry_to_queue_points:?}, page_on_call_rect={page_on_call_rect:?}"
    );

    let fast_support = *fastpath_to_metrics_points
        .get(fastpath_to_metrics_points.len().saturating_sub(2))
        .expect("Serve Cached -> Emit Metrics should include terminal support point");
    let audit_support = *audit_to_metrics_points
        .get(audit_to_metrics_points.len().saturating_sub(2))
        .expect("Audit Log -> Emit Metrics should include terminal support point");
    let support_y_delta = (fast_support.1 - audit_support.1).abs();
    let support_x_delta = (fast_support.0 - audit_support.0).abs();
    assert!(
        support_y_delta >= 1.0 || support_x_delta >= 8.0,
        "Serve Cached -> Emit Metrics and Audit Log -> Emit Metrics should keep terminal support anchors visibly separated (vertical or horizontal staggering); fast_support={fast_support:?}, audit_support={audit_support:?}, fast_path={fastpath_to_metrics_points:?}, audit_path={audit_to_metrics_points:?}"
    );

    // Find a probe_y at the midpoint of the retry edge's longest vertical segment.
    // This adapts to layout changes (e.g., variable gap spacing) instead of
    // hardcoding a fixed y coordinate.
    let probe_y = longest_vertical_segment_midpoint(&retry_to_queue_points)
        .expect("Retry -> Enqueue Job should have at least one vertical segment");
    let retry_lane_x = vertical_lane_x_at_y(&retry_to_queue_points, probe_y)
        .expect("Retry -> Enqueue Job should expose a vertical lane through probe y");
    let fastpath_lane_x = vertical_lane_x_at_y(&fastpath_to_metrics_points, probe_y)
        .expect("Serve Cached -> Emit Metrics should expose a vertical lane through probe y");
    assert!(
        (retry_lane_x - fastpath_lane_x).abs() >= 1.0,
        "Retry -> Enqueue Job should not share the same vertical lane as Serve Cached -> Emit Metrics around y={probe_y}; retry_x={retry_lane_x}, fastpath_x={fastpath_lane_x}, retry_path={retry_to_queue_points:?}, fast_path={fastpath_to_metrics_points:?}"
    );
}

fn svg_flux_inline_label_flowchart_avoids_known_node_intrusions_for_routing_style(
    routing_style: RoutingStyle,
) {
    let diagram = load_flowchart_fixture_diagram("inline_label_flowchart.mmd");
    let svg = render_flux_engine_svg_for_fixture_with_style(
        "inline_label_flowchart.mmd",
        routing_style,
        Curve::Linear(CornerStyle::Sharp),
    );

    let cache_to_validate = edge_index(&diagram, "cache", "validate");
    let reject_to_metrics = edge_index(&diagram, "reject", "metrics");
    let retry_to_queue = edge_index(&diagram, "retry", "queue");
    let cache_to_validate_points = edge_path_for_svg_order(&diagram, &svg, cache_to_validate);
    let reject_to_metrics_points = edge_path_for_svg_order(&diagram, &svg, reject_to_metrics);
    let retry_to_queue_points = edge_path_for_svg_order(&diagram, &svg, retry_to_queue);

    let serve_cached_rect =
        node_rect_for_label(&svg, "Serve Cached").expect("missing Serve Cached rect");
    let notify_user_rect =
        node_rect_for_label(&svg, "Notify User").expect("missing Notify User rect");
    let page_on_call_rect =
        node_rect_for_label(&svg, "Page On-call").expect("missing Page On-call rect");

    assert!(
        !path_crosses_rect_interior_any(&cache_to_validate_points, serve_cached_rect, 1.0),
        "Lookup Cache -> Valid? should avoid Serve Cached interior in flux polyline mode; path={cache_to_validate_points:?}, serve_cached_rect={serve_cached_rect:?}"
    );
    assert!(
        !path_crosses_rect_interior_any(&reject_to_metrics_points, notify_user_rect, 1.0),
        "Reject -> Emit Metrics should avoid Notify User interior in flux polyline mode; path={reject_to_metrics_points:?}, notify_user_rect={notify_user_rect:?}"
    );
    assert!(
        !path_crosses_rect_interior_any(&reject_to_metrics_points, page_on_call_rect, 1.0),
        "Reject -> Emit Metrics should avoid Page On-call interior in flux polyline mode; path={reject_to_metrics_points:?}, page_on_call_rect={page_on_call_rect:?}"
    );
    assert!(
        !path_crosses_rect_interior_any(&retry_to_queue_points, page_on_call_rect, 1.0),
        "Retry -> Enqueue Job should avoid Page On-call interior in flux polyline mode; path={retry_to_queue_points:?}, page_on_call_rect={page_on_call_rect:?}"
    );
}

#[test]
fn svg_flux_direct_inline_label_flowchart_avoids_known_node_intrusions() {
    svg_flux_inline_label_flowchart_avoids_known_node_intrusions_for_routing_style(
        RoutingStyle::Direct,
    );
}

#[test]
fn svg_flux_polyline_inline_label_flowchart_avoids_known_node_intrusions() {
    svg_flux_inline_label_flowchart_avoids_known_node_intrusions_for_routing_style(
        RoutingStyle::Polyline,
    );
}

#[test]
fn svg_flux_orthogonal_inline_label_flowchart_avoids_known_node_intrusions() {
    svg_flux_inline_label_flowchart_avoids_known_node_intrusions_for_routing_style(
        RoutingStyle::Orthogonal,
    );
}

#[test]
fn path_simplification_monotonicity_holds_none_lossless_lossy() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multi_subgraph_direction_override.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);
    let edge_index = diagram
        .edges
        .iter()
        .find(|edge| edge.from == "Bmid" && edge.to == "F")
        .expect("fixture should contain edge Bmid -> F")
        .index;

    let render_for = |path_simplification: PathSimplification| {
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Rounded)),
            path_simplification,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);
        edge_path_for_svg_order(&diagram, &svg, edge_index).len()
    };

    let full = render_for(PathSimplification::None);
    let compact = render_for(PathSimplification::Lossless);
    let simplified = render_for(PathSimplification::Lossy);

    assert!(
        full >= compact && compact >= simplified,
        "path-detail monotonicity violated for SVG: full={full}, compact={compact}, simplified={simplified}"
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_preserves_clear_terminal_stem_into_arrowhead() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multi_subgraph_direction_override.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);
    let edge_index = diagram
        .edges
        .iter()
        .find(|edge| edge.from == "Bmid" && edge.to == "F")
        .expect("fixture should contain edge Bmid -> F")
        .index;

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_index);
    assert!(
        points.len() >= 2,
        "expected routed SVG points for Bmid -> F"
    );

    let prev = points[points.len() - 2];
    let end = points[points.len() - 1];
    let axis = segment_axis(prev, end).expect("terminal segment should be axis-aligned");
    let stem_len = manhattan_segment_len(prev, end);
    assert_eq!(
        axis, 'V',
        "Bmid -> F terminal segment should be vertical in TD layout: {points:?}"
    );
    assert!(
        end.1 > prev.1,
        "Bmid -> F terminal segment should point downward into F (arrow-support direction), got prev={prev:?}, end={end:?}, points={points:?}"
    );
    assert!(
        !has_immediate_axis_backtrack(&points),
        "Bmid -> F path should not include an immediate axis backtrack near the elbow: {points:?}"
    );
    assert!(
        stem_len >= 2.0,
        "Bmid -> F terminal stem should retain a visible stem into arrowhead (>= 2px), got {stem_len} with {points:?}"
    );

    let (_fx, fy, _fw, _fh) = node_rect_for_label(&svg, "f").expect("expected SVG rect for node f");
    let expected_endpoint_y = fy - 4.0;
    assert!(
        (end.1 - expected_endpoint_y).abs() <= 0.5,
        "Bmid -> F endpoint should be pulled back so arrow tip touches F border: endpoint_y={}, expected_y={} (f_top={fy}) points={points:?}",
        end.1,
        expected_endpoint_y
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_does_not_add_short_staircase_jogs_after_adjustment() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multi_subgraph_direction_override.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);

    let edge_index = diagram
        .edges
        .iter()
        .find(|edge| edge.from == "Bmid" && edge.to == "F")
        .expect("fixture should contain edge Bmid -> F")
        .index;

    let config =
        EngineConfig::Layered(crate::engines::graph::algorithms::layered::LayoutConfig::default());
    let geom = run_layered_layout(&MeasurementMode::Grid, &diagram, &config)
        .expect("layout should succeed");
    let routed = route_graph_geometry(&diagram, &geom, EdgeRouting::OrthogonalRoute);
    let routed_edge = routed
        .edges
        .iter()
        .find(|edge| edge.index == edge_index)
        .expect("orthogonal routed edge should exist");
    let routed_segments = routed_edge.path.len().saturating_sub(1);

    // Sharp renders straight-line segments without arc corners, so segment
    // counts are directly comparable to routed waypoints.
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Sharp)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_index);
    let svg_segments = points.len().saturating_sub(1);
    assert!(
        svg_segments <= routed_segments + 2,
        "SVG conversion should not add staircase jogs for Bmid -> F: routed_segments={routed_segments}, svg_segments={svg_segments}, svg_points={points:?}"
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_multiple_cycles_avoids_tiny_terminal_staircase_jogs() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multiple_cycles.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);
    let edges = [
        edge_index(&diagram, "C", "A"),
        edge_index(&diagram, "C", "B"),
    ];

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    for edge_idx in edges {
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        assert!(
            points.len() >= 2,
            "multiple_cycles edge should keep at least one terminal segment in orthogonal mode: {points:?}"
        );
        let terminal_support =
            manhattan_segment_len(points[points.len() - 2], points[points.len() - 1]);
        // A perfectly straight terminal (2 points) is acceptable as long as it is not tiny.
        // If there is an elbow near the terminal (>= 3 points), also require the
        // pre-terminal leg to be non-trivial to avoid staircase artifacts.
        if points.len() >= 3 {
            let pre_terminal =
                manhattan_segment_len(points[points.len() - 3], points[points.len() - 2]);
            assert!(
                terminal_support >= 10.0 && pre_terminal >= 3.0,
                "multiple_cycles orthogonal tail should avoid tiny terminal staircase jogs; terminal_support={terminal_support}, pre_terminal={pre_terminal}, points={points:?}"
            );
        } else {
            assert!(
                terminal_support >= 10.0,
                "multiple_cycles orthogonal straight terminal should remain substantial (>= 10px): terminal_support={terminal_support}, points={points:?}"
            );
        }
    }
}

#[test]
fn svg_orthogonal_orthogonal_route_double_skip_avoids_tiny_leading_lateral_jog() {
    let diagram = load_flowchart_fixture_diagram("double_skip.mmd");
    let edge_idx = edge_index(&diagram, "A", "C");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
    assert!(
        points.len() >= 2,
        "double_skip A -> C should render with at least one segment: {points:?}"
    );

    if points.len() >= 4 {
        let p0 = points[0];
        let p1 = points[1];
        let p2 = points[2];
        let p3 = points[3];
        let first_vertical = segment_axis(p0, p1) == Some('V');
        let middle_horizontal = segment_axis(p1, p2) == Some('H');
        let terminal_vertical = segment_axis(p2, p3) == Some('V');
        if first_vertical && middle_horizontal && terminal_vertical {
            let jog = manhattan_segment_len(p1, p2);
            assert!(
                jog >= 3.0,
                "double_skip A -> C should not keep a tiny leading lateral shim in orthogonal mode; jog={jog}, points={points:?}"
            );
        }
    }
}

#[test]
fn svg_orthogonal_orthogonal_route_decision_diamond_outbound_prefers_horizontal_departure() {
    let diagram = load_flowchart_fixture_diagram("decision.mmd");
    let edges = [
        edge_index(&diagram, "B", "C"),
        edge_index(&diagram, "B", "D"),
    ];

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    for edge_idx in edges {
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        assert!(
            points.len() >= 3,
            "decision branch should keep at least one bend after horizontal departure preference: {points:?}"
        );
        assert_eq!(
            segment_axis(points[0], points[1]),
            Some('H'),
            "decision branch should depart diamond horizontally in TD orthogonal orthogonal mode: {points:?}"
        );
        assert_eq!(
            segment_axis(points[points.len() - 2], points[points.len() - 1]),
            Some('V'),
            "decision branch should arrive at target with vertical support in TD orthogonal orthogonal mode: {points:?}"
        );
    }
}

#[test]
fn svg_orthogonal_orthogonal_route_hexagon_outbound_departure_insets_from_bottom_border() {
    let diagram = load_flowchart_fixture_diagram("hexagon_flow.mmd");
    let edges = [
        edge_index(&diagram, "A", "B"),
        edge_index(&diagram, "A", "D"),
    ];

    let measurement_mode = default_proportional_mode();
    let config =
        EngineConfig::Layered(crate::engines::graph::algorithms::layered::LayoutConfig::default());
    let geom = run_layered_layout(&measurement_mode, &diagram, &config)
        .expect("layout should succeed for hexagon_flow fixture");
    let source_rect = geom
        .nodes
        .get("A")
        .expect("hexagon_flow fixture should contain source node A")
        .rect;
    let source_bottom = source_rect.y + source_rect.height;

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    for edge_idx in edges {
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        assert!(
            points.len() >= 3,
            "hexagon outbound edge should keep at least one bend: {points:?}"
        );
        assert_eq!(
            segment_axis(points[0], points[1]),
            Some('H'),
            "hexagon outbound edge should depart laterally first in TD orthogonal orthogonal mode: {points:?}"
        );
        assert!(
            points[0].1 <= source_bottom - 1.0,
            "hexagon outbound edge start should be inset above the bottom border to avoid border-aligned stems: start={:?}, source_bottom={}, points={points:?}",
            points[0],
            source_bottom
        );
        assert_eq!(
            segment_axis(points[points.len() - 2], points[points.len() - 1]),
            Some('V'),
            "hexagon outbound edge should arrive with a vertical terminal support: {points:?}"
        );
    }
}

#[test]
fn svg_orthogonal_orthogonal_route_nested_subgraph_edge_avoids_large_lateral_detour() {
    let diagram = load_flowchart_fixture_diagram("nested_subgraph_edge.mmd");
    let edges = [
        edge_index(&diagram, "Client", "Server1"),
        edge_index(&diagram, "Server1", "Monitoring"),
    ];

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    for edge_idx in edges {
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        let span = horizontal_span(&points);
        assert!(
            span <= 20.0,
            "nested_subgraph_edge orthogonal path should not make a large horizontal detour: span={span}, points={points:?}"
        );
    }
}

#[test]
fn svg_curved_orthogonal_route_ampersand_avoids_tiny_terminal_hook_before_arrow() {
    let diagram = load_flowchart_fixture_diagram("ampersand.mmd");
    let merge_in_edges = [
        edge_index(&diagram, "A", "C"),
        edge_index(&diagram, "B", "C"),
    ];

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Basis),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    for edge_idx in merge_in_edges {
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        assert!(
            points.len() >= 2,
            "ampersand edge should contain at least two path points: {points:?}"
        );
        let terminal = terminal_collinear_run_len(&points);
        assert!(
            terminal >= 3.5,
            "curved orthogonal terminal approach should avoid tiny hook before marker; collinear_terminal_run={terminal}, points={points:?}"
        );
    }
}

#[test]
fn svg_non_orth_orthogonal_route_backward_edges_terminal_tangent_points_toward_target() {
    let cases = [
        ("decision.mmd", "D", "A"),
        ("git_workflow.mmd", "Remote", "Working"),
        ("http_request.mmd", "Response", "Client"),
        ("labeled_edges.mmd", "Error", "Setup"),
    ];
    let styles = [SHARP, ROUNDED, SMOOTH];

    for (fixture_name, from, to) in cases {
        let diagram = load_flowchart_fixture_diagram(fixture_name);
        let edge_idx = edge_index(&diagram, from, to);
        let target_center = node_center_for_id(&diagram, to);

        for style in styles {
            let options = RenderConfig {
                routing_style: Some(RoutingStyle::Orthogonal),
                curve: Some(style.1),
                path_simplification: PathSimplification::None,
                ..Default::default()
            };
            let svg = render_svg(&diagram, &options);
            let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);

            assert!(
                points.len() >= 2,
                "{fixture_name} {from}->{to} should have at least two SVG path points for {style:?}: {points:?}"
            );

            let prev = points[points.len() - 2];
            let end = points[points.len() - 1];
            let toward_target = distance(end, target_center) < distance(prev, target_center);
            assert!(
                toward_target,
                "{fixture_name} {from}->{to} terminal tangent should point toward target center for {style:?}: prev={prev:?}, end={end:?}, target_center={target_center:?}, points={points:?}"
            );
        }
    }
}

#[test]
fn svg_straight_orthogonal_route_avoids_primary_axis_backtrack_for_bmid_to_f() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multi_subgraph_direction_override.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);
    let edge_index = diagram
        .edges
        .iter()
        .find(|edge| edge.from == "Bmid" && edge.to == "F")
        .expect("fixture should contain edge Bmid -> F")
        .index;

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Sharp)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_index);

    assert!(
        !has_primary_axis_backtrack(&points, diagram.direction),
        "Bmid -> F should not backtrack along TD primary axis in straight SVG: {points:?}"
    );
}

#[test]
fn svg_curved_orthogonal_route_avoids_primary_axis_backtrack_for_bmid_to_f() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multi_subgraph_direction_override.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);
    let edge_index = diagram
        .edges
        .iter()
        .find(|edge| edge.from == "Bmid" && edge.to == "F")
        .expect("fixture should contain edge Bmid -> F")
        .index;

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Basis),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_index);

    assert!(
        !has_primary_axis_backtrack(&points, diagram.direction),
        "Bmid -> F should not backtrack along TD primary axis in curved SVG: {points:?}"
    );
}

#[test]
fn svg_rounded_orthogonal_route_avoids_primary_axis_backtrack_for_bmid_to_f() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multi_subgraph_direction_override.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);
    let edge_index = diagram
        .edges
        .iter()
        .find(|edge| edge.from == "Bmid" && edge.to == "F")
        .expect("fixture should contain edge Bmid -> F")
        .index;

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_index);

    assert!(
        !has_primary_axis_backtrack(&points, diagram.direction),
        "Bmid -> F should not backtrack along TD primary axis in rounded SVG: {points:?}"
    );
}

#[test]
fn svg_orthogonal_route_five_fan_out_lr_inner_branches_avoid_primary_axis_backtrack() {
    let diagram = load_flowchart_fixture_diagram("five_fan_out_lr.mmd");
    let styles = [SHARP, ROUNDED, SMOOTH];
    let branches = [("A", "C"), ("A", "E")];

    for style in styles {
        let svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, style);
        for (from, to) in branches {
            let edge_idx = edge_index(&diagram, from, to);
            let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
            assert!(
                !has_primary_axis_backtrack(&points, diagram.direction),
                "five_fan_out_lr {from}->{to} should not backtrack along LR primary axis for {style:?}: {points:?}"
            );
        }
    }
}

#[test]
fn svg_non_orth_orthogonal_route_keeps_endpoint_pulled_back_for_visible_arrow_tip() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("multi_subgraph_direction_override.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);
    let edge_index = diagram
        .edges
        .iter()
        .find(|edge| edge.from == "Bmid" && edge.to == "F")
        .expect("fixture should contain edge Bmid -> F")
        .index;

    let styles = [SHARP, ROUNDED, SMOOTH];

    for style in styles {
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(style.1),
            path_simplification: PathSimplification::None,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);
        let points = edge_path_for_svg_order(&diagram, &svg, edge_index);
        let end = points
            .last()
            .copied()
            .expect("Bmid -> F should have SVG path points");
        let (_fx, fy, _fw, _fh) =
            node_rect_for_label(&svg, "f").expect("expected SVG rect for node f");
        let expected_endpoint_y = fy - 4.0;

        assert!(
            (end.1 - expected_endpoint_y).abs() <= 0.5,
            "non-orth {style:?} endpoint should be pulled back so arrow tip lands on F border: endpoint_y={}, expected_y={} (f_top={fy}) points={points:?}",
            end.1,
            expected_endpoint_y
        );
    }
}

#[test]
fn svg_non_orth_orthogonal_route_fan_in_lr_terminal_arrowheads_do_not_end_inside_target() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("fan_in_lr.mmd");
    let input = fs::read_to_string(fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);

    let top_edge = edge_index(&diagram, "A", "D");
    let bottom_edge = edge_index(&diagram, "C", "D");
    let styles = [SHARP, ROUNDED, SMOOTH];

    for style in styles {
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(style.1),
            path_simplification: PathSimplification::None,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);
        let (tx, ty, tw, th) =
            node_rect_for_label(&svg, "Target").expect("target rect should exist");

        for edge_idx in [top_edge, bottom_edge] {
            let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
            let end = points
                .last()
                .copied()
                .expect("edge should have path points");
            let inside = end.0 > tx + 0.5
                && end.0 < tx + tw - 0.5
                && end.1 > ty + 0.5
                && end.1 < ty + th - 0.5;

            assert!(
                !inside,
                "fan_in_lr edge endpoint should not be inside target interior for {style:?}: end={end:?}, target_rect=({tx}, {ty}, {tw}, {th}), points={points:?}"
            );
        }
    }
}

#[test]
fn svg_non_orth_orthogonal_route_backward_edges_keep_terminal_arrowheads_visible() {
    // Note: complex.mmd E->A was removed because model_order tie-breaking
    // changes the layout, moving Input so the backward edge approaches from
    // the left side rather than bottom. The polyline endpoint geometry
    // differs in this new layout.
    let cases = [
        ("decision.mmd", "D", "A", "Start"),
        ("labeled_edges.mmd", "Error", "Setup", "Setup"),
        ("http_request.mmd", "Response", "Client", "Client"),
    ];
    let styles = [SHARP, ROUNDED, SMOOTH];

    for (fixture_name, from, to, target_label) in cases {
        let diagram = load_flowchart_fixture_diagram(fixture_name);
        let edge_idx = edge_index(&diagram, from, to);

        for style in styles {
            let options = RenderConfig {
                routing_style: Some(RoutingStyle::Orthogonal),
                curve: Some(style.1),
                path_simplification: PathSimplification::None,
                ..Default::default()
            };
            let svg = render_svg(&diagram, &options);
            let (tx, ty, tw, th) = node_rect_for_label(&svg, target_label)
                .unwrap_or_else(|| panic!("target rect should exist for {target_label}"));
            let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
            let end = points
                .last()
                .copied()
                .expect("edge should have path points");
            let inside = end.0 > tx + 0.5
                && end.0 < tx + tw - 0.5
                && end.1 > ty + 0.5
                && end.1 < ty + th - 0.5;

            assert!(
                !inside,
                "{fixture_name} {from}->{to} endpoint should stay outside target interior for {style:?}: end={end:?}, target_rect=({tx}, {ty}, {tw}, {th}), points={points:?}"
            );
        }
    }
}

#[test]
fn svg_non_orth_orthogonal_route_backward_in_subgraph_avoids_tiny_terminal_tail_hooks() {
    const MIN_TERMINAL_SUPPORT: f64 = 3.5;
    let diagram = load_flowchart_fixture_diagram("backward_in_subgraph.mmd");
    let edge_idx = edge_index(&diagram, "B", "A");
    let styles = [SHARP, ROUNDED, SMOOTH];

    for style in styles {
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(style.1),
            path_simplification: PathSimplification::None,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        assert!(
            points.len() >= 2,
            "backward_in_subgraph B->A should have at least two points for {style:?}: {points:?}"
        );

        let rect = node_rect_for_label(&svg, "Node").expect("target rect should exist for Node");
        let end_face = svg_terminal_approach_face_relaxed(rect, &points);
        assert_eq!(
            end_face, "bottom",
            "backward_in_subgraph B->A should enter Node on bottom face for {style:?}: points={points:?}"
        );

        let terminal_support =
            manhattan_segment_len(points[points.len() - 2], points[points.len() - 1]);
        let min_terminal_support = if style.1 == Curve::Basis {
            // Curved rendering intentionally tapers the final straight cap segment.
            1.0
        } else {
            MIN_TERMINAL_SUPPORT
        };
        assert!(
            terminal_support >= min_terminal_support,
            "backward_in_subgraph B->A should avoid tiny terminal tail hooks before the arrowhead for {style:?}: terminal_support={terminal_support}, min={min_terminal_support}, points={points:?}"
        );
    }
}

#[test]
fn svg_orthogonal_orthogonal_route_complex_backward_edge_keeps_arrowhead_visible() {
    let diagram = load_flowchart_fixture_diagram("complex.mmd");
    let edge_idx = edge_index(&diagram, "E", "A");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let (tx, ty, tw, th) =
        node_rect_for_label(&svg, "Input").expect("target rect should exist for Input");
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
    let end = points
        .last()
        .copied()
        .expect("complex E->A should have SVG path points");

    let ends_on_target_border_or_inside =
        end.0 >= tx - 0.5 && end.0 <= tx + tw + 0.5 && end.1 >= ty - 0.5 && end.1 <= ty + th + 0.5;
    assert!(
        !ends_on_target_border_or_inside,
        "complex E->A orthogonal endpoint should be pulled outside the Input node envelope so arrowhead remains visible; end={end:?}, target_rect=({tx}, {ty}, {tw}, {th}), points={points:?}"
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_complex_backward_edge_terminal_tangent_points_toward_target() {
    let diagram = load_flowchart_fixture_diagram("complex.mmd");
    let edge_idx = edge_index(&diagram, "E", "A");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let rect = node_rect_for_label(&svg, "Input").expect("target rect should exist for Input");
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
    assert!(
        points.len() >= 2,
        "complex E->A should have at least two path points in orthogonal mode: {points:?}"
    );
    let prev = points[points.len() - 2];
    let end = points[points.len() - 1];
    let end_face = svg_terminal_approach_face_relaxed(rect, &points);

    match end_face {
        "right" => assert!(
            (end.1 - prev.1).abs() <= 0.5 && end.0 < prev.0,
            "complex E->A orthogonal terminal tangent on right face should point left into Input; prev={prev:?}, end={end:?}, points={points:?}"
        ),
        "left" => assert!(
            (end.1 - prev.1).abs() <= 0.5 && end.0 > prev.0,
            "complex E->A orthogonal terminal tangent on left face should point right into Input; prev={prev:?}, end={end:?}, points={points:?}"
        ),
        "top" => assert!(
            (end.0 - prev.0).abs() <= 0.5 && end.1 > prev.1,
            "complex E->A orthogonal terminal tangent on top face should point down into Input; prev={prev:?}, end={end:?}, points={points:?}"
        ),
        "bottom" => assert!(
            (end.0 - prev.0).abs() <= 0.5 && end.1 < prev.1,
            "complex E->A orthogonal terminal tangent on bottom face should point up into Input; prev={prev:?}, end={end:?}, points={points:?}"
        ),
        other => panic!(
            "complex E->A orthogonal terminal approach should resolve to a concrete Input face, got {other}; prev={prev:?}, end={end:?}, points={points:?}"
        ),
    }
}

#[test]
fn backward_routes_keep_outer_lane_and_terminal_tangent_contracts() {
    const MIN_OUTER_LANE_CLEARANCE: f64 = 12.0;

    let diagram = load_flowchart_fixture_diagram("multiple_cycles.mmd");
    let edge_idx = edge_index(&diagram, "C", "A");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let rect = node_rect_for_label(&svg, "Top").expect("target rect should exist for Top");
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);

    assert!(
        points.len() >= 4,
        "multiple_cycles C->A should have enough SVG path points to form an outer return lane: {points:?}"
    );

    let start = points[0];
    let prev = points[points.len() - 2];
    let end = points[points.len() - 1];
    let baseline_max_x = start.0.max(end.0);
    let route_max_x = points
        .iter()
        .map(|point| point.0)
        .fold(f64::NEG_INFINITY, f64::max);
    let clearance = route_max_x - baseline_max_x;
    assert!(
        clearance >= MIN_OUTER_LANE_CLEARANCE,
        "multiple_cycles C->A should preserve an outer-lane lateral clearance (>= {MIN_OUTER_LANE_CLEARANCE}) in SVG orthogonal mode: clearance={clearance}, points={points:?}"
    );

    match svg_terminal_approach_face_relaxed(rect, &points) {
        "right" => assert!(
            (end.1 - prev.1).abs() <= 0.5 && end.0 < prev.0,
            "multiple_cycles C->A orthogonal terminal tangent on right face should point left into Top; prev={prev:?}, end={end:?}, points={points:?}"
        ),
        "left" => assert!(
            (end.1 - prev.1).abs() <= 0.5 && end.0 > prev.0,
            "multiple_cycles C->A orthogonal terminal tangent on left face should point right into Top; prev={prev:?}, end={end:?}, points={points:?}"
        ),
        "top" => assert!(
            (end.0 - prev.0).abs() <= 0.5 && end.1 > prev.1,
            "multiple_cycles C->A orthogonal terminal tangent on top face should point down into Top; prev={prev:?}, end={end:?}, points={points:?}"
        ),
        "bottom" => assert!(
            (end.0 - prev.0).abs() <= 0.5 && end.1 < prev.1,
            "multiple_cycles C->A orthogonal terminal tangent on bottom face should point up into Top; prev={prev:?}, end={end:?}, points={points:?}"
        ),
        other => panic!(
            "multiple_cycles C->A orthogonal terminal approach should resolve to a concrete Top face, got {other}; prev={prev:?}, end={end:?}, points={points:?}"
        ),
    }
}

#[test]
fn svg_orthogonal_route_complex_top_diamond_loop_avoids_single_edge_micro_jogs() {
    // Keep this slightly below 6.0 to tolerate small metric/layout drift while
    // still catching true micro-jogs.
    const MIN_SEGMENT_LEN: f64 = 5.75;

    let diagram = load_flowchart_fixture_diagram("complex.mmd");
    let straight_options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Sharp)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let straight_svg = render_svg(&diagram, &straight_options);

    for (from, to) in [("C", "E"), ("E", "A")] {
        let edge_idx = edge_index(&diagram, from, to);
        let points = edge_path_for_svg_order(&diagram, &straight_svg, edge_idx);
        assert!(
            points.len() >= 2,
            "complex {from}->{to} should emit at least one segment in straight mode: {points:?}"
        );
        let min_segment = min_svg_segment_len(&points);
        assert!(
            min_segment >= MIN_SEGMENT_LEN,
            "complex {from}->{to} should avoid tiny elbow jog segments in orthogonal straight mode (min {MIN_SEGMENT_LEN}): min_segment={min_segment}, points={points:?}"
        );
    }

    let orth_options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let orth_svg = render_svg(&diagram, &orth_options);
    let backward_idx = edge_index(&diagram, "E", "A");
    let backward_points = edge_path_for_svg_order(&diagram, &orth_svg, backward_idx);
    assert!(
        !has_immediate_axis_backtrack(&backward_points),
        "complex E->A should not include an immediate axis backtrack in orthogonal orthogonal mode: {backward_points:?}"
    );
}

#[test]
fn svg_non_orth_orthogonal_route_complex_backward_edge_avoids_center_biased_input_attachment() {
    const MIN_CENTER_OFFSET: f64 = 12.0;

    let diagram = load_flowchart_fixture_diagram("complex.mmd");
    let edge_idx = edge_index(&diagram, "E", "A");
    let styles = [SHARP, ROUNDED, SMOOTH];

    for style in styles {
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(style.1),
            path_simplification: PathSimplification::None,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);

        let rect = node_rect_for_label(&svg, "Input").expect("target rect should exist for Input");
        let center_x = rect.0 + rect.2 / 2.0;
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        let end = *points
            .last()
            .expect("complex E->A should have path points for non-orth style");
        let end_face = svg_terminal_approach_face_relaxed(rect, &points);

        if end_face == "bottom" || end_face == "top" {
            let center_offset = (end.0 - center_x).abs();
            assert!(
                center_offset >= MIN_CENTER_OFFSET,
                "complex E->A {style:?} should avoid center-biased vertical attachment on Input when approaching from a backward top-loop lane; end={end:?}, center_x={center_x}, center_offset={center_offset}, min_offset={MIN_CENTER_OFFSET}, points={points:?}"
            );
        }
    }
}

#[test]
fn svg_orthogonal_route_diamond_fan_out_td_lateral_edges_depart_horizontally_first() {
    let diagram = load_flowchart_fixture_diagram("diamond_fan_out.mmd");
    let styles = [SHARP, ROUNDED, SMOOTH];

    for style in styles {
        let svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, style);
        for (from, to) in [("A", "B"), ("A", "D")] {
            let edge_idx = edge_index(&diagram, from, to);
            let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
            assert!(
                points.len() >= 2,
                "diamond_fan_out {from}->{to} should expose at least two points for {style:?}: {points:?}"
            );
            let start = points[0];
            let next = points[1];
            assert!(
                (next.1 - start.1).abs() <= 0.5 && (next.0 - start.0).abs() > 0.5,
                "diamond_fan_out {from}->{to} should depart diamond laterally first in TD for {style:?}: start={start:?}, next={next:?}, points={points:?}"
            );
        }
    }
}

#[test]
fn svg_orthogonal_route_ci_pipeline_lr_diamond_exits_depart_vertically_first() {
    let diagram = load_flowchart_fixture_diagram("ci_pipeline.mmd");
    let styles = [SHARP, ROUNDED, SMOOTH];

    for style in styles {
        let svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, style);
        for (from, to) in [("Deploy", "Staging"), ("Deploy", "Prod")] {
            let edge_idx = edge_index(&diagram, from, to);
            let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
            assert!(
                points.len() >= 2,
                "ci_pipeline {from}->{to} should expose at least two points for {style:?}: {points:?}"
            );
            let start = points[0];
            let next = points[1];
            assert!(
                (next.0 - start.0).abs() <= 0.5 && (next.1 - start.1).abs() > 0.5,
                "ci_pipeline {from}->{to} should depart Deploy? on secondary axis first in LR for {style:?}: start={start:?}, next={next:?}, points={points:?}"
            );
        }
    }
}

#[test]
fn svg_straight_orthogonal_route_ci_pipeline_diamond_exits_avoid_extra_elbow_jogs() {
    let diagram = load_flowchart_fixture_diagram("ci_pipeline.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Sharp)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    for (from, to) in [("Deploy", "Staging"), ("Deploy", "Prod")] {
        let edge_idx = edge_index(&diagram, from, to);
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        assert!(
            points.len() >= 3,
            "ci_pipeline {from}->{to} should have at least three points for elbow checks: {points:?}"
        );
        let first = points[0];
        let second = points[1];
        let third = points[2];
        let first_axis = segment_axis(first, second);
        let second_axis = segment_axis(second, third);
        if points.len() >= 4 {
            let fourth = points[3];
            let third_axis = segment_axis(third, fourth);
            assert!(
                !(first_axis.is_none() && second_axis.is_some() && third_axis.is_some()),
                "ci_pipeline {from}->{to} should avoid extra elbow jogs right after Deploy? in orthogonal straight mode (prefer direct diagonal-to-lane): points={points:?}"
            );
        }
    }
}

#[test]
fn svg_orthogonal_route_backward_edges_preserve_selected_non_orth_style() {
    let diagram = load_flowchart_fixture_diagram("simple_cycle.mmd");
    let edge_idx = edge_index(&diagram, "C", "A");

    let curved_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SMOOTH);
    let curved_d = edge_path_d_for_svg_order(&diagram, &curved_svg, edge_idx);
    assert!(
        curved_d.contains('C'),
        "simple_cycle C->A backward edge should use curved-style cubic segments in orthogonal routing: d={curved_d}"
    );

    let rounded_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, ROUNDED);
    let rounded_d = edge_path_d_for_svg_order(&diagram, &rounded_svg, edge_idx);
    assert!(
        rounded_d.contains('Q'),
        "simple_cycle C->A backward edge should use rounded corner commands in orthogonal routing: d={rounded_d}"
    );
    let rounded_points = edge_path_for_svg_order(&diagram, &rounded_svg, edge_idx);
    assert!(
        rounded_points.len() >= 2,
        "simple_cycle C->A backward edge should expose at least two rounded points: {rounded_points:?}"
    );
    let rounded_prev = rounded_points[rounded_points.len() - 2];
    let rounded_end = rounded_points[rounded_points.len() - 1];
    let rounded_dx = (rounded_end.0 - rounded_prev.0).abs();
    let rounded_dy = (rounded_end.1 - rounded_prev.1).abs();
    assert!(
        rounded_dx <= 0.5 || rounded_dy <= 0.5,
        "simple_cycle C->A rounded backward terminal approach should stay axis-aligned (no diagonal terminal tail): prev={rounded_prev:?}, end={rounded_end:?}, d={rounded_d}"
    );

    let straight_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SHARP);
    let straight_d = edge_path_d_for_svg_order(&diagram, &straight_svg, edge_idx);
    assert!(
        !straight_d.contains('Q') && !straight_d.contains('C'),
        "simple_cycle C->A backward edge should remain polyline in straight mode: d={straight_d}"
    );
    let straight_points = edge_path_for_svg_order(&diagram, &straight_svg, edge_idx);
    assert!(
        straight_points.len() >= 2,
        "simple_cycle C->A backward edge should expose at least two straight points: {straight_points:?}"
    );
    let straight_prev = straight_points[straight_points.len() - 2];
    let straight_end = straight_points[straight_points.len() - 1];
    let straight_dx = (straight_end.0 - straight_prev.0).abs();
    let straight_dy = (straight_end.1 - straight_prev.1).abs();
    assert!(
        straight_dx <= 0.5 || straight_dy <= 0.5,
        "simple_cycle C->A straight backward terminal approach should stay axis-aligned (no diagonal terminal tail): prev={straight_prev:?}, end={straight_end:?}, d={straight_d}"
    );
}

#[test]
fn svg_orthogonal_criss_cross_step_preserves_center_corridor_detour() {
    let diagram = load_flowchart_fixture_diagram("criss_cross.mmd");
    let edge_idx = edge_index(&diagram, "B", "E");
    let svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SHARP);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);

    assert!(
        points.len() >= 6,
        "criss_cross B->E should keep the orthogonal detour points in SVG sharp mode instead of collapsing back into the overlapping mirrored lane: {points:?}"
    );

    let center_x = (points.first().expect("path has points").0
        + points.last().expect("path has points").0)
        / 2.0;
    let mut center_corridor_levels: Vec<f64> = points
        .iter()
        .filter(|(x, _)| (*x - center_x).abs() <= 0.75)
        .map(|(_, y)| *y)
        .collect();
    center_corridor_levels.sort_by(|a, b| a.total_cmp(b));
    center_corridor_levels.dedup_by(|a, b| (*a - *b).abs() <= 0.75);
    assert!(
        center_corridor_levels.len() >= 2,
        "criss_cross B->E sharp SVG path should traverse a visible center corridor after de-overlap instead of collapsing back onto the mirrored edge lane: center_x={center_x}, levels={center_corridor_levels:?}, points={points:?}"
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_label_spacing_keeps_td_departure_stems_from_source() {
    let diagram = load_flowchart_fixture_diagram("label_spacing.mmd");
    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    for (from, to) in [("A", "B"), ("A", "C")] {
        let edge_idx = edge_index(&diagram, from, to);
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        assert!(
            points.len() >= 2,
            "label_spacing {from}->{to} should expose at least two points in orthogonal mode: {points:?}"
        );
        let start = points[0];
        let next = points[1];
        assert!(
            (next.0 - start.0).abs() <= 0.5 && (next.1 - start.1).abs() > 0.5,
            "label_spacing {from}->{to} orthogonal route should depart A along TD primary axis (vertical stem first), not lateral-first: start={start:?}, next={next:?}, points={points:?}"
        );
    }
}

#[test]
fn svg_non_orth_orthogonal_route_fan_in_backward_channel_conflict_keeps_backward_canonical_face() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("flowchart")
        .join("fan_in_backward_channel_conflict.mmd");
    let input = fs::read_to_string(&fixture).expect("fixture should load");
    let flowchart = parse_flowchart(&input).expect("fixture should parse");
    let diagram = compile_to_graph(&flowchart);
    let edge_idx = edge_index(&diagram, "Loop", "B");

    let styles = [SHARP, ROUNDED, SMOOTH];

    let mut rect = None;

    for style in styles {
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(style.1),
            path_simplification: PathSimplification::None,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);
        let (tx, ty, tw, th) = match rect {
            Some(rect) => rect,
            None => {
                let parsed = node_rect_for_label(&svg, "Target")
                    .expect("expected target rect for fan_in_backward_channel_conflict fixture");
                rect = Some(parsed);
                parsed
            }
        };
        let rect = (tx, ty, tw, th);

        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        let end = points
            .last()
            .copied()
            .expect("backward edge should have path points");
        let end_face = svg_terminal_approach_face_relaxed(rect, &points);

        // With per-edge label spacing, compact unlabeled edges route the
        // backward edge via the bottom face instead of the right-face
        // side-channel.
        assert_eq!(
            end_face, "bottom",
            "Loop-conflict edge should use bottom face entry for {style:?}: end={end:?}, rect={rect:?}, points={points:?}"
        );
    }
}

#[test]
fn svg_curved_orthogonal_route_fan_in_backward_channel_conflict_avoids_tiny_terminal_hook_before_arrow()
 {
    let diagram = load_flowchart_fixture_diagram("fan_in_backward_channel_conflict.mmd");
    let edge_idx = edge_index(&diagram, "Loop", "B");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Basis),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);

    assert!(
        points.len() >= 3,
        "fan_in_backward_channel_conflict backward edge should keep at least one terminal support segment in curved mode: points={points:?}"
    );

    let terminal = manhattan_segment_len(points[points.len() - 2], points[points.len() - 1]);
    let trailing_run = trailing_segment_run_len(&points, 4);
    assert!(
        terminal >= 1.0 && trailing_run >= 6.0,
        "curved orthogonal backward terminal hook should avoid tiny elbow before marker; terminal={terminal}, trailing_run={trailing_run}, points={points:?}"
    );
}

#[test]
fn svg_non_orth_orthogonal_route_fan_in_backward_channel_conflict_preserves_lower_terminal_lane() {
    let diagram = load_flowchart_fixture_diagram("fan_in_backward_channel_conflict.mmd");
    let edge_idx = edge_index(&diagram, "Loop", "B");
    let styles = [SHARP, ROUNDED, SMOOTH];

    let mut rect = None;
    for style in styles {
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(style.1),
            path_simplification: PathSimplification::None,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);
        let (_tx, ty, _tw, th) = match rect {
            Some(rect) => rect,
            None => {
                let parsed = node_rect_for_label(&svg, "Target")
                    .expect("expected target rect for fan_in_backward_channel_conflict fixture");
                rect = Some(parsed);
                parsed
            }
        };
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        let end = points
            .last()
            .copied()
            .expect("fan_in_backward_channel_conflict backward edge should have path points");

        // With per-edge label spacing, the backward edge now uses bottom-face
        // routing. The endpoint should land near the target rect (within
        // the rect or just beyond its bottom border due to marker pullback).
        assert!(
            end.1 >= ty && end.1 <= ty + th + 6.0,
            "Loop-conflict non-orth terminal should land near target rect for {style:?}: end={end:?}, target_rect_y={ty}, target_rect_h={th}, points={points:?}"
        );
    }
}

#[test]
fn svg_orthogonal_orthogonal_route_fan_in_backward_channel_conflict_avoids_terminal_axis_backtrack()
{
    let diagram = load_flowchart_fixture_diagram("fan_in_backward_channel_conflict.mmd");
    let edge_idx = edge_index(&diagram, "Loop", "B");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);

    assert!(
        !has_immediate_axis_backtrack(&points),
        "fan_in_backward_channel_conflict orthogonal backward edge should not axis-backtrack near the terminal hook; points={points:?}"
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_decision_backward_edge_avoids_source_elbow_axis_backtrack() {
    let diagram = load_flowchart_fixture_diagram("decision.mmd");
    let edge_idx = edge_index(&diagram, "D", "A");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);

    assert!(
        !has_immediate_axis_backtrack(&points),
        "decision D->A orthogonal backward edge should avoid source-elbow axis backtrack spikes; points={points:?}"
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_decision_backward_edge_uses_right_face_to_avoid_crossing() {
    // D is to the right of A; the crossing-avoidance heuristic bypasses TD
    // top/bottom parity so the backward edge uses side-channel (right-face)
    // routing instead, avoiding a crossing with the forward A->D edge.
    let diagram = load_flowchart_fixture_diagram("decision.mmd");
    let edge_idx = edge_index(&diagram, "D", "A");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
    let start_rect =
        node_rect_for_label(&svg, "Start").expect("missing Start rect in decision fixture");
    let target_face = svg_terminal_approach_face_relaxed(start_rect, &points);

    assert_eq!(
        target_face, "right",
        "decision D->A orthogonal backward edge should enter Start from the right face (crossing avoided); face={target_face}, points={points:?}"
    );
}

#[test]
fn svg_orthogonal_orthogonal_route_decision_backward_edge_preserves_routed_terminal_lane_x() {
    const MAX_TERMINAL_LANE_X_DRIFT: f64 = 10.0;

    let diagram = load_flowchart_fixture_diagram("decision.mmd");
    let edge_idx = edge_index(&diagram, "D", "A");

    let measurement_mode = default_proportional_mode();
    let config = EngineConfig::Layered(crate::engines::graph::algorithms::layered::LayoutConfig {
        greedy_switch: true,
        model_order_tiebreak: true,
        variable_rank_spacing: true,
        track_reversed_chains: true,
        per_edge_label_spacing: true,
        ..crate::engines::graph::algorithms::layered::LayoutConfig::default()
    });
    let geom = run_layered_layout(&measurement_mode, &diagram, &config)
        .expect("layout should succeed for decision fixture");
    let routed = route_graph_geometry(&diagram, &geom, EdgeRouting::OrthogonalRoute);
    let routed_edge = routed
        .edges
        .iter()
        .find(|edge| edge.from == "D" && edge.to == "A")
        .expect("decision fixture should contain backward edge D -> A");
    assert!(
        routed_edge.path.len() >= 3,
        "routed decision D->A should keep at least one terminal support segment: path={:?}",
        routed_edge.path
    );
    let routed_terminal_support = routed_edge.path[routed_edge.path.len() - 2];

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Rounded)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
    assert!(
        points.len() >= 3,
        "rendered decision D->A should keep at least one terminal support segment: points={points:?}"
    );
    let svg_terminal_support = points[points.len() - 2];
    let drift = (svg_terminal_support.0 - routed_terminal_support.x).abs();

    assert!(
        drift <= MAX_TERMINAL_LANE_X_DRIFT,
        "decision D->A orthogonal SVG endpoint adjustment should preserve routed terminal lane x (drift <= {MAX_TERMINAL_LANE_X_DRIFT}); routed_terminal_support={routed_terminal_support:?}, svg_terminal_support={svg_terminal_support:?}, drift={drift}, routed_path={:?}, svg_points={points:?}",
        routed_edge.path
    );
}

#[test]
fn svg_straight_fan_in_backward_channel_interaction_fixture_matrix_matches_documented_faces() {
    let fan_in_cases = [
        ("stacked_fan_in.mmd", "C", "Bot", 0usize),
        ("fan_in.mmd", "D", "Target", 0usize),
        ("five_fan_in.mmd", "F", "Target", 0usize),
    ];

    for (fixture_name, target_id, target_label, min_side_faces) in fan_in_cases {
        let diagram = load_flowchart_fixture_diagram(fixture_name);
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);
        let rect = node_rect_for_label(&svg, target_label)
            .unwrap_or_else(|| panic!("missing target rect for {target_label} in {fixture_name}"));
        let inbound_indices: Vec<usize> = diagram
            .edges
            .iter()
            .filter(|edge| edge.to == target_id)
            .map(|edge| edge.index)
            .collect();
        assert!(
            !inbound_indices.is_empty(),
            "fixture {fixture_name} should have inbound edges to {target_id}"
        );

        let mut side_face_count = 0usize;
        let mut interior_or_corner_count = 0usize;
        for edge_index in inbound_indices {
            let points = edge_path_for_svg_order(&diagram, &svg, edge_index);
            let face = svg_terminal_approach_face(rect, &points);
            if face == "interior_or_corner" {
                interior_or_corner_count += 1;
            }
            if matches!(face, "left" | "right") {
                side_face_count += 1;
            }
        }

        assert_eq!(
            interior_or_corner_count, 0,
            "fixture {fixture_name} should keep inbound endpoints on a concrete target face under Fan-in overflow policy"
        );
        if min_side_faces == 0 {
            assert_eq!(
                side_face_count, 0,
                "fixture {fixture_name} should stay on primary TD incoming face when overflow is not required"
            );
        } else {
            assert!(
                side_face_count >= min_side_faces,
                "fixture {fixture_name} should spill overflow arrivals to side faces under Fan-in overflow policy: expected >= {min_side_faces}, actual={side_face_count}"
            );
        }
    }

    // Corridor-obstructed backward edges typically route via the canonical
    // backward face (right in TD).  With per-edge label spacing, some edges
    // switch to bottom-face routing when compact spacing makes that path
    // more efficient.
    let backward_channel_cases = [
        (
            "simple_cycle.mmd",
            "C",
            "A",
            "End",
            "Start",
            "right",
            "right",
        ),
        (
            "multiple_cycles.mmd",
            "C",
            "A",
            "Bottom",
            "Top",
            "right",
            "right",
        ),
        (
            "fan_in_backward_channel_conflict.mmd",
            "Loop",
            "B",
            "Sink",
            "Target",
            "top",
            "bottom",
        ),
        (
            "http_request.mmd",
            "Response",
            "Client",
            "Send Response",
            "Client",
            "right",
            "right",
        ),
        (
            "git_workflow.mmd",
            "Remote",
            "Working",
            "Remote Repo",
            "Working Dir",
            "bottom",
            "bottom",
        ),
    ];

    for (
        fixture_name,
        from,
        to,
        source_label,
        target_label,
        expected_source_face,
        expected_target_face,
    ) in backward_channel_cases
    {
        let diagram = load_flowchart_fixture_diagram(fixture_name);
        let options = RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        };
        let svg = render_svg(&diagram, &options);
        let source_rect = node_rect_for_label(&svg, source_label)
            .unwrap_or_else(|| panic!("missing source rect for {source_label} in {fixture_name}"));
        let target_rect = node_rect_for_label(&svg, target_label)
            .unwrap_or_else(|| panic!("missing target rect for {target_label} in {fixture_name}"));
        let edge_idx = edge_index(&diagram, from, to);
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        let source_face = svg_source_departure_face(source_rect, &points);
        assert_eq!(
            source_face, expected_source_face,
            "fixture {fixture_name} edge {from}->{to} should keep expected backward source face {expected_source_face}; points={points:?}"
        );
        let target_face = svg_terminal_approach_face_relaxed(target_rect, &points);
        assert_eq!(
            target_face, expected_target_face,
            "fixture {fixture_name} edge {from}->{to} should keep expected backward target face {expected_target_face}; points={points:?}"
        );
    }
}

#[test]
fn svg_orthogonal_route_five_fan_in_keeps_e_terminal_not_left_of_d() {
    let diagram = load_flowchart_fixture_diagram("five_fan_in.mmd");
    let d_edge = edge_index(&diagram, "D", "F");
    let e_edge = edge_index(&diagram, "E", "F");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Basis),
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let d_points = edge_path_for_svg_order(&diagram, &svg, d_edge);
    let e_points = edge_path_for_svg_order(&diagram, &svg, e_edge);
    let d_end = d_points[d_points.len() - 1];
    let e_end = e_points[e_points.len() - 1];

    assert!(
        e_end.0 + 1.0 >= d_end.0,
        "five_fan_in orthogonal routing should not place E->Target terminal left of D->Target: d_end={d_end:?}, e_end={e_end:?}, d_points={d_points:?}, e_points={e_points:?}"
    );
}

#[test]
fn svg_curved_orthogonal_route_five_fan_in_keeps_mirrored_pairs_visually_symmetric() {
    let diagram = load_flowchart_fixture_diagram("five_fan_in.mmd");
    let b_edge = edge_index(&diagram, "B", "F");
    let d_edge = edge_index(&diagram, "D", "F");
    let a_edge = edge_index(&diagram, "A", "F");
    let e_edge = edge_index(&diagram, "E", "F");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Basis),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let b_points = edge_path_for_svg_order(&diagram, &svg, b_edge);
    let d_points = edge_path_for_svg_order(&diagram, &svg, d_edge);
    let a_points = edge_path_for_svg_order(&diagram, &svg, a_edge);
    let e_points = edge_path_for_svg_order(&diagram, &svg, e_edge);

    assert!(
        b_points.len() >= 2 && d_points.len() >= 2 && a_points.len() >= 2 && e_points.len() >= 2,
        "curved fan-in edges should each include at least one segment: B={b_points:?} D={d_points:?} A={a_points:?} E={e_points:?}"
    );
    let b_prev = b_points[b_points.len() - 2];
    let d_prev = d_points[d_points.len() - 2];
    let a_prev = a_points[a_points.len() - 2];
    let e_prev = e_points[e_points.len() - 2];

    assert!(
        (b_prev.1 - d_prev.1).abs() <= 1.0,
        "curved B->Target and D->Target should have mirrored terminal approach depth after fan-in channel collapse: B_prev={b_prev:?}, D_prev={d_prev:?}, B={b_points:?}, D={d_points:?}"
    );
    assert!(
        (a_prev.1 - e_prev.1).abs() <= 1.0,
        "curved A->Target and E->Target should have mirrored terminal approach depth after fan-in channel collapse: A_prev={a_prev:?}, E_prev={e_prev:?}, A={a_points:?}, E={e_points:?}"
    );
}

#[test]
fn svg_curved_orthogonal_route_git_workflow_backward_edge_keeps_terminal_support_into_working_dir()
{
    let diagram = load_flowchart_fixture_diagram("git_workflow.mmd");
    let backward_edge = edge_index(&diagram, "Remote", "Working");

    let options = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Basis),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let svg = render_svg(&diagram, &options);

    let points = edge_path_for_svg_order(&diagram, &svg, backward_edge);
    assert!(
        points.len() >= 2,
        "git_workflow backward curved edge should include a terminal segment: {points:?}"
    );

    let prev = points[points.len() - 2];
    let end = points[points.len() - 1];
    let terminal_support = (prev.0 - end.0).abs() + (prev.1 - end.1).abs();
    assert!(
        terminal_support >= 3.0,
        "git_workflow backward curved edge should keep at least ~3px terminal support into Working Dir: support={terminal_support}, prev={prev:?}, end={end:?}, points={points:?}"
    );
}

#[test]
fn style_segment_monitor_reports_actionable_summary_for_svg() {
    let report =
        style_segment_monitor_report_for_svg(&["edge_styles.mmd", "inline_edge_labels.mmd"], 12.0);
    assert!(
        report.scanned_styled_paths > 0,
        "style monitor should scan at least one styled path; report={report:?}"
    );
    assert!(
        !report.summary_line.is_empty(),
        "style monitor should emit a stable summary line for CI parsing"
    );
    assert!(
        report.violations.is_empty(),
        "style monitor detected styled-segment violations: {:#?}",
        report
    );
}

#[test]
fn svg_straight_orthogonal_route_self_loop_tail_does_not_collapse_upward_before_arrow() {
    let diagram = load_flowchart_fixture_diagram("self_loop_labeled.mmd");
    let edge_idx = edge_index(&diagram, "B", "B");

    let full_svg = render_fixture_svg(&diagram, EdgeRouting::PolylineRoute, SHARP);
    let orthogonal_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SHARP);

    let full_points = edge_path_for_svg_order(&diagram, &full_svg, edge_idx);
    let orthogonal_points = edge_path_for_svg_order(&diagram, &orthogonal_svg, edge_idx);

    assert!(
        full_points.len() >= 4 && orthogonal_points.len() >= 4,
        "expected self-loop to contain at least 4 points; full={full_points:?}, orthogonal={orthogonal_points:?}"
    );

    // Compare the bottom loop lane instead of relying on a fixed elbow index.
    // Polyline cleanup can reduce intermediate points while preserving loop shape.
    let full_tail_lane_y = full_points
        .iter()
        .take(full_points.len().saturating_sub(1))
        .map(|point| point.1)
        .fold(f64::NEG_INFINITY, f64::max);
    let orthogonal_tail_lane_y = orthogonal_points
        .iter()
        .take(orthogonal_points.len().saturating_sub(1))
        .map(|point| point.1)
        .fold(f64::NEG_INFINITY, f64::max);
    let delta_y = (full_tail_lane_y - orthogonal_tail_lane_y).abs();

    assert!(
        delta_y <= 12.0,
        "self-loop tail lane should remain near polyline routing in orthogonal straight mode (avoid upward collapse); full_tail_lane_y={full_tail_lane_y}, orthogonal_tail_lane_y={orthogonal_tail_lane_y}, delta_y={delta_y}, full_points={full_points:?}, orthogonal_points={orthogonal_points:?}"
    );
}

#[test]
fn orthogonal_route_diamond_boundary_clipping_matches_shape_boundary() {
    let diagram = load_flowchart_fixture_diagram("decision.mmd");

    let mode = default_proportional_mode();
    let config =
        EngineConfig::Layered(crate::engines::graph::algorithms::layered::LayoutConfig::default());
    let geom = run_layered_layout(&mode, &diagram, &config).unwrap();
    let routed = route_graph_geometry(&diagram, &geom, EdgeRouting::OrthogonalRoute);

    // B is a diamond; B->D is a forward edge — verify source endpoint is on diamond boundary
    let edge = routed
        .edges
        .iter()
        .find(|e| e.from == "B" && e.to == "D")
        .expect("missing B->D edge");
    let start = edge.path.first().unwrap();
    let b_rect = geom.nodes.get("B").unwrap().rect;
    let cx = b_rect.x + b_rect.width / 2.0;
    let cy = b_rect.y + b_rect.height / 2.0;
    let w = b_rect.width / 2.0;
    let h = b_rect.height / 2.0;
    let boundary = (start.x - cx).abs() / w + (start.y - cy).abs() / h;
    assert!(
        (boundary - 1.0).abs() < 0.05,
        "orthogonal B->D source should be on diamond boundary: boundary={boundary}, start={start:?}"
    );
}

#[test]
fn orthogonal_route_subgraph_to_subgraph_edge_keeps_terminal_attachment() {
    let diagram = load_flowchart_fixture_diagram("subgraph_to_subgraph_edge.mmd");
    let edge_index = edge_index(&diagram, "API", "DB");

    let full_svg = render_fixture_svg(&diagram, EdgeRouting::PolylineRoute, SMOOTH);
    let orthogonal_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SMOOTH);

    let full_points = edge_path_for_svg_order(&diagram, &full_svg, edge_index);
    let orthogonal_points = edge_path_for_svg_order(&diagram, &orthogonal_svg, edge_index);
    let full_start = full_points[0];
    let orthogonal_start = orthogonal_points[0];
    let full_end = full_points[full_points.len() - 1];
    let orthogonal_end = orthogonal_points[orthogonal_points.len() - 1];

    assert!(
        (full_start.1 - orthogonal_start.1).abs() <= 1.0
            && (full_end.1 - orthogonal_end.1).abs() <= 1.0,
        "API -> DB should keep vertical attachment parity with polyline routing; full_points={full_points:?}, orthogonal_points={orthogonal_points:?}"
    );
}

#[test]
fn orthogonal_route_inner_bt_subgraph_edge_does_not_collapse() {
    let diagram = load_flowchart_fixture_diagram("subgraph_direction_nested_both.mmd");
    let edge_index = edge_index(&diagram, "A", "B");

    let full_svg = render_fixture_svg(&diagram, EdgeRouting::PolylineRoute, SMOOTH);
    let orthogonal_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SMOOTH);

    let full_points = edge_path_for_svg_order(&diagram, &full_svg, edge_index);
    let orthogonal_points = edge_path_for_svg_order(&diagram, &orthogonal_svg, edge_index);
    let full_start = full_points[0];
    let orthogonal_start = orthogonal_points[0];
    let full_end = full_points[full_points.len() - 1];
    let orthogonal_end = orthogonal_points[orthogonal_points.len() - 1];
    let full_span = (full_start.1 - full_end.1).abs();
    let orthogonal_span = (orthogonal_start.1 - orthogonal_end.1).abs();

    assert!(
        (full_start.1 - orthogonal_start.1).abs() <= 1.0
            && (full_end.1 - orthogonal_end.1).abs() <= 1.0
            && orthogonal_span >= full_span - 1.0,
        "A -> B in inner BT subgraph should preserve polyline span; full_points={full_points:?}, orthogonal_points={orthogonal_points:?}, full_span={full_span}, orthogonal_span={orthogonal_span}"
    );
}

#[test]
fn orthogonal_route_nested_override_cross_boundary_edge_keeps_lr_side_faces() {
    let diagram = load_flowchart_fixture_diagram("subgraph_direction_nested_both.mmd");
    let edge_index = edge_index(&diagram, "C", "A");

    let full_svg = render_fixture_svg(&diagram, EdgeRouting::PolylineRoute, ROUNDED);
    let orthogonal_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, ROUNDED);

    let full_points = edge_path_for_svg_order(&diagram, &full_svg, edge_index);
    let orthogonal_points = edge_path_for_svg_order(&diagram, &orthogonal_svg, edge_index);

    let source_rect = node_rect_for_label(&full_svg, "C")
        .expect("subgraph_direction_nested_both should render node rect for C");
    let target_rect = node_rect_for_label(&full_svg, "A")
        .expect("subgraph_direction_nested_both should render node rect for A");

    let full_source_face = svg_source_departure_face(source_rect, &full_points);
    let full_target_face = svg_terminal_approach_face_relaxed(target_rect, &full_points);
    let orthogonal_source_face = svg_source_departure_face(source_rect, &orthogonal_points);
    let orthogonal_target_face =
        svg_terminal_approach_face_relaxed(target_rect, &orthogonal_points);

    assert_eq!(
        full_source_face, "right",
        "fixture contract invalid: polyline C->A should depart C from east/right face: points={full_points:?}"
    );
    assert_eq!(
        full_target_face, "left",
        "fixture contract invalid: polyline C->A should enter A from west/left face: points={full_points:?}"
    );
    assert_eq!(
        orthogonal_source_face, full_source_face,
        "orthogonal C->A should preserve source face parity with polyline in nested override cross-boundary routing: full={full_source_face}, orthogonal={orthogonal_source_face}, full_points={full_points:?}, orthogonal_points={orthogonal_points:?}"
    );
    assert_eq!(
        orthogonal_target_face, full_target_face,
        "orthogonal C->A should preserve target face parity with polyline in nested override cross-boundary routing: full={full_target_face}, orthogonal={orthogonal_target_face}, full_points={full_points:?}, orthogonal_points={orthogonal_points:?}"
    );
}

#[test]
fn render_svg_edge_styles_and_labels() {
    let input = "graph TD\nA ==>|yes| B\nB -.->|no| C\nC <--> D\n";
    let flowchart = parse_flowchart(input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    assert!(svg.contains("stroke-dasharray"));
    assert!(svg.contains("stroke-width"));
    assert!(svg.contains("marker-end"));
    assert!(svg.contains("marker-start"));
    assert!(svg.contains("yes"));
    assert!(svg.contains("no"));
}

#[test]
fn svg_render_applies_fill_stroke_and_label_color_from_node_style() {
    let diagram = load_flowchart_fixture_diagram("style-basic.mmd");
    let svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SMOOTH);

    assert!(
        svg.contains("fill=\"#ffeeaa\""),
        "styled node fill missing: {svg}"
    );
    assert!(
        svg.contains("stroke=\"#333\""),
        "styled node stroke missing: {svg}"
    );
    assert!(
        svg.contains("fill=\"#111\">Alpha</text>"),
        "styled node label color missing: {svg}"
    );
}

#[test]
fn runtime_svg_theme_does_not_override_node_style_colors() {
    let input = fs::read_to_string(
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("fixtures")
            .join("flowchart")
            .join("style-basic.mmd"),
    )
    .expect("fixture should load");
    let svg = crate::render_diagram(
        &input,
        OutputFormat::Svg,
        &RenderConfig {
            svg_theme: Some(SvgThemeConfig {
                name: Some("dark".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        },
    )
    .expect("runtime SVG render should succeed");

    assert!(svg.contains("background-color: #333333;"), "{svg}");
    assert!(svg.contains("fill=\"#ffeeaa\""), "{svg}");
    assert!(svg.contains("stroke=\"#333\""), "{svg}");
    assert!(svg.contains("fill=\"#111\">Alpha</text>"), "{svg}");
}

#[test]
fn unstyled_svg_keeps_existing_default_colors() {
    let input = "graph TD\nA-->B\n";
    let flowchart = parse_flowchart(input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    assert!(
        svg.contains("fill=\"white\" stroke=\"#333\""),
        "unstyled node shape colors changed: {svg}"
    );
    assert!(
        svg.contains("fill=\"#333\">A</text>"),
        "unstyled node label color changed: {svg}"
    );
}

#[test]
fn render_svg_subgraphs_and_self_edges() {
    let input = "graph TD\nsubgraph Group\nA-->A\nend\n";
    let flowchart = parse_flowchart(input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    assert!(svg.contains("Group"));
    assert!(svg.contains("class=\"subgraph\""));
    assert!(svg.matches("<path").count() >= 2);
}

#[test]
fn render_svg_direction_override_lr_node_positions() {
    // subgraph_direction_lr.mmd: TD graph with LR subgraph containing Step 1 -> Step 2 -> Step 3
    // After direction override, these nodes should be arranged horizontally (increasing x).
    let input =
        std::fs::read_to_string("tests/fixtures/flowchart/subgraph_direction_lr.mmd").unwrap();
    let flowchart = parse_flowchart(&input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    let positions = extract_node_x_positions(&svg);
    let x_step1 = positions.get("Step 1").expect("Step 1 not found in SVG");
    let x_step2 = positions.get("Step 2").expect("Step 2 not found in SVG");
    let x_step3 = positions.get("Step 3").expect("Step 3 not found in SVG");

    assert!(
        x_step1 < x_step2 && x_step2 < x_step3,
        "LR direction override: Step 1 ({x_step1}) < Step 2 ({x_step2}) < Step 3 ({x_step3}) expected"
    );
}

#[test]
fn render_svg_direction_override_cross_boundary() {
    // subgraph_direction_cross_boundary.mmd: TD graph with LR subgraph, cross-boundary edges
    let input =
        std::fs::read_to_string("tests/fixtures/flowchart/subgraph_direction_cross_boundary.mmd")
            .unwrap();
    let flowchart = parse_flowchart(&input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    // A and B are inside the LR subgraph, should be horizontal
    let positions = extract_node_x_positions(&svg);
    let x_a = positions.get("A").expect("A not found in SVG");
    let x_b = positions.get("B").expect("B not found in SVG");

    assert!(
        x_a < x_b,
        "LR direction override: A ({x_a}) should be left of B ({x_b})"
    );

    // SVG should not contain NaN values
    assert!(!svg.contains("NaN"), "SVG should not contain NaN values");
}

#[test]
fn render_svg_direction_override_cross_boundary_remains_nan_free() {
    let input =
        std::fs::read_to_string("tests/fixtures/flowchart/subgraph_direction_cross_boundary.mmd")
            .unwrap();
    let flowchart = parse_flowchart(&input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    assert!(!svg.contains("NaN"), "SVG should not contain NaN values");
    assert!(
        !svg.contains("inf"),
        "SVG should not contain infinite values"
    );
}

#[test]
fn cross_boundary_direction_override_edges_still_render_without_nan() {
    let input =
        std::fs::read_to_string("tests/fixtures/flowchart/subgraph_direction_cross_boundary.mmd")
            .unwrap();
    let flowchart = parse_flowchart(&input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    assert!(!svg.contains("NaN"));
}

#[test]
fn render_svg_direction_override_mixed() {
    // subgraph_direction_mixed.mmd: Two subgraphs with different direction overrides
    let input =
        std::fs::read_to_string("tests/fixtures/flowchart/subgraph_direction_mixed.mmd").unwrap();
    let flowchart = parse_flowchart(&input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    let positions = extract_node_x_positions(&svg);

    // LR group: A should be left of B
    let x_a = positions.get("A").expect("A not found");
    let x_b = positions.get("B").expect("B not found");
    assert!(x_a < x_b, "LR: A ({x_a}) should be left of B ({x_b})");

    // BT group: C and D should be vertically arranged (same x or close x)
    let x_c = positions.get("C").expect("C not found");
    let x_d = positions.get("D").expect("D not found");
    assert!(
        (x_c - x_d).abs() < 1.0,
        "BT: C ({x_c}) and D ({x_d}) should have similar x (vertically stacked)"
    );

    assert!(!svg.contains("NaN"), "SVG should not contain NaN");
}

#[test]
fn render_svg_direction_override_nested() {
    // subgraph_direction_nested.mmd: Outer (no override) with inner LR subgraph
    let input =
        std::fs::read_to_string("tests/fixtures/flowchart/subgraph_direction_nested.mmd").unwrap();
    let flowchart = parse_flowchart(&input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    let positions = extract_node_x_positions(&svg);

    // Inner LR: A -> B -> C should be horizontal
    let x_a = positions.get("A").expect("A not found");
    let x_b = positions.get("B").expect("B not found");
    let x_c = positions.get("C").expect("C not found");
    assert!(
        x_a < x_b && x_b < x_c,
        "Inner LR: A ({x_a}) < B ({x_b}) < C ({x_c})"
    );

    assert!(!svg.contains("NaN"), "SVG should not contain NaN");
}

#[test]
fn render_svg_direction_override_nested_both() {
    // subgraph_direction_nested_both.mmd: Outer LR with inner BT
    let input =
        std::fs::read_to_string("tests/fixtures/flowchart/subgraph_direction_nested_both.mmd")
            .unwrap();
    let flowchart = parse_flowchart(&input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    let positions = extract_node_x_positions(&svg);

    // Inner BT: A and B should be vertically arranged (similar x)
    let x_a = positions.get("A").expect("A not found");
    let x_b = positions.get("B").expect("B not found");
    assert!(
        (x_a - x_b).abs() < 1.0,
        "Inner BT: A ({x_a}) and B ({x_b}) should have similar x"
    );

    // Outer LR: C should be to the side of the inner subgraph
    assert!(positions.contains_key("C"), "C should be present");

    assert!(!svg.contains("NaN"), "SVG should not contain NaN");
}

#[test]
fn render_svg_all_direction_override_fixtures_valid() {
    // Run all direction override fixtures and verify no NaN and valid SVG
    let fixtures = [
        "subgraph_direction_lr.mmd",
        "subgraph_direction_cross_boundary.mmd",
        "subgraph_direction_mixed.mmd",
        "subgraph_direction_nested.mmd",
        "subgraph_direction_nested_both.mmd",
    ];
    for fixture in &fixtures {
        let path = format!("tests/fixtures/flowchart/{fixture}");
        let input =
            std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("Failed to read {path}: {e}"));
        let flowchart =
            parse_flowchart(&input).unwrap_or_else(|e| panic!("Failed to parse {path}: {e}"));
        let diagram = compile_to_graph(&flowchart);
        let svg = render_svg(&diagram, &RenderConfig::default());

        assert!(
            svg.starts_with("<svg"),
            "{fixture}: SVG should start with <svg"
        );
        assert!(
            !svg.contains("NaN"),
            "{fixture}: SVG should not contain NaN"
        );
        // Every fixture should have at least one edge path
        assert!(
            svg.contains("<path"),
            "{fixture}: SVG should contain at least one <path element"
        );
    }
}

#[test]
fn render_svg_direction_override_backward_edge() {
    // Backward edge (B -> Start) crossing subgraph boundary
    let input = r#"graph TD
    Start --> A
    subgraph sg1[Loop Section]
        direction LR
        A --> B
    end
    B --> Start
"#;
    let flowchart = parse_flowchart(input).unwrap();
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    let positions = extract_node_x_positions(&svg);

    // LR nodes A and B should be horizontal
    let x_a = positions.get("A").expect("A not found");
    let x_b = positions.get("B").expect("B not found");
    assert!(x_a < x_b, "LR: A ({x_a}) should be left of B ({x_b})");

    assert!(!svg.contains("NaN"), "SVG should not contain NaN");
    assert!(svg.contains("<path"), "SVG should have edge paths");
}

#[test]
fn render_svg_positioned_mmds_routed_basic_includes_paths_and_subgraph() {
    let input = std::fs::read_to_string("tests/fixtures/mmds/positioned/routed-basic.json")
        .expect("positioned fixture should exist");
    let config = RenderConfig::default();
    let svg = crate::runtime::mmds::render_input(
        &input,
        OutputFormat::Svg,
        config.geometry_level,
        &config.text_render_options(OutputFormat::Svg),
        &config.svg_render_options(),
        None,
    )
    .expect("routed MMDS should render SVG");

    assert!(svg.starts_with("<svg"));
    assert!(svg.contains("class=\"subgraph\""));
    assert!(svg.contains("<path"));
    assert!(svg.contains("Start"));
    assert!(svg.contains("Group"));
}

/// Assert MMDS and SVG endpoints agree within `tolerance` for a given edge.
fn assert_mmds_svg_endpoint_convergence(
    diagram: &crate::graph::Graph,
    from: &str,
    to: &str,
    tolerance: f64,
) {
    // MMDS path (no SVG post-adjustment) — use flux-layered enhancements
    // to match the SVG path which goes through render_svg (flux-layered).
    let mode = default_proportional_mode();
    let config = EngineConfig::Layered(crate::engines::graph::algorithms::layered::LayoutConfig {
        greedy_switch: true,
        model_order_tiebreak: true,
        variable_rank_spacing: true,
        track_reversed_chains: true,
        per_edge_label_spacing: true,
        ..crate::engines::graph::algorithms::layered::LayoutConfig::default()
    });
    let geom = run_layered_layout(&mode, diagram, &config).unwrap();
    let routed = route_graph_geometry(diagram, &geom, EdgeRouting::OrthogonalRoute);
    let mmds_edge = routed
        .edges
        .iter()
        .find(|e| e.from == from && e.to == to)
        .unwrap_or_else(|| panic!("MMDS should have edge {from}->{to}"));
    let mmds_start = mmds_edge.path.first().unwrap();
    let mmds_end = mmds_edge.path.last().unwrap();

    // SVG path (with SVG post-adjustment pipeline)
    let svg = render_fixture_svg(diagram, EdgeRouting::OrthogonalRoute, SMOOTH);
    let edge_idx = edge_index(diagram, from, to);
    let svg_points = edge_path_for_svg_order(diagram, &svg, edge_idx);
    let svg_start = svg_points[0];
    let svg_end = svg_points[svg_points.len() - 1];

    // Source convergence
    let dx = (mmds_start.x - svg_start.0).abs();
    let dy = (mmds_start.y - svg_start.1).abs();
    assert!(
        dx <= tolerance && dy <= tolerance,
        "MMDS/SVG source convergence failed for {from}->{to}: mmds={mmds_start:?}, svg={svg_start:?}, delta=({dx:.2}, {dy:.2})"
    );

    // Target convergence
    let dx = (mmds_end.x - svg_end.0).abs();
    let dy = (mmds_end.y - svg_end.1).abs();
    assert!(
        dx <= tolerance && dy <= tolerance,
        "MMDS/SVG target convergence failed for {from}->{to}: mmds=({:.2}, {:.2}), svg={svg_end:?}, delta=({dx:.2}, {dy:.2})",
        mmds_end.x,
        mmds_end.y
    );
}

#[test]
fn mmds_svg_diamond_endpoint_convergence_decision() {
    let diagram = load_flowchart_fixture_diagram("decision.mmd");

    // Tolerance accounts for SVG marker offsets (~3-4px for arrow markers).
    // Before single-sourcing, diamond endpoints diverged by 30-40+px.
    let tolerance = 5.0;

    // Test edges from diamond node B (source convergence)
    for (from, to) in [("B", "C"), ("B", "D")] {
        assert_mmds_svg_endpoint_convergence(&diagram, from, to, tolerance);
    }

    // Test edge into diamond node B (target convergence)
    assert_mmds_svg_endpoint_convergence(&diagram, "A", "B", tolerance);
}

#[test]
fn mmds_svg_diamond_endpoint_convergence_diamond_fan_out() {
    let diagram = load_flowchart_fixture_diagram("diamond_fan_out.mmd");
    let tolerance = 5.0;
    for to in ["B", "C", "D"] {
        assert_mmds_svg_endpoint_convergence(&diagram, "A", to, tolerance);
    }
}

#[test]
fn mmds_svg_hexagon_endpoint_convergence_hexagon_flow() {
    let diagram = load_flowchart_fixture_diagram("hexagon_flow.mmd");
    let tolerance = 5.0;
    // Fan-out from hexagon A
    for to in ["B", "D"] {
        assert_mmds_svg_endpoint_convergence(&diagram, "A", to, tolerance);
    }
    // Fan-in to hexagon A
    assert_mmds_svg_endpoint_convergence(&diagram, "C", "A", tolerance);
}

#[test]
fn mmds_svg_diamond_backward_endpoint_convergence() {
    let diagram = load_flowchart_fixture_diagram("diamond_backward.mmd");
    let tolerance = 5.0;
    // Forward edges to/from diamond B
    assert_mmds_svg_endpoint_convergence(&diagram, "A", "B", tolerance);
    assert_mmds_svg_endpoint_convergence(&diagram, "B", "C", tolerance);
    // Backward edge C->B (target is diamond)
    assert_mmds_svg_endpoint_convergence(&diagram, "C", "B", tolerance);
}

#[test]
fn svg_rerouted_endpoints_do_not_detach_from_expected_faces() {
    let diagram = load_flowchart_fixture_diagram("diamond_backward.mmd");
    let svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SMOOTH);
    let points = edge_path_for_svg_order(&diagram, &svg, edge_index(&diagram, "C", "B"));
    let source_rect =
        node_rect_for_label(&svg, "Process").expect("source rect should exist in rendered SVG");
    let target_rect =
        node_rect_for_label(&svg, "Check").expect("target rect should exist in rendered SVG");
    let end = *points
        .last()
        .expect("rerouted path should have a terminal point");
    let (target_x, target_y, target_w, target_h) = target_rect;
    let target_bottom = target_y + target_h;

    assert_eq!(
        svg_source_departure_face(source_rect, &points),
        "top",
        "diamond_backward C->B should leave the source from the top face after rerouting: points={points:?}"
    );
    assert!(
        end.0 >= target_x && end.0 <= target_x + target_w,
        "diamond_backward C->B should stay horizontally aligned with the diamond target after rerouting: end={end:?}, target_rect={target_rect:?}"
    );
    assert!(
        end.1 <= target_bottom && target_bottom - end.1 <= 6.0,
        "diamond_backward C->B should terminate within marker pullback tolerance of the diamond bottom boundary after rerouting: end={end:?}, target_rect={target_rect:?}"
    );
}

#[test]
fn mmds_svg_mixed_shape_chain_endpoint_convergence() {
    let diagram = load_flowchart_fixture_diagram("mixed_shape_chain.mmd");
    let tolerance = 5.0;
    // A[rect]->B{diamond}->C{{hexagon}}->D[rect]
    assert_mmds_svg_endpoint_convergence(&diagram, "A", "B", tolerance);
    assert_mmds_svg_endpoint_convergence(&diagram, "B", "C", tolerance);
    assert_mmds_svg_endpoint_convergence(&diagram, "C", "D", tolerance);
}

// --- Task 4.3: SVG style/topology decoupling ---

/// Extract (start, end) endpoint coordinates for each edge path in the SVG.
fn extract_edge_endpoints(svg: &str) -> Vec<((f64, f64), (f64, f64))> {
    edge_path_data(svg)
        .iter()
        .filter_map(|d| {
            let pts = parse_svg_path_points(d);
            if pts.len() >= 2 {
                Some((pts[0], pts[pts.len() - 1]))
            } else {
                None
            }
        })
        .collect()
}

#[test]
fn svg_style_does_not_alter_edge_path_topology() {
    // Style (Sharp vs Smooth) should not change which points edges connect —
    // only how segments are drawn.
    let diagram = load_flowchart_fixture_diagram("fan_in.mmd");

    let sharp_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SHARP);
    let smooth_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SMOOTH);

    let sharp_endpoints = extract_edge_endpoints(&sharp_svg);
    let smooth_endpoints = extract_edge_endpoints(&smooth_svg);

    assert_eq!(
        sharp_endpoints.len(),
        smooth_endpoints.len(),
        "same number of edge paths"
    );
    for (i, (se, sme)) in sharp_endpoints
        .iter()
        .zip(smooth_endpoints.iter())
        .enumerate()
    {
        let (sharp_start, sharp_end) = se;
        let (smooth_start, smooth_end) = sme;
        assert!(
            (sharp_start.0 - smooth_start.0).abs() <= 1.0
                && (sharp_start.1 - smooth_start.1).abs() <= 1.0,
            "edge {i} start should match: sharp={sharp_start:?} smooth={smooth_start:?}"
        );
        assert!(
            (sharp_end.0 - smooth_end.0).abs() <= 1.0 && (sharp_end.1 - smooth_end.1).abs() <= 1.0,
            "edge {i} end should match: sharp={sharp_end:?} smooth={smooth_end:?}"
        );
    }
}

#[test]
fn svg_rounded_style_does_not_force_orthogonal_topology() {
    // Rounded applies arc corners to existing engine-provided paths.
    // It must not alter how endpoints connect to nodes.
    let diagram = load_flowchart_fixture_diagram("fan_in.mmd");

    let rounded_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, ROUNDED);
    let smooth_svg = render_fixture_svg(&diagram, EdgeRouting::OrthogonalRoute, SMOOTH);

    let rounded_endpoints = extract_edge_endpoints(&rounded_svg);
    let smooth_endpoints = extract_edge_endpoints(&smooth_svg);

    assert_eq!(
        rounded_endpoints.len(),
        smooth_endpoints.len(),
        "same number of edge paths"
    );
    for (i, (re, sme)) in rounded_endpoints
        .iter()
        .zip(smooth_endpoints.iter())
        .enumerate()
    {
        let (r_start, r_end) = re;
        let (s_start, s_end) = sme;
        assert!(
            (r_start.0 - s_start.0).abs() <= 1.0 && (r_start.1 - s_start.1).abs() <= 1.0,
            "edge {i} start should match: rounded={r_start:?} smooth={s_start:?}"
        );
        assert!(
            (r_end.0 - s_end.0).abs() <= 1.0 && (r_end.1 - s_end.1).abs() <= 1.0,
            "edge {i} end should match: rounded={r_end:?} smooth={s_end:?}"
        );
    }
}

#[test]
fn svg_flux_complex_polyline_presets_keep_node_layout_invariant() {
    let diagram = load_flowchart_fixture_diagram("complex.mmd");

    let basis_svg = render_flux_svg_with_style(
        &diagram,
        EdgeRouting::PolylineRoute,
        RoutingStyle::Polyline,
        Curve::Basis,
    );
    let polyline_svg = render_flux_svg_with_style(
        &diagram,
        EdgeRouting::PolylineRoute,
        RoutingStyle::Polyline,
        Curve::Linear(CornerStyle::Sharp),
    );

    let basis_centers = svg_node_centers_by_id(&diagram, &basis_svg);
    let polyline_centers = svg_node_centers_by_id(&diagram, &polyline_svg);
    assert_svg_node_centers_equal(
        &basis_centers,
        &polyline_centers,
        0.25,
        "complex polyline-routing presets",
    );
}

#[test]
fn svg_flux_complex_orthogonal_presets_keep_node_layout_invariant() {
    let diagram = load_flowchart_fixture_diagram("complex.mmd");

    let step_svg = render_flux_svg_with_style(
        &diagram,
        EdgeRouting::OrthogonalRoute,
        RoutingStyle::Orthogonal,
        Curve::Linear(CornerStyle::Sharp),
    );
    let smooth_step_svg = render_flux_svg_with_style(
        &diagram,
        EdgeRouting::OrthogonalRoute,
        RoutingStyle::Orthogonal,
        Curve::Linear(CornerStyle::Rounded),
    );
    let curved_step_svg = render_flux_svg_with_style(
        &diagram,
        EdgeRouting::OrthogonalRoute,
        RoutingStyle::Orthogonal,
        Curve::Basis,
    );

    let step_centers = svg_node_centers_by_id(&diagram, &step_svg);
    let smooth_step_centers = svg_node_centers_by_id(&diagram, &smooth_step_svg);
    let curved_step_centers = svg_node_centers_by_id(&diagram, &curved_step_svg);

    assert_svg_node_centers_equal(
        &step_centers,
        &smooth_step_centers,
        0.25,
        "complex orthogonal step vs smooth-step",
    );
    assert_svg_node_centers_equal(
        &step_centers,
        &curved_step_centers,
        0.25,
        "complex orthogonal step vs curved-step",
    );
}

#[test]
fn svg_flux_crossing_minimize_direct_and_orthogonal_avoid_known_crossing_pair() {
    let diagram = load_flowchart_fixture_diagram("crossing_minimize.mmd");
    let edge_bd = edge_index(&diagram, "B", "D");
    let edge_ea = edge_index(&diagram, "E", "A");

    let styles = [
        (
            "straight",
            EdgeRouting::DirectRoute,
            RoutingStyle::Direct,
            Curve::Linear(CornerStyle::Sharp),
        ),
        (
            "step",
            EdgeRouting::OrthogonalRoute,
            RoutingStyle::Orthogonal,
            Curve::Linear(CornerStyle::Sharp),
        ),
    ];

    for (style_name, edge_routing, routing_style, curve) in styles {
        let svg = render_flux_svg_with_style(&diagram, edge_routing, routing_style, curve);
        let bd_path = edge_path_for_svg_order(&diagram, &svg, edge_bd);
        let ea_path = edge_path_for_svg_order(&diagram, &svg, edge_ea);
        assert!(
            !paths_have_strict_interior_crossing(&bd_path, &ea_path),
            "crossing_minimize {style_name} should avoid strict interior crossing between B->D and E->A; B->D={bd_path:?}, E->A={ea_path:?}"
        );
    }
}

#[test]
fn svg_renders_head_label() {
    let input = "graph TD\n  A --> B\n";
    let flowchart = parse_flowchart(input).unwrap();
    let mut diagram = compile_to_graph(&flowchart);
    diagram.edges[0].head_label = Some("1..*".to_string());

    let svg = render_svg(&diagram, &RenderConfig::default());
    assert!(
        svg.contains("1..*"),
        "SVG should contain head label text '1..*'"
    );
}

#[test]
fn svg_renders_tail_label() {
    let input = "graph TD\n  A --> B\n";
    let flowchart = parse_flowchart(input).unwrap();
    let mut diagram = compile_to_graph(&flowchart);
    diagram.edges[0].tail_label = Some("src".to_string());

    let svg = render_svg(&diagram, &RenderConfig::default());
    assert!(
        svg.contains(">src<"),
        "SVG should contain tail label text 'src'"
    );
}

// ---------------------------------------------------------------------------
// LR forward orthogonal clearance — characterization (plan 0122, task 1.1)
// ---------------------------------------------------------------------------

/// Both step and basis routing must avoid the `render` node interior on the
/// architecture-style LR fixture.  (Before the forward-avoidance fix, step
/// crossed render while basis did not.)
#[test]
fn svg_lr_architecture_repro_both_presets_avoid_render() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_intrusion.mmd");
    let edge_idx = edge_index(&diagram, "registry", "format");

    // Step preset: RoutingStyle::Orthogonal + Curve::Linear(CornerStyle::Sharp)
    let step_svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    // Basis preset: RoutingStyle::Polyline + Curve::Basis
    let basis_svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Polyline),
            curve: Some(Curve::Basis),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    // Step must now avoid render.
    let render_rect =
        node_rect_for_label(&step_svg, "render").expect("render node should exist in step SVG");
    let step_points = edge_path_for_svg_order(&diagram, &step_svg, edge_idx);
    assert!(
        !path_crosses_rect_interior(&step_points, render_rect, -0.5),
        "step registry→format should NOT cross render; points={step_points:?}, rect={render_rect:?}"
    );

    // Basis was already clean — confirm it stays that way.
    let basis_render =
        node_rect_for_label(&basis_svg, "render").expect("render node should exist in basis SVG");
    let basis_d = edge_path_d_for_svg_order(&diagram, &basis_svg, edge_idx);
    let basis_sampled = sample_svg_path_commands(&parse_svg_path_command_sequence(&basis_d), 64);
    assert!(
        !sampled_path_crosses_rect_interior(&basis_sampled, basis_render, 1.0),
        "basis registry→format should NOT cross render; d={basis_d}"
    );
}

/// The step route on the architecture-style LR fixture must be multi-bend
/// (≥5 SVG path commands) after full orthogonalization, so it exercises the
/// non-trivial forward routing path rather than the trivial 4-point case.
#[test]
fn svg_lr_architecture_repro_step_route_is_multi_bend_after_orthogonalization() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_intrusion.mmd");
    let step_svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    let d = edge_path_d_for_svg_order(
        &diagram,
        &step_svg,
        edge_index(&diagram, "registry", "format"),
    );
    let commands = parse_svg_path_command_sequence(&d);
    assert!(
        commands.len() >= 5,
        "expected a multi-bend path (≥5 commands), got {} commands; d={d}",
        commands.len()
    );
}

// ---------------------------------------------------------------------------
// LR forward orthogonal clearance — desired behavior (plan 0122, task 2.1)
// ---------------------------------------------------------------------------

/// After the forward avoidance fix, step-preset edges on the architecture-style
/// LR fixture must no longer cross through unrelated node interiors.
/// Extract all (label, rect) pairs from an SVG.
fn extract_all_node_rects(svg: &str) -> Vec<(String, (f64, f64, f64, f64))> {
    let mut results = Vec::new();
    for line in svg.lines() {
        if let Some((_, _, value)) = parse_svg_text_position_and_value(line)
            && let Some(rect) = node_rect_for_label(svg, &value)
        {
            results.push((value, rect));
        }
    }
    results.dedup_by(|a, b| a.0 == b.0);
    results
}

/// Get the display label for a node ID in a diagram.
fn node_label(diagram: &crate::graph::Graph, node_id: &str) -> String {
    diagram
        .nodes
        .get(node_id)
        .map(|n| n.label.clone())
        .unwrap_or_else(|| node_id.to_string())
}

#[test]
fn svg_lr_architecture_repro_step_avoids_render_after_forward_fix() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_intrusion.mmd");
    let edge_idx = edge_index(&diagram, "registry", "format");

    let step_svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    let render_rect = node_rect_for_label(&step_svg, "render").expect("render node should exist");
    let step_points = edge_path_for_svg_order(&diagram, &step_svg, edge_idx);

    assert!(
        !path_crosses_rect_interior(&step_points, render_rect, -0.5),
        "step registry→format should NOT cross render after fix; points={step_points:?}, rect={render_rect:?}"
    );
}

// ---------------------------------------------------------------------------
// LR forward orthogonal clearance — multi-preset and hairpin (plan 0122, tasks 2.2/2.3)
// ---------------------------------------------------------------------------

/// All orthogonal presets (step, smooth-step, curved-step) must avoid the
/// `render` node interior on the architecture-style LR fixture.
#[test]
fn svg_lr_architecture_repro_all_orthogonal_presets_avoid_render() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_intrusion.mmd");
    let edge_idx = edge_index(&diagram, "registry", "format");

    let presets: &[(RoutingStyle, Curve, &str)] = &[
        (
            RoutingStyle::Orthogonal,
            Curve::Linear(CornerStyle::Sharp),
            "step",
        ),
        (
            RoutingStyle::Orthogonal,
            Curve::Linear(CornerStyle::Rounded),
            "smooth-step",
        ),
        (RoutingStyle::Orthogonal, Curve::Basis, "curved-step"),
    ];

    for &(routing, curve, label) in presets {
        let svg = render_svg(
            &diagram,
            &RenderConfig {
                routing_style: Some(routing),
                curve: Some(curve),
                path_simplification: PathSimplification::None,
                ..Default::default()
            },
        );

        let render_rect = node_rect_for_label(&svg, "render").expect("render node should exist");

        // For basis-curve presets, sample the cubic curves densely.
        if matches!(curve, Curve::Basis) {
            let d = edge_path_d_for_svg_order(&diagram, &svg, edge_idx);
            let sampled = sample_svg_path_commands(&parse_svg_path_command_sequence(&d), 64);
            assert!(
                !sampled_path_crosses_rect_interior(&sampled, render_rect, 1.0),
                "{label} registry→format should NOT cross render; d={d}"
            );
        } else {
            let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
            assert!(
                !path_crosses_rect_interior(&points, render_rect, -0.5),
                "{label} registry→format should NOT cross render; points={points:?}"
            );
        }
    }
}

/// The LR forward route on the architecture fixture must not contain a
/// primary-axis reversal (hairpin) after the avoidance fix.
#[test]
fn svg_lr_architecture_repro_no_primary_axis_reversal() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_intrusion.mmd");
    let edge_idx = edge_index(&diagram, "registry", "format");

    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
    // In LR, primary axis is x.  No consecutive x-coordinates should decrease.
    let has_x_reversal = points.windows(2).any(|w| w[1].0 < w[0].0 - 0.5);
    assert!(
        !has_x_reversal,
        "registry→format should not have a primary-axis (x) reversal; points={points:?}"
    );
}

#[test]
fn svg_lr_architecture_render_graph_step_preserves_source_support_elbow() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_intrusion.mmd");
    let edge_idx = edge_index(&diagram, "render", "graph");
    let config = RenderConfig {
        routing_style: Some(RoutingStyle::Orthogonal),
        curve: Some(Curve::Linear(CornerStyle::Sharp)),
        path_simplification: PathSimplification::None,
        ..Default::default()
    };
    let visual = solve_visual_geometry(&diagram, &config);
    let visual_path = visual
        .edges
        .iter()
        .find(|edge| edge.index == edge_idx)
        .and_then(|edge| edge.layout_path_hint.clone())
        .unwrap_or_default();
    assert!(
        visual_path.len() >= 3,
        "render→graph visual orthogonal hint should contain at least three points for its source-support elbow: visual_path={visual_path:?}"
    );
    assert!(
        (visual_path[0].y - visual_path[1].y).abs() <= 0.5
            && (visual_path[0].x - visual_path[1].x).abs() >= 3.5,
        "render→graph visual orthogonal hint should leave render on a short horizontal support segment before turning upward: visual_path={visual_path:?}"
    );
    assert!(
        (visual_path[1].x - visual_path[2].x).abs() <= 0.5,
        "render→graph visual orthogonal hint should turn vertically immediately after its source-support elbow: visual_path={visual_path:?}"
    );

    let svg = render_svg(&diagram, &config);

    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
    assert!(
        points.len() >= 3,
        "render→graph step SVG should contain at least three points for its source-support elbow: points={points:?}"
    );
    assert!(
        (points[0].1 - points[1].1).abs() <= 0.5 && (points[0].0 - points[1].0).abs() >= 3.5,
        "render→graph step SVG should leave render on a short horizontal support segment before turning upward: visual_path={visual_path:?}, points={points:?}"
    );
    assert!(
        (points[1].0 - points[2].0).abs() <= 0.5,
        "render→graph step SVG should turn vertically immediately after its source-support elbow: visual_path={visual_path:?}, points={points:?}"
    );
}

#[test]
fn svg_lr_architecture_payload_timeline_step_simplifies_source_staircase() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_intrusion.mmd");
    let edge_idx = edge_index(&diagram, "payload", "timeline");
    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
    assert!(
        points.len() >= 2,
        "payload→timeline step SVG should contain at least two points: points={points:?}"
    );
    assert!(
        (points[0].1 - points[1].1).abs() <= 0.5,
        "payload→timeline step SVG should start on a single horizontal lane from payload: points={points:?}"
    );
    assert!(
        points.len() >= 4,
        "payload→timeline step SVG should contain an interior vertical column and a final horizontal approach: points={points:?}"
    );
    assert!(
        points[1..points.len() - 1]
            .windows(2)
            .all(|segment| (segment[0].0 - segment[1].0).abs() <= 0.5),
        "payload→timeline step SVG should use a single interior vertical column instead of a split source staircase: points={points:?}"
    );
    assert!(
        (points[points.len() - 2].1 - points[points.len() - 1].1).abs() <= 0.5,
        "payload→timeline step SVG should finish with a direct horizontal approach into timeline: points={points:?}"
    );
}

#[test]
fn svg_lr_architecture_payload_timeline_smooth_step_avoids_source_shelf() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_intrusion.mmd");
    let edge_idx = edge_index(&diagram, "payload", "timeline");
    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Rounded)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    let d = edge_path_d_for_svg_order(&diagram, &svg, edge_idx);
    assert!(
        d.contains('Q'),
        "payload→timeline smooth-step SVG should use rounded corner commands: d={d}"
    );

    let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
    assert!(
        points.len() >= 4,
        "payload→timeline smooth-step SVG should expose a rounded interior column: points={points:?}, d={d}"
    );
    let start_y = points[0].1;
    let end_y = points[points.len() - 1].1;
    let interior_xs: Vec<f64> = points
        .iter()
        .skip(1)
        .take(points.len().saturating_sub(2))
        .filter(|(_, y)| *y > start_y + 1.0 && *y < end_y - 1.0)
        .map(|(x, _)| *x)
        .collect();
    assert!(
        !interior_xs.is_empty(),
        "payload→timeline smooth-step SVG should contain interior rounded-column samples: points={points:?}, d={d}"
    );
    let min_x = interior_xs.iter().copied().fold(f64::INFINITY, f64::min);
    let max_x = interior_xs
        .iter()
        .copied()
        .fold(f64::NEG_INFINITY, f64::max);
    assert!(
        max_x - min_x <= 1.0,
        "payload→timeline smooth-step SVG should keep one interior vertical column instead of a rounded source shelf: points={points:?}, d={d}"
    );
}

/// Existing LR fan fixtures must remain free of non-endpoint node crossings
/// under step routing after the forward avoidance changes.
#[test]
fn svg_lr_fan_fixtures_no_non_endpoint_crossings_after_forward_fix() {
    for fixture in ["fan_in_lr.mmd", "five_fan_out_lr.mmd", "five_fan_in_lr.mmd"] {
        let diagram = load_flowchart_fixture_diagram(fixture);
        let svg = render_svg(
            &diagram,
            &RenderConfig {
                routing_style: Some(RoutingStyle::Orthogonal),
                curve: Some(Curve::Linear(CornerStyle::Sharp)),
                path_simplification: PathSimplification::None,
                ..Default::default()
            },
        );

        // Check every edge against every non-endpoint node.
        for edge in &diagram.edges {
            if edge.stroke == crate::graph::Stroke::Invisible {
                continue;
            }
            let points = edge_path_for_svg_order(&diagram, &svg, edge.index);
            for (label, rect) in extract_all_node_rects(&svg) {
                if label == node_label(&diagram, &edge.from)
                    || label == node_label(&diagram, &edge.to)
                {
                    continue;
                }
                assert!(
                    !path_crosses_rect_interior(&points, rect, -0.5),
                    "{fixture}: edge {}→{} crosses {label}; points={points:?}, rect={rect:?}",
                    edge.from,
                    edge.to,
                );
            }
        }
    }
}

// ---------------------------------------------------------------------------
// LR terminal contracts + forward hairpins (plan 0123)
// ---------------------------------------------------------------------------

/// Assert that the terminal segment of an edge arrives normal to its endpoint
/// face with at least `min_support` pixels of straight stem.
///
/// Uses existing `svg_terminal_approach_face_relaxed` for face detection and
/// checks axis alignment + stem length of the penultimate→endpoint segment.
fn assert_edge_terminal_is_face_normal_with_min_support(
    diagram: &crate::graph::Graph,
    svg: &str,
    from: &str,
    to: &str,
    min_support: f64,
) {
    let edge_idx = edge_index(diagram, from, to);
    let d = edge_path_d_for_svg_order(diagram, svg, edge_idx);
    let commands = parse_svg_path_command_sequence(&d);

    // For face detection, use densely sampled points (handles cubic curves).
    let sampled = sample_svg_path_commands(&commands, 64);
    assert!(
        sampled.len() >= 2,
        "{from}→{to}: path has fewer than 2 sampled points; d={d}"
    );

    let target_label = node_label(diagram, to);
    let target_rect = node_rect_for_label(svg, &target_label)
        .unwrap_or_else(|| panic!("{from}→{to}: target node '{target_label}' rect not found"));

    // For the terminal stem check, use the last two SVG path command endpoints
    // (not sampled curve points) so cubic smoothing doesn't introduce false
    // axis-deviation.  Command endpoints represent the routing intent.
    let cmd_endpoints: Vec<(f64, f64)> = commands
        .iter()
        .map(|cmd| match cmd {
            SvgPathCommand::Move(p) | SvgPathCommand::Line(p) => *p,
            SvgPathCommand::Cubic(_, _, p) => *p,
        })
        .collect();
    assert!(
        cmd_endpoints.len() >= 2,
        "{from}→{to}: path has fewer than 2 command endpoints; d={d}"
    );

    let end = *cmd_endpoints.last().unwrap();
    let pen = cmd_endpoints[cmd_endpoints.len() - 2];

    // Use the existing relaxed face detector on sampled points (handles curves).
    let face = svg_terminal_approach_face_relaxed(target_rect, &sampled);

    let dx = (end.0 - pen.0).abs();
    let dy = (end.1 - pen.1).abs();

    match face {
        "left" | "right" => {
            // Terminal segment must be horizontal (dy ≈ 0) with enough stem.
            assert!(
                dy <= 1.0,
                "{from}→{to}: terminal approaches {face} face but stem is not horizontal; \
                 pen=({:.1},{:.1}) end=({:.1},{:.1}) dy={dy:.1}",
                pen.0,
                pen.1,
                end.0,
                end.1,
            );
            assert!(
                dx >= min_support,
                "{from}→{to}: terminal stem on {face} face too short; \
                 dx={dx:.1} < min_support={min_support}",
            );
        }
        "top" | "bottom" => {
            // Terminal segment must be vertical (dx ≈ 0) with enough stem.
            assert!(
                dx <= 1.0,
                "{from}→{to}: terminal approaches {face} face but stem is not vertical; \
                 pen=({:.1},{:.1}) end=({:.1},{:.1}) dx={dx:.1}",
                pen.0,
                pen.1,
                end.0,
                end.1,
            );
            assert!(
                dy >= min_support,
                "{from}→{to}: terminal stem on {face} face too short; \
                 dy={dy:.1} < min_support={min_support}",
            );
        }
        _ => {
            panic!(
                "{from}→{to}: could not determine endpoint face; \
                 face='{face}' end=({:.1},{:.1}) rect={target_rect:?}",
                end.0, end.1,
            );
        }
    }
}

/// Assert all sampled path points remain within the SVG viewBox.
fn sampled_path_stays_within_view_box(
    points: &[(f64, f64)],
    view_box: (f64, f64, f64, f64),
    eps: f64,
) -> bool {
    let (min_x, min_y, width, height) = view_box;
    let max_x = min_x + width;
    let max_y = min_y + height;
    points
        .iter()
        .all(|&(x, y)| x >= min_x - eps && x <= max_x + eps && y >= min_y - eps && y <= max_y + eps)
}

/// Convenience wrapper: parse viewBox as (min_x, min_y, width, height).
fn svg_view_box(svg: &str) -> Option<(f64, f64, f64, f64)> {
    parse_svg_viewbox(svg)
}

// -- Plan 0123, Task 1.2: Helper micro-test --

/// Verify the terminal-contract helper works on a known-good edge from the
/// 0122 fixture where `graph→format` arrives at the left face cleanly.
#[test]
fn svg_terminal_contract_helpers_identify_faces_and_terminal_axis() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_intrusion.mmd");
    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );
    // graph→format arrives at format's left face with a clean horizontal stem.
    assert_edge_terminal_is_face_normal_with_min_support(&diagram, &svg, "graph", "format", 8.0);
}

// -- Plan 0123, Task 1.1: Red tests --

#[test]
fn svg_lr_architecture_terminal_contracts_step_heavy_targets_are_face_normal_and_have_min_stem() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_terminal_contracts.mmd");
    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    // Edges known to have wrong-face terminals on current HEAD.
    let checks = [
        ("mmds", "graph1"),
        ("render", "graph1"),
        ("registry", "errors"),
        ("runtime", "timeline"),
    ];

    for (from, to) in checks {
        assert_edge_terminal_is_face_normal_with_min_support(&diagram, &svg, from, to, 8.0);
    }
}

/// Verify terminal contract across all orthogonal presets.  Step gets the
/// strict axis-alignment + min-support check.  Smooth-step and curved-step
/// share the same routing but their SVG curve rendering distorts the terminal
/// (rounded corners / basis interpolation), so we verify approach direction
/// only: the endpoint's face should match across presets.
#[test]
fn svg_lr_architecture_terminal_contracts_all_orthogonal_presets_face_normal() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_terminal_contracts.mmd");

    let presets: &[(RoutingStyle, Curve, &str)] = &[
        (
            RoutingStyle::Orthogonal,
            Curve::Linear(CornerStyle::Sharp),
            "step",
        ),
        (
            RoutingStyle::Orthogonal,
            Curve::Linear(CornerStyle::Rounded),
            "smooth-step",
        ),
        (RoutingStyle::Orthogonal, Curve::Basis, "curved-step"),
    ];

    let edges = [("mmds", "graph1"), ("registry", "errors")];

    for &(routing, curve, label) in presets {
        let svg = render_svg(
            &diagram,
            &RenderConfig {
                routing_style: Some(routing),
                curve: Some(curve),
                path_simplification: PathSimplification::None,
                ..Default::default()
            },
        );

        for (from, to) in edges {
            if matches!(curve, Curve::Linear(CornerStyle::Sharp)) {
                // Step: strict axis alignment + min support.
                assert_edge_terminal_is_face_normal_with_min_support(&diagram, &svg, from, to, 8.0);
            } else {
                // Curved presets: verify the approach face is correct (same
                // routing → same face), but don't enforce strict axis alignment
                // since the curve rendering distorts the terminal segment.
                let edge_idx = edge_index(&diagram, from, to);
                let d = edge_path_d_for_svg_order(&diagram, &svg, edge_idx);
                let sampled = sample_svg_path_commands(&parse_svg_path_command_sequence(&d), 64);
                let target_label = node_label(&diagram, to);
                let target_rect = node_rect_for_label(&svg, &target_label)
                    .unwrap_or_else(|| panic!("{label} {from}→{to}: target rect not found"));
                let face = svg_terminal_approach_face_relaxed(target_rect, &sampled);
                assert!(
                    face == "left" || face == "top" || face == "bottom",
                    "{label} {from}→{to}: expected left/top/bottom approach, got '{face}'"
                );
            }
        }
    }
}

/// Verify that edge endpoints remain on the target node boundary after
/// forward reroutes (no post-reroute drift).
#[test]
fn svg_lr_architecture_terminal_contracts_endpoints_remain_on_target_boundary() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_terminal_contracts.mmd");
    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    for (from, to) in [
        ("diagrams", "errors"),
        ("registry", "errors"),
        ("mmds", "graph1"),
        ("render", "graph1"),
    ] {
        let edge_idx = edge_index(&diagram, from, to);
        let points = edge_path_for_svg_order(&diagram, &svg, edge_idx);
        let end = *points.last().unwrap();
        let target_label = node_label(&diagram, to);
        let target_rect = node_rect_for_label(&svg, &target_label)
            .unwrap_or_else(|| panic!("{from}→{to}: target rect not found"));
        let (rx, ry, rw, rh) = target_rect;
        // Tolerance accounts for SVG arrowhead marker offset (refX ≈ 5px):
        // the path endpoint sits slightly before the node boundary so the
        // marker tip lands on the face.
        let eps = 6.0;
        let on_boundary = (end.0 - rx).abs() <= eps
            || (end.0 - (rx + rw)).abs() <= eps
            || (end.1 - ry).abs() <= eps
            || (end.1 - (ry + rh)).abs() <= eps;
        assert!(
            on_boundary,
            "{from}→{to}: endpoint ({:.1},{:.1}) is not on target boundary; rect={target_rect:?}",
            end.0, end.1,
        );
    }
}

#[test]
fn svg_lr_architecture_hairpin_diagrams_to_errors_does_not_exit_viewbox() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_terminal_contracts.mmd");
    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    let view = svg_view_box(&svg).expect("viewBox should exist");
    let d = edge_path_d_for_svg_order(&diagram, &svg, edge_index(&diagram, "diagrams", "errors"));
    let sampled = sample_svg_path_commands(&parse_svg_path_command_sequence(&d), 64);

    assert!(
        sampled_path_stays_within_view_box(&sampled, view, 0.5),
        "diagrams→errors should not exit viewBox; d={d}"
    );
}

#[test]
fn svg_lr_architecture_hairpin_no_primary_axis_reversal_on_diagrams_to_errors() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_terminal_contracts.mmd");
    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );

    let points =
        edge_path_for_svg_order(&diagram, &svg, edge_index(&diagram, "diagrams", "errors"));
    let has_x_reversal = points.windows(2).any(|w| w[1].0 < w[0].0 - 0.5);
    assert!(
        !has_x_reversal,
        "diagrams→errors should not reverse along x; points={points:?}"
    );
}

// ---------------------------------------------------------------------------
// LR target-node transit avoidance (plan 0124)
// ---------------------------------------------------------------------------

/// Assert that no segment of an edge path crosses the target node's rect
/// interior.  Uses `path_crosses_rect_interior` (axis-aligned segment check)
/// with the caller-provided margin.
fn assert_edge_does_not_transit_target_rect_interior(
    diagram: &crate::graph::Graph,
    svg: &str,
    from: &str,
    to: &str,
    interior_margin: f64,
) {
    let edge_idx = edge_index(diagram, from, to);
    let target_label = node_label(diagram, to);
    let target_rect = node_rect_for_label(svg, &target_label)
        .unwrap_or_else(|| panic!("{from}→{to}: target rect '{target_label}' not found"));

    let points = edge_path_for_svg_order(diagram, svg, edge_idx);
    assert!(points.len() >= 2, "{from}→{to}: expected at least 2 points");

    assert!(
        !path_crosses_rect_interior(&points, target_rect, interior_margin),
        "{from}→{to}: route crosses target node '{target_label}' interior; \
         points={points:?}, rect={target_rect:?}"
    );
}

// -- Plan 0124, Task 1.1: Red tests --

#[test]
fn svg_lr_architecture_target_transit_mermaid_to_errors_does_not_cross_errors_interior() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_terminal_contracts.mmd");
    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );
    assert_edge_does_not_transit_target_rect_interior(&diagram, &svg, "mermaid", "errors", -0.5);
}

#[test]
fn svg_lr_architecture_target_transit_runtime_to_errors_does_not_cross_errors_interior() {
    let diagram = load_flowchart_fixture_diagram("architecture_graph_lr_terminal_contracts.mmd");
    let svg = render_svg(
        &diagram,
        &RenderConfig {
            routing_style: Some(RoutingStyle::Orthogonal),
            curve: Some(Curve::Linear(CornerStyle::Sharp)),
            path_simplification: PathSimplification::None,
            ..Default::default()
        },
    );
    assert_edge_does_not_transit_target_rect_interior(&diagram, &svg, "runtime", "errors", -0.5);
}

#[test]
fn svg_root_stays_transparent_when_no_theme_is_selected() {
    let flowchart =
        parse_flowchart("graph TD\nA[Start] --> B[End]\n").expect("inline flowchart should parse");
    let diagram = compile_to_graph(&flowchart);
    let svg = render_svg(&diagram, &RenderConfig::default());

    assert!(
        svg.contains("background-color: transparent;"),
        "default SVG root should stay transparent: {svg}"
    );
    assert!(
        !svg.contains("--bg:"),
        "default SVG root should not emit theme variables: {svg}"
    );
}