vexy-vsvg-plugin-sdk 2.3.1

Plugin SDK for vexy-vsvg
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
// this_file: crates/vexy-vsvg-plugin-sdk/src/plugins/convert_path_data/mod.rs

//! Optimizes SVG path data for maximum compression.
//!
//! This plugin is the heart of Vexy Vsvg's path optimization, porting SVGO's `convertPathData`.
//! It applies multiple transformations to make path data as compact as possible while
//! preserving visual appearance within tolerance.
//!
//! ## What it does
//!
//! 1. **Smart coordinate system**: Chooses absolute vs relative for each command based on which is shorter
//! 2. **Removes redundant commands**: `L 10 10` to current position → deleted
//! 3. **Collapses repeated commands**: `h 5 h 10` → `h 15` (when safe)
//! 4. **Precision control**: Rounds coordinates to configurable decimal places
//! 5. **Geometric simplifications** (optional):
//!    - **Straightens curves**: Nearly-straight Béziers → `L` commands
//!    - **Converts cubic to quadratic**: When a quadratic curve approximates well enough
//!    - **Converts curves to arcs**: When a curve is actually circular
//!
//! ## Configuration
//!
//! - `floatPrecision` (default: `3`) — Decimal places for coordinates
//! - `transformPrecision` (default: `5`) — Decimal places for transforms (more sensitive)
//! - `removeUseless` (default: `true`) — Remove no-op commands
//! - `collapseRepeated` (default: `true`) — Merge adjacent same-type commands
//! - `utilizeAbsolute` (default: `true`) — Choose absolute vs relative dynamically
//! - `leadingZero` (default: `true`) — Keep `0.5` vs `.5`
//! - `negativeExtraSpace` (default: `true`) — Add space before negative: `10-5` vs `10 -5`
//! - `straightCurves` (default: `false`) — Convert nearly-straight curves to lines
//! - `convertToQ` (default: `false`) — Convert cubic Béziers to quadratic when possible
//! - `makeArcs` (default: `false`) — Convert curves to arc commands when circular
//!
//! ## Reference
//!
//! SVGO's `convertPathData` plugin.

pub mod abs_to_rel;
pub mod normalize;
pub mod rel_to_abs;

use crate::Plugin;
use anyhow::Result;
use lyon::geom::{CubicBezierSegment, Point, QuadraticBezierSegment, Vector};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vexy_vsvg::ast::{Document, Element, Node};

/// Default decimal precision for path coordinates
const DEFAULT_FLOAT_PRECISION: u8 = 3;

/// Default decimal precision for transform values
const DEFAULT_TRANSFORM_PRECISION: u8 = 5;

/// Configuration for path data optimization.
///
/// All options balance file size vs visual quality. Aggressive settings can introduce
/// visible distortion, so test with your specific content.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ConvertPathDataConfig {
    #[serde(default = "default_float_precision")]
    pub float_precision: u8,

    #[serde(default = "default_transform_precision")]
    pub transform_precision: u8,

    #[serde(default = "default_true")]
    pub remove_useless: bool,

    #[serde(default = "default_true")]
    pub collapse_repeated: bool,

    #[serde(default = "default_true")]
    pub utilize_absolute: bool,

    #[serde(default = "default_true")]
    pub leading_zero: bool,

    #[serde(default = "default_true")]
    pub negative_extra_space: bool,

    /// Convert curves to arcs where geometrically appropriate
    #[serde(default)]
    pub make_arcs: MakeArcsConfig,

    /// Straighten curves that are nearly straight lines
    #[serde(default = "default_false")]
    pub straight_curves: bool,

    /// Convert cubic bezier curves to quadratic where possible
    #[serde(default = "default_false")]
    pub convert_to_q: bool,

    /// Tolerance for curve straightening (smaller = more strict)
    #[serde(default = "default_curve_tolerance")]
    pub curve_tolerance: f64,

    /// Tolerance for arc detection (smaller = more strict)
    #[serde(default = "default_arc_tolerance")]
    pub arc_tolerance: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MakeArcsConfig {
    Enabled(bool),
    Params(MakeArcsParams),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MakeArcsParams {
    #[serde(default = "default_make_arcs_threshold")]
    pub threshold: f64,
    #[serde(default = "default_make_arcs_tolerance")]
    pub tolerance: f64,
}

impl MakeArcsConfig {
    fn is_enabled(&self) -> bool {
        match self {
            Self::Enabled(enabled) => *enabled,
            Self::Params(_) => true,
        }
    }

    fn tolerance(&self, default_tolerance: f64) -> f64 {
        match self {
            Self::Params(params) => params.tolerance,
            Self::Enabled(_) => default_tolerance,
        }
    }
}

impl Default for MakeArcsConfig {
    fn default() -> Self {
        Self::Enabled(false)
    }
}

fn default_float_precision() -> u8 {
    DEFAULT_FLOAT_PRECISION
}

fn default_transform_precision() -> u8 {
    DEFAULT_TRANSFORM_PRECISION
}

fn default_true() -> bool {
    true
}

fn default_false() -> bool {
    false
}

fn default_curve_tolerance() -> f64 {
    0.1
}

fn default_arc_tolerance() -> f64 {
    0.5
}

fn default_make_arcs_threshold() -> f64 {
    2.5
}

fn default_make_arcs_tolerance() -> f64 {
    0.5
}

impl Default for ConvertPathDataConfig {
    fn default() -> Self {
        Self {
            float_precision: default_float_precision(),
            transform_precision: default_transform_precision(),
            remove_useless: true,
            collapse_repeated: true,
            utilize_absolute: true,
            leading_zero: true,
            negative_extra_space: true,
            make_arcs: MakeArcsConfig::default(),
            straight_curves: false,
            convert_to_q: false,
            curve_tolerance: default_curve_tolerance(),
            arc_tolerance: default_arc_tolerance(),
        }
    }
}

/// SVGO's `convertPathData` plugin ported to Rust.
///
/// Applies multiple optimization passes to `<path>` elements' `d` attributes.
pub struct ConvertPathDataPlugin {
    config: ConvertPathDataConfig,
}

impl ConvertPathDataPlugin {
    pub fn new() -> Self {
        Self {
            config: ConvertPathDataConfig::default(),
        }
    }

    pub fn with_config(config: ConvertPathDataConfig) -> Self {
        Self { config }
    }

    fn parse_config(params: &Value) -> Result<ConvertPathDataConfig> {
        if params.is_null() {
            Ok(ConvertPathDataConfig::default())
        } else {
            serde_json::from_value(params.clone())
                .map_err(|e| anyhow::anyhow!("Invalid plugin configuration: {}", e))
        }
    }

    /// Recursively optimize paths in an element and its children
    fn optimize_paths_in_element(&self, element: &mut Element) {
        // Process this element if it's a path
        if element.name == "path" {
            if let Some(d) = element.attr("d") {
                match optimize_path_data(d, &self.config) {
                    Ok(optimized) => {
                        element.set_attr("d", &optimized);
                    }
                    Err(e) => {
                        // Log error but continue processing other paths
                        eprintln!("Warning: Failed to optimize path data: {}", e);
                    }
                }
            }
        }

        // Process children
        let mut i = 0;
        while i < element.children.len() {
            if let Node::Element(child) = &mut element.children[i] {
                self.optimize_paths_in_element(child);
            }
            i += 1;
        }
    }
}

impl Default for ConvertPathDataPlugin {
    fn default() -> Self {
        Self::new()
    }
}

impl Plugin for ConvertPathDataPlugin {
    fn name(&self) -> &'static str {
        "convertPathData"
    }

    fn description(&self) -> &'static str {
        "converts path data to relative or absolute, optimizes segments, simplifies curves"
    }

    fn validate_params(&self, params: &Value) -> Result<()> {
        Self::parse_config(params)?;
        Ok(())
    }

    fn configure(&mut self, params: &Value) -> Result<()> {
        self.config = Self::parse_config(params)?;
        Ok(())
    }

    fn apply(&self, document: &mut Document) -> Result<()> {
        self.optimize_paths_in_element(&mut document.root);
        Ok(())
    }
}

/// Internal representation of path command types during optimization.
#[derive(Debug, Clone, Copy, PartialEq)]
enum CommandType {
    MoveTo,
    LineTo,
    HorizontalLineTo,
    VerticalLineTo,
    CurveTo,
    SmoothCurveTo,
    QuadraticBezier,
    SmoothQuadraticBezier,
    Arc,
    ClosePath,
}

/// Internal command representation during optimization pipeline.
#[derive(Debug, Clone)]
struct PathCommand {
    cmd_type: CommandType,
    is_absolute: bool,
    params: Vec<f64>,
}

impl PathCommand {
    /// Get the command character
    fn get_char(&self) -> char {
        match (self.cmd_type, self.is_absolute) {
            (CommandType::MoveTo, true) => 'M',
            (CommandType::MoveTo, false) => 'm',
            (CommandType::LineTo, true) => 'L',
            (CommandType::LineTo, false) => 'l',
            (CommandType::HorizontalLineTo, true) => 'H',
            (CommandType::HorizontalLineTo, false) => 'h',
            (CommandType::VerticalLineTo, true) => 'V',
            (CommandType::VerticalLineTo, false) => 'v',
            (CommandType::CurveTo, true) => 'C',
            (CommandType::CurveTo, false) => 'c',
            (CommandType::SmoothCurveTo, true) => 'S',
            (CommandType::SmoothCurveTo, false) => 's',
            (CommandType::QuadraticBezier, true) => 'Q',
            (CommandType::QuadraticBezier, false) => 'q',
            (CommandType::SmoothQuadraticBezier, true) => 'T',
            (CommandType::SmoothQuadraticBezier, false) => 't',
            (CommandType::Arc, true) => 'A',
            (CommandType::Arc, false) => 'a',
            (CommandType::ClosePath, _) => 'z',
        }
    }
}

/// Parse a path data string into commands
fn parse_path_data(path_data: &str) -> Result<Vec<PathCommand>> {
    let mut commands = Vec::new();
    let mut chars = path_data.chars().peekable();
    let mut current_nums = Vec::new();
    let mut current_num = String::new();
    let mut last_cmd_type = None;
    let mut in_number = false;
    let mut in_exponent = false;
    let mut seen_decimal = false;

    for ch in chars.by_ref() {
        match ch {
            'M' | 'm' | 'L' | 'l' | 'H' | 'h' | 'V' | 'v' | 'C' | 'c' | 'S' | 's' | 'Q' | 'q'
            | 'T' | 't' | 'A' | 'a' | 'Z' | 'z' => {
                if !current_num.is_empty() {
                    if let Ok(num) = current_num.parse::<f64>() {
                        current_nums.push(num);
                    }
                    current_num.clear();
                    in_number = false;
                    in_exponent = false;
                    seen_decimal = false;
                }

                if let Some(cmd_type) = last_cmd_type {
                    process_accumulated_params(&mut commands, cmd_type, &mut current_nums)?;
                }

                let (cmd_type, is_absolute) = parse_command_char(ch)?;

                if cmd_type == CommandType::ClosePath {
                    commands.push(PathCommand {
                        cmd_type,
                        is_absolute: true,
                        params: vec![],
                    });
                    last_cmd_type = None;
                } else {
                    last_cmd_type = Some((cmd_type, is_absolute));
                }
            }
            '0'..='9' | '.' | '-' | '+' | 'e' | 'E' => {
                if ch == '-' || ch == '+' {
                    // Handle sign changes
                    // Sign after 'e' or 'E' starts exponent, not new number
                    // If we're in a number and see a sign NOT in exponent, it's a new number
                    if !current_num.is_empty() && in_number && !in_exponent {
                        if let Ok(num) = current_num.parse::<f64>() {
                            current_nums.push(num);
                        }
                        current_num.clear();
                        in_exponent = false;
                        seen_decimal = false;
                    }
                    current_num.push(ch);
                } else if ch == '.' {
                    if !current_num.is_empty() && in_number && seen_decimal && !in_exponent {
                        if let Ok(num) = current_num.parse::<f64>() {
                            current_nums.push(num);
                        }
                        current_num.clear();
                        in_exponent = false;
                    }
                    current_num.push(ch);
                    seen_decimal = true;
                } else if ch == 'e' || ch == 'E' {
                    current_num.push(ch);
                    in_exponent = true;
                } else {
                    current_num.push(ch);
                }
                in_number = true;
            }
            ' ' | ',' | '\t' | '\n' | '\r' => {
                if !current_num.is_empty() {
                    if let Ok(num) = current_num.parse::<f64>() {
                        current_nums.push(num);
                    }
                    current_num.clear();
                    in_number = false;
                    in_exponent = false;
                    seen_decimal = false;
                }
            }
            _ => {}
        }
    }

    if !current_num.is_empty() {
        if let Ok(num) = current_num.parse::<f64>() {
            current_nums.push(num);
        }
    }

    if let Some(cmd_type) = last_cmd_type {
        process_accumulated_params(&mut commands, cmd_type, &mut current_nums)?;
    }

    Ok(commands)
}

/// Parse a command character into its type and whether it's absolute
fn parse_command_char(ch: char) -> Result<(CommandType, bool)> {
    match ch {
        'M' => Ok((CommandType::MoveTo, true)),
        'm' => Ok((CommandType::MoveTo, false)),
        'L' => Ok((CommandType::LineTo, true)),
        'l' => Ok((CommandType::LineTo, false)),
        'H' => Ok((CommandType::HorizontalLineTo, true)),
        'h' => Ok((CommandType::HorizontalLineTo, false)),
        'V' => Ok((CommandType::VerticalLineTo, true)),
        'v' => Ok((CommandType::VerticalLineTo, false)),
        'C' => Ok((CommandType::CurveTo, true)),
        'c' => Ok((CommandType::CurveTo, false)),
        'S' => Ok((CommandType::SmoothCurveTo, true)),
        's' => Ok((CommandType::SmoothCurveTo, false)),
        'Q' => Ok((CommandType::QuadraticBezier, true)),
        'q' => Ok((CommandType::QuadraticBezier, false)),
        'T' => Ok((CommandType::SmoothQuadraticBezier, true)),
        't' => Ok((CommandType::SmoothQuadraticBezier, false)),
        'A' => Ok((CommandType::Arc, true)),
        'a' => Ok((CommandType::Arc, false)),
        'Z' | 'z' => Ok((CommandType::ClosePath, true)),
        _ => Err(anyhow::anyhow!("Unknown command character: {}", ch)),
    }
}

/// Process accumulated parameters for a command type
fn process_accumulated_params(
    commands: &mut Vec<PathCommand>,
    (cmd_type, is_absolute): (CommandType, bool),
    params: &mut Vec<f64>,
) -> Result<()> {
    let expected = match cmd_type {
        CommandType::MoveTo | CommandType::LineTo => 2,
        CommandType::HorizontalLineTo | CommandType::VerticalLineTo => 1,
        CommandType::CurveTo => 6,
        CommandType::SmoothCurveTo | CommandType::QuadraticBezier => 4,
        CommandType::SmoothQuadraticBezier => 2,
        CommandType::Arc => 7,
        CommandType::ClosePath => 0,
    };

    if expected == 0 {
        return Ok(());
    }

    // Process params in chunks
    while params.len() >= expected {
        let chunk: Vec<f64> = params.drain(..expected).collect();

        // Special case: MoveTo followed by implicit LineTo
        let actual_cmd_type = if cmd_type == CommandType::MoveTo && !commands.is_empty() {
            CommandType::LineTo
        } else {
            cmd_type
        };

        commands.push(PathCommand {
            cmd_type: actual_cmd_type,
            is_absolute,
            params: chunk,
        });
    }

    if !params.is_empty() {
        // Leftover params - this is technically an error but we'll ignore them
        params.clear();
    }

    Ok(())
}

/// Main optimization pipeline: parse → optimize → stringify.
///
/// 1. Parse path string to commands
/// 2. Normalize all to absolute coordinates
/// 3. Apply optimization passes (remove useless, collapse repeated, geometric transforms)
/// 4. Choose absolute vs relative per command for shortest output
/// 5. Stringify back to path data
fn optimize_path_data(path_data: &str, config: &ConvertPathDataConfig) -> Result<String> {
    // Parse path data
    let mut commands = parse_path_data(path_data)?;

    // Track current position for relative/absolute conversions
    let mut current_x = 0.0;
    let mut current_y = 0.0;
    let mut start_x = 0.0;
    let mut start_y = 0.0;

    // Convert to absolute coordinates for processing
    for cmd in &mut commands {
        match cmd.cmd_type {
            CommandType::MoveTo => {
                if !cmd.is_absolute && cmd.params.len() >= 2 {
                    cmd.params[0] += current_x;
                    cmd.params[1] += current_y;
                    cmd.is_absolute = true;
                }
                if cmd.params.len() >= 2 {
                    current_x = cmd.params[0];
                    current_y = cmd.params[1];
                    start_x = current_x;
                    start_y = current_y;
                }
            }
            CommandType::LineTo => {
                if !cmd.is_absolute && cmd.params.len() >= 2 {
                    cmd.params[0] += current_x;
                    cmd.params[1] += current_y;
                    cmd.is_absolute = true;
                }
                if cmd.params.len() >= 2 {
                    current_x = cmd.params[0];
                    current_y = cmd.params[1];
                }
            }
            CommandType::HorizontalLineTo => {
                if !cmd.is_absolute && !cmd.params.is_empty() {
                    cmd.params[0] += current_x;
                    cmd.is_absolute = true;
                }
                if !cmd.params.is_empty() {
                    current_x = cmd.params[0];
                }
            }
            CommandType::VerticalLineTo => {
                if !cmd.is_absolute && !cmd.params.is_empty() {
                    cmd.params[0] += current_y;
                    cmd.is_absolute = true;
                }
                if !cmd.params.is_empty() {
                    current_y = cmd.params[0];
                }
            }
            CommandType::CurveTo => {
                if !cmd.is_absolute && cmd.params.len() >= 6 {
                    cmd.params[0] += current_x;
                    cmd.params[1] += current_y;
                    cmd.params[2] += current_x;
                    cmd.params[3] += current_y;
                    cmd.params[4] += current_x;
                    cmd.params[5] += current_y;
                    cmd.is_absolute = true;
                }
                if cmd.params.len() >= 6 {
                    current_x = cmd.params[4];
                    current_y = cmd.params[5];
                }
            }
            CommandType::SmoothCurveTo => {
                if !cmd.is_absolute && cmd.params.len() >= 4 {
                    cmd.params[0] += current_x;
                    cmd.params[1] += current_y;
                    cmd.params[2] += current_x;
                    cmd.params[3] += current_y;
                    cmd.is_absolute = true;
                }
                if cmd.params.len() >= 4 {
                    current_x = cmd.params[2];
                    current_y = cmd.params[3];
                }
            }
            CommandType::QuadraticBezier => {
                if !cmd.is_absolute && cmd.params.len() >= 4 {
                    cmd.params[0] += current_x;
                    cmd.params[1] += current_y;
                    cmd.params[2] += current_x;
                    cmd.params[3] += current_y;
                    cmd.is_absolute = true;
                }
                if cmd.params.len() >= 4 {
                    current_x = cmd.params[2];
                    current_y = cmd.params[3];
                }
            }
            CommandType::SmoothQuadraticBezier => {
                if !cmd.is_absolute && cmd.params.len() >= 2 {
                    cmd.params[0] += current_x;
                    cmd.params[1] += current_y;
                    cmd.is_absolute = true;
                }
                if cmd.params.len() >= 2 {
                    current_x = cmd.params[0];
                    current_y = cmd.params[1];
                }
            }
            CommandType::Arc => {
                if !cmd.is_absolute && cmd.params.len() >= 7 {
                    cmd.params[5] += current_x;
                    cmd.params[6] += current_y;
                    cmd.is_absolute = true;
                }
                if cmd.params.len() >= 7 {
                    current_x = cmd.params[5];
                    current_y = cmd.params[6];
                }
            }
            CommandType::ClosePath => {
                current_x = start_x;
                current_y = start_y;
            }
        }
    }

    // Apply optimizations
    if config.remove_useless {
        commands = remove_useless_commands(commands);
    }

    if config.collapse_repeated {
        commands = collapse_repeated_commands(commands);
    }

    // Apply advanced geometric optimizations
    if config.straight_curves {
        commands = straighten_curves(commands, config.curve_tolerance);
    }

    if config.convert_to_q {
        commands = convert_cubic_to_quadratic(commands, config.curve_tolerance);
    }

    if config.make_arcs.is_enabled() {
        commands =
            convert_curves_to_arcs(commands, config.make_arcs.tolerance(config.arc_tolerance));
    }

    // Convert back to string
    stringify_commands(
        &commands,
        config.float_precision,
        config.utilize_absolute,
        config.leading_zero,
        config.negative_extra_space,
    )
}

/// Removes no-op commands that don't change the path.
///
/// Examples: `L 10 10` when already at (10,10), `H 20` when x is already 20.
fn remove_useless_commands(mut commands: Vec<PathCommand>) -> Vec<PathCommand> {
    let mut result = Vec::new();
    let mut current_x = 0.0;
    let mut current_y = 0.0;

    for cmd in commands.drain(..) {
        let mut keep = true;

        match cmd.cmd_type {
            CommandType::LineTo => {
                if cmd.params.len() >= 2 {
                    // Remove LineTo that goes to current position
                    if (cmd.params[0] - current_x).abs() < f64::EPSILON
                        && (cmd.params[1] - current_y).abs() < f64::EPSILON
                    {
                        keep = false;
                    } else {
                        current_x = cmd.params[0];
                        current_y = cmd.params[1];
                    }
                }
            }
            CommandType::HorizontalLineTo => {
                if !cmd.params.is_empty() {
                    if (cmd.params[0] - current_x).abs() < f64::EPSILON {
                        keep = false;
                    } else {
                        current_x = cmd.params[0];
                    }
                }
            }
            CommandType::VerticalLineTo => {
                if !cmd.params.is_empty() {
                    if (cmd.params[0] - current_y).abs() < f64::EPSILON {
                        keep = false;
                    } else {
                        current_y = cmd.params[0];
                    }
                }
            }
            CommandType::MoveTo => {
                if cmd.params.len() >= 2 {
                    current_x = cmd.params[0];
                    current_y = cmd.params[1];
                }
            }
            CommandType::CurveTo => {
                if cmd.params.len() >= 6 {
                    current_x = cmd.params[4];
                    current_y = cmd.params[5];
                }
            }
            CommandType::SmoothCurveTo => {
                if cmd.params.len() >= 4 {
                    current_x = cmd.params[2];
                    current_y = cmd.params[3];
                }
            }
            CommandType::QuadraticBezier => {
                if cmd.params.len() >= 4 {
                    current_x = cmd.params[2];
                    current_y = cmd.params[3];
                }
            }
            CommandType::SmoothQuadraticBezier => {
                if cmd.params.len() >= 2 {
                    current_x = cmd.params[0];
                    current_y = cmd.params[1];
                }
            }
            CommandType::Arc => {
                if cmd.params.len() >= 7 {
                    current_x = cmd.params[5];
                    current_y = cmd.params[6];
                }
            }
            _ => {}
        }

        if keep {
            result.push(cmd);
        }
    }

    result
}

/// Merges consecutive commands of the same type when safe.
///
/// Examples:
/// - `h 10 h 20` → `h 30` (both positive)
/// - `m 5 5 m 10 10` → `m 15 15` (relative moveto)
///
/// Only collapses when both values have the same sign to avoid introducing errors.
fn collapse_repeated_commands(commands: Vec<PathCommand>) -> Vec<PathCommand> {
    if commands.is_empty() {
        return commands;
    }

    let mut result = Vec::new();
    let mut current_x = 0.0;
    let mut current_y = 0.0;
    let mut i = 0;

    while i < commands.len() {
        let cmd = commands[i].clone();

        // Check if this command can be collapsed with the previous one
        if i > 0 && can_collapse_commands(&result[result.len() - 1], &cmd) {
            let len = result.len();
            let prev_cmd = &mut result[len - 1];

            // Collapse the commands based on type
            match cmd.cmd_type {
                CommandType::MoveTo => {
                    // m 10 20 m 5 5 -> m 15 25
                    if cmd.params.len() >= 2 {
                        prev_cmd.params[0] += cmd.params[0];
                        prev_cmd.params[1] += cmd.params[1];
                    }
                }
                CommandType::LineTo => {
                    // Consecutive line commands can be collapsed into a single command
                    // l 10 20 l 5 5 -> l 15 25 (for relative)
                    if cmd.params.len() >= 2 && !cmd.is_absolute {
                        prev_cmd.params[0] += cmd.params[0];
                        prev_cmd.params[1] += cmd.params[1];
                    } else {
                        // For absolute commands, we can't simply add the values
                        result.push(cmd);
                    }
                }
                CommandType::HorizontalLineTo => {
                    // h 10 h 20 -> h 30 (if same sign)
                    if !cmd.params.is_empty() {
                        prev_cmd.params[0] += cmd.params[0];
                    }
                }
                CommandType::VerticalLineTo => {
                    // v 10 v 20 -> v 30 (if same sign)
                    if !cmd.params.is_empty() {
                        prev_cmd.params[0] += cmd.params[0];
                    }
                }
                _ => {
                    // For other commands, just add this one
                    result.push(cmd);
                }
            }
        } else {
            result.push(cmd);
        }

        // Update position tracking
        if let Some(last_cmd) = result.last() {
            update_position(last_cmd, &mut current_x, &mut current_y);
        }

        i += 1;
    }

    result
}

/// Check if two commands can be collapsed together
fn can_collapse_commands(prev: &PathCommand, current: &PathCommand) -> bool {
    // Commands must be of the same type
    if prev.cmd_type != current.cmd_type {
        return false;
    }

    // Commands must have same absolute/relative nature
    if prev.is_absolute != current.is_absolute {
        return false;
    }

    // Only collapse specific command types
    match current.cmd_type {
        CommandType::MoveTo => {
            // Can always collapse moveto commands
            true
        }
        CommandType::LineTo => {
            // Can collapse relative LineTo commands
            // Don't collapse absolute LineTo as they set specific positions
            !current.is_absolute
        }
        CommandType::HorizontalLineTo => {
            // Can collapse if both values have the same sign (both positive or both negative)
            if prev.params.is_empty() || current.params.is_empty() {
                return false;
            }
            (prev.params[0] >= 0.0) == (current.params[0] >= 0.0)
        }
        CommandType::VerticalLineTo => {
            // Can collapse if both values have the same sign (both positive or both negative)
            if prev.params.is_empty() || current.params.is_empty() {
                return false;
            }
            (prev.params[0] >= 0.0) == (current.params[0] >= 0.0)
        }
        _ => false, // Don't collapse other command types
    }
}

/// Convert commands back to string format
fn stringify_commands(
    commands: &[PathCommand],
    precision: u8,
    utilize_absolute: bool,
    leading_zero: bool,
    negative_extra_space: bool,
) -> Result<String> {
    let mut result = String::new();
    let mut last_cmd_char = '\0';
    let mut current_x = 0.0;
    let mut current_y = 0.0;

    for (i, cmd) in commands.iter().enumerate() {
        // Decide whether to use absolute or relative
        let mut use_absolute = cmd.is_absolute;
        if utilize_absolute && i > 0 {
            // Calculate which is shorter
            use_absolute = should_use_absolute(cmd, current_x, current_y, precision);
        }

        // Get the command character
        let cmd_char = if use_absolute {
            cmd.get_char().to_ascii_uppercase()
        } else {
            cmd.get_char().to_ascii_lowercase()
        };

        // Add command character if different from last
        if cmd_char != last_cmd_char || cmd.cmd_type == CommandType::MoveTo {
            if !result.is_empty() && cmd_char != 'Z' && cmd_char != 'z' {
                result.push(' ');
            }
            result.push(cmd_char);
            last_cmd_char = cmd_char;
        } else if !result.is_empty() {
            result.push(' ');
        }

        // Add parameters
        let params = if use_absolute {
            cmd.params.clone()
        } else {
            convert_to_relative(cmd, current_x, current_y)
        };

        for (j, &param) in params.iter().enumerate() {
            if j > 0 || (cmd_char != last_cmd_char && cmd_char != 'Z' && cmd_char != 'z') {
                // Add space before parameter unless it's negative and we're saving space
                if negative_extra_space || param >= 0.0 || j == 0 {
                    result.push(' ');
                }
            }

            result.push_str(&format_number(param, precision, leading_zero));
        }

        // Update current position
        update_position(cmd, &mut current_x, &mut current_y);
    }

    Ok(result)
}

/// Determine if absolute coordinates are more efficient
fn should_use_absolute(cmd: &PathCommand, current_x: f64, current_y: f64, precision: u8) -> bool {
    // Get absolute parameters
    let absolute_params = cmd.params.clone();

    // Get relative parameters
    let relative_params = convert_to_relative(cmd, current_x, current_y);

    // Compare the string length of both representations
    let absolute_str = format_params(&absolute_params, precision, true, true);
    let relative_str = format_params(&relative_params, precision, true, true);

    // Use absolute if it's shorter or equal length
    // This matches SVGO's behavior where absolute is preferred when lengths are equal
    absolute_str.len() <= relative_str.len()
}

/// Format parameters as they would appear in the path string
fn format_params(
    params: &[f64],
    precision: u8,
    leading_zero: bool,
    negative_extra_space: bool,
) -> String {
    let mut result = String::new();

    for (i, &param) in params.iter().enumerate() {
        if i > 0 {
            // Add space before parameter unless it's negative and we're saving space
            if negative_extra_space || param >= 0.0 {
                result.push(' ');
            }
        }

        result.push_str(&format_number(param, precision, leading_zero));
    }

    result
}

/// Convert absolute coordinates to relative
fn convert_to_relative(cmd: &PathCommand, current_x: f64, current_y: f64) -> Vec<f64> {
    let mut params = cmd.params.clone();

    match cmd.cmd_type {
        CommandType::MoveTo | CommandType::LineTo => {
            if params.len() >= 2 {
                params[0] -= current_x;
                params[1] -= current_y;
            }
        }
        CommandType::HorizontalLineTo => {
            if !params.is_empty() {
                params[0] -= current_x;
            }
        }
        CommandType::VerticalLineTo => {
            if !params.is_empty() {
                params[0] -= current_y;
            }
        }
        CommandType::CurveTo => {
            if params.len() >= 6 {
                params[0] -= current_x;
                params[1] -= current_y;
                params[2] -= current_x;
                params[3] -= current_y;
                params[4] -= current_x;
                params[5] -= current_y;
            }
        }
        CommandType::SmoothCurveTo => {
            if params.len() >= 4 {
                params[0] -= current_x;
                params[1] -= current_y;
                params[2] -= current_x;
                params[3] -= current_y;
            }
        }
        CommandType::QuadraticBezier => {
            if params.len() >= 4 {
                params[0] -= current_x;
                params[1] -= current_y;
                params[2] -= current_x;
                params[3] -= current_y;
            }
        }
        CommandType::SmoothQuadraticBezier => {
            if params.len() >= 2 {
                params[0] -= current_x;
                params[1] -= current_y;
            }
        }
        CommandType::Arc => {
            if params.len() >= 7 {
                params[5] -= current_x;
                params[6] -= current_y;
            }
        }
        _ => {}
    }

    params
}

/// Update current position based on command
fn update_position(cmd: &PathCommand, current_x: &mut f64, current_y: &mut f64) {
    match cmd.cmd_type {
        CommandType::MoveTo | CommandType::LineTo => {
            if cmd.params.len() >= 2 {
                *current_x = cmd.params[0];
                *current_y = cmd.params[1];
            }
        }
        CommandType::HorizontalLineTo => {
            if !cmd.params.is_empty() {
                *current_x = cmd.params[0];
            }
        }
        CommandType::VerticalLineTo => {
            if !cmd.params.is_empty() {
                *current_y = cmd.params[0];
            }
        }
        CommandType::CurveTo => {
            if cmd.params.len() >= 6 {
                *current_x = cmd.params[4];
                *current_y = cmd.params[5];
            }
        }
        CommandType::SmoothCurveTo => {
            if cmd.params.len() >= 4 {
                *current_x = cmd.params[2];
                *current_y = cmd.params[3];
            }
        }
        CommandType::QuadraticBezier => {
            if cmd.params.len() >= 4 {
                *current_x = cmd.params[2];
                *current_y = cmd.params[3];
            }
        }
        CommandType::SmoothQuadraticBezier => {
            if cmd.params.len() >= 2 {
                *current_x = cmd.params[0];
                *current_y = cmd.params[1];
            }
        }
        CommandType::Arc => {
            if cmd.params.len() >= 7 {
                *current_x = cmd.params[5];
                *current_y = cmd.params[6];
            }
        }
        _ => {}
    }
}

/// Format a number with optional precision
fn format_number(value: f64, precision: u8, leading_zero: bool) -> String {
    // Format with precision
    let formatted = format!("{:.1$}", value, precision as usize);

    // Remove trailing zeros and decimal point if integer
    let mut trimmed = formatted.trim_end_matches('0').trim_end_matches('.');

    // Handle edge cases
    if trimmed.is_empty() || trimmed == "-" {
        return "0".to_string();
    }

    // Remove leading zero if requested
    if !leading_zero && trimmed.starts_with("0.") {
        trimmed = &trimmed[1..];
    } else if !leading_zero && trimmed.starts_with("-0.") {
        return format!("-{}", &trimmed[2..]);
    }

    trimmed.to_string()
}

/// Replaces nearly-straight Bézier curves with line commands.
///
/// Checks if control points lie within `tolerance` distance from the straight line
/// between start and end. Saves bytes when a complex curve is visually indistinguishable
/// from a straight line.
fn straighten_curves(commands: Vec<PathCommand>, tolerance: f64) -> Vec<PathCommand> {
    let mut result = Vec::new();
    let mut current_x = 0.0;
    let mut current_y = 0.0;

    for cmd in commands {
        let mut new_cmd = cmd.clone();

        match cmd.cmd_type {
            CommandType::CurveTo if cmd.params.len() >= 6 => {
                // Create a cubic bezier segment
                let start = Point::new(current_x as f32, current_y as f32);
                let ctrl1 = Point::new(cmd.params[0] as f32, cmd.params[1] as f32);
                let ctrl2 = Point::new(cmd.params[2] as f32, cmd.params[3] as f32);
                let end = Point::new(cmd.params[4] as f32, cmd.params[5] as f32);

                let curve = CubicBezierSegment {
                    from: start,
                    ctrl1,
                    ctrl2,
                    to: end,
                };

                // Check if the curve is nearly straight
                if is_curve_nearly_straight(&curve, tolerance as f32) {
                    // Convert to LineTo
                    new_cmd = PathCommand {
                        cmd_type: CommandType::LineTo,
                        is_absolute: cmd.is_absolute,
                        params: vec![cmd.params[4], cmd.params[5]],
                    };
                }

                current_x = cmd.params[4];
                current_y = cmd.params[5];
            }
            CommandType::QuadraticBezier if cmd.params.len() >= 4 => {
                // Create a quadratic bezier segment
                let start = Point::new(current_x as f32, current_y as f32);
                let ctrl = Point::new(cmd.params[0] as f32, cmd.params[1] as f32);
                let end = Point::new(cmd.params[2] as f32, cmd.params[3] as f32);

                let curve = QuadraticBezierSegment {
                    from: start,
                    ctrl,
                    to: end,
                };

                // Check if the curve is nearly straight
                if is_quadratic_curve_nearly_straight(&curve, tolerance as f32) {
                    // Convert to LineTo
                    new_cmd = PathCommand {
                        cmd_type: CommandType::LineTo,
                        is_absolute: cmd.is_absolute,
                        params: vec![cmd.params[2], cmd.params[3]],
                    };
                }

                current_x = cmd.params[2];
                current_y = cmd.params[3];
            }
            _ => {
                update_position(&cmd, &mut current_x, &mut current_y);
            }
        }

        result.push(new_cmd);
    }

    result
}

/// Converts cubic Bézier curves (C) to quadratic (Q) when quality loss is acceptable.
///
/// Quadratic curves use 1 control point vs 2 for cubic, saving 2 coordinates.
/// Only converts when the quadratic approximation stays within `tolerance`.
fn convert_cubic_to_quadratic(commands: Vec<PathCommand>, tolerance: f64) -> Vec<PathCommand> {
    let mut result = Vec::new();
    let mut current_x = 0.0;
    let mut current_y = 0.0;

    for cmd in commands {
        let mut new_cmd = cmd.clone();

        if cmd.cmd_type == CommandType::CurveTo && cmd.params.len() >= 6 {
            // Create a cubic bezier segment
            let start = Point::new(current_x as f32, current_y as f32);
            let ctrl1 = Point::new(cmd.params[0] as f32, cmd.params[1] as f32);
            let ctrl2 = Point::new(cmd.params[2] as f32, cmd.params[3] as f32);
            let end = Point::new(cmd.params[4] as f32, cmd.params[5] as f32);

            let curve = CubicBezierSegment {
                from: start,
                ctrl1,
                ctrl2,
                to: end,
            };

            // Try to convert to quadratic
            if let Some(quad_ctrl) = cubic_to_quadratic_control_point(&curve, tolerance as f32) {
                // Convert to quadratic bezier
                new_cmd = PathCommand {
                    cmd_type: CommandType::QuadraticBezier,
                    is_absolute: cmd.is_absolute,
                    params: vec![
                        quad_ctrl.x as f64,
                        quad_ctrl.y as f64,
                        cmd.params[4],
                        cmd.params[5],
                    ],
                };
            }

            current_x = cmd.params[4];
            current_y = cmd.params[5];
        } else {
            update_position(&cmd, &mut current_x, &mut current_y);
        }

        result.push(new_cmd);
    }

    result
}

/// Converts Bézier curves to arc commands when the curve is circular.
///
/// Arc commands are more compact for circular arcs. This detects when a curve
/// approximates a circular arc and replaces it with an `A` command.
fn convert_curves_to_arcs(commands: Vec<PathCommand>, tolerance: f64) -> Vec<PathCommand> {
    let mut result = Vec::new();
    let mut current_x = 0.0;
    let mut current_y = 0.0;

    for cmd in commands {
        let mut new_cmd = cmd.clone();

        match cmd.cmd_type {
            CommandType::CurveTo if cmd.params.len() >= 6 => {
                // Create a cubic bezier segment
                let start = Point::new(current_x as f32, current_y as f32);
                let ctrl1 = Point::new(cmd.params[0] as f32, cmd.params[1] as f32);
                let ctrl2 = Point::new(cmd.params[2] as f32, cmd.params[3] as f32);
                let end = Point::new(cmd.params[4] as f32, cmd.params[5] as f32);

                let curve = CubicBezierSegment {
                    from: start,
                    ctrl1,
                    ctrl2,
                    to: end,
                };

                // Try to convert to arc
                if let Some(arc_params) = cubic_to_arc_parameters(&curve, tolerance as f32) {
                    // Convert to Arc command
                    new_cmd = PathCommand {
                        cmd_type: CommandType::Arc,
                        is_absolute: cmd.is_absolute,
                        params: arc_params,
                    };
                }

                current_x = cmd.params[4];
                current_y = cmd.params[5];
            }
            CommandType::QuadraticBezier if cmd.params.len() >= 4 => {
                // Create a quadratic bezier segment
                let start = Point::new(current_x as f32, current_y as f32);
                let ctrl = Point::new(cmd.params[0] as f32, cmd.params[1] as f32);
                let end = Point::new(cmd.params[2] as f32, cmd.params[3] as f32);

                let curve = QuadraticBezierSegment {
                    from: start,
                    ctrl,
                    to: end,
                };

                // Try to convert to arc
                if let Some(arc_params) = quadratic_to_arc_parameters(&curve, tolerance as f32) {
                    // Convert to Arc command
                    new_cmd = PathCommand {
                        cmd_type: CommandType::Arc,
                        is_absolute: cmd.is_absolute,
                        params: arc_params,
                    };
                }

                current_x = cmd.params[2];
                current_y = cmd.params[3];
            }
            _ => {
                update_position(&cmd, &mut current_x, &mut current_y);
            }
        }

        result.push(new_cmd);
    }

    result
}

/// Tests if a cubic Bézier curve is visually indistinguishable from a straight line.
///
/// Measures perpendicular distance from control points to the straight line. If both
/// control points are within `tolerance`, the curve is straight enough to replace with `L`.
fn is_curve_nearly_straight(curve: &CubicBezierSegment<f32>, tolerance: f32) -> bool {
    // Calculate the maximum distance from control points to the straight line
    let line_vec = curve.to - curve.from;
    let line_length = line_vec.length();

    if line_length < tolerance {
        return true; // Very short curve, consider it straight
    }

    let line_unit = line_vec / line_length;

    // Distance from ctrl1 to line
    let ctrl1_vec = curve.ctrl1 - curve.from;
    let ctrl1_proj = ctrl1_vec.dot(line_unit);
    let ctrl1_perp = ctrl1_vec - line_unit * ctrl1_proj;
    let ctrl1_dist = ctrl1_perp.length();

    // Distance from ctrl2 to line
    let ctrl2_vec = curve.ctrl2 - curve.from;
    let ctrl2_proj = ctrl2_vec.dot(line_unit);
    let ctrl2_perp = ctrl2_vec - line_unit * ctrl2_proj;
    let ctrl2_dist = ctrl2_perp.length();

    ctrl1_dist < tolerance && ctrl2_dist < tolerance
}

/// Check if a quadratic curve is nearly straight
fn is_quadratic_curve_nearly_straight(curve: &QuadraticBezierSegment<f32>, tolerance: f32) -> bool {
    // Calculate the distance from control point to the straight line
    let line_vec = curve.to - curve.from;
    let line_length = line_vec.length();

    if line_length < tolerance {
        return true; // Very short curve, consider it straight
    }

    let line_unit = line_vec / line_length;

    // Distance from ctrl to line
    let ctrl_vec = curve.ctrl - curve.from;
    let ctrl_proj = ctrl_vec.dot(line_unit);
    let ctrl_perp = ctrl_vec - line_unit * ctrl_proj;
    let ctrl_dist = ctrl_perp.length();

    ctrl_dist < tolerance
}

/// Try to find a quadratic control point that approximates a cubic curve
fn cubic_to_quadratic_control_point(
    curve: &CubicBezierSegment<f32>,
    tolerance: f32,
) -> Option<Point<f32>> {
    // For a cubic to be convertible to quadratic, the control points must be approximately collinear
    // with the start and end points, and the quadratic control point should be the intersection
    // of lines from start through ctrl1 and from end through ctrl2

    let start_to_ctrl1 = curve.ctrl1 - curve.from;
    let end_to_ctrl2 = curve.ctrl2 - curve.to;

    // Check if lines are approximately parallel (not suitable for conversion)
    let cross_product = start_to_ctrl1.x * end_to_ctrl2.y - start_to_ctrl1.y * end_to_ctrl2.x;
    if cross_product.abs() < 1e-6 {
        return None;
    }

    // Find intersection point using parametric line equations
    let dx = curve.to.x - curve.from.x;
    let dy = curve.to.y - curve.from.y;

    let det = start_to_ctrl1.x * (-end_to_ctrl2.y) - start_to_ctrl1.y * (-end_to_ctrl2.x);
    if det.abs() < 1e-6 {
        return None;
    }

    let t = (dx * (-end_to_ctrl2.y) - dy * (-end_to_ctrl2.x)) / det;

    let quad_ctrl = curve.from + start_to_ctrl1 * t;

    // Create a test quadratic curve and check approximation quality
    let test_quad = QuadraticBezierSegment {
        from: curve.from,
        ctrl: quad_ctrl,
        to: curve.to,
    };

    // Sample points and check deviation
    const SAMPLES: usize = 10;
    for i in 1..SAMPLES {
        let t = i as f32 / SAMPLES as f32;
        let cubic_point = curve.sample(t);
        let quad_point = test_quad.sample(t);
        let distance = (cubic_point - quad_point).length();

        if distance > tolerance {
            return None;
        }
    }

    Some(quad_ctrl)
}

/// Try to convert a cubic curve to arc parameters
fn cubic_to_arc_parameters(curve: &CubicBezierSegment<f32>, tolerance: f32) -> Option<Vec<f64>> {
    // This is a simplified arc detection - a full implementation would be more complex
    // For now, we'll detect if the curve could represent a circular arc

    // Sample points along the curve
    const SAMPLES: usize = 5;
    let mut points = Vec::new();
    for i in 0..=SAMPLES {
        let t = i as f32 / SAMPLES as f32;
        points.push(curve.sample(t));
    }

    // Try to fit a circle through the points
    if let Some((center, radius)) = fit_circle_to_points(&points, tolerance) {
        // Calculate arc parameters: rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, x, y
        let start_angle = (curve.from.y - center.y).atan2(curve.from.x - center.x);
        let end_angle = (curve.to.y - center.y).atan2(curve.to.x - center.x);

        let mut angle_diff = end_angle - start_angle;
        if angle_diff > std::f32::consts::PI {
            angle_diff -= 2.0 * std::f32::consts::PI;
        } else if angle_diff < -std::f32::consts::PI {
            angle_diff += 2.0 * std::f32::consts::PI;
        }

        let large_arc_flag = if angle_diff.abs() > std::f32::consts::PI {
            1.0
        } else {
            0.0
        };
        let sweep_flag = if angle_diff > 0.0 { 1.0 } else { 0.0 };

        return Some(vec![
            radius as f64,     // rx
            radius as f64,     // ry
            0.0,               // x_axis_rotation
            large_arc_flag,    // large_arc_flag
            sweep_flag,        // sweep_flag
            curve.to.x as f64, // x
            curve.to.y as f64, // y
        ]);
    }

    None
}

/// Try to convert a quadratic curve to arc parameters
fn quadratic_to_arc_parameters(
    curve: &QuadraticBezierSegment<f32>,
    tolerance: f32,
) -> Option<Vec<f64>> {
    // Sample points along the curve
    const SAMPLES: usize = 5;
    let mut points = Vec::new();
    for i in 0..=SAMPLES {
        let t = i as f32 / SAMPLES as f32;
        points.push(curve.sample(t));
    }

    // Try to fit a circle through the points
    if let Some((center, radius)) = fit_circle_to_points(&points, tolerance) {
        // Calculate arc parameters
        let start_angle = (curve.from.y - center.y).atan2(curve.from.x - center.x);
        let end_angle = (curve.to.y - center.y).atan2(curve.to.x - center.x);

        let mut angle_diff = end_angle - start_angle;
        if angle_diff > std::f32::consts::PI {
            angle_diff -= 2.0 * std::f32::consts::PI;
        } else if angle_diff < -std::f32::consts::PI {
            angle_diff += 2.0 * std::f32::consts::PI;
        }

        let large_arc_flag = if angle_diff.abs() > std::f32::consts::PI {
            1.0
        } else {
            0.0
        };
        let sweep_flag = if angle_diff > 0.0 { 1.0 } else { 0.0 };

        return Some(vec![
            radius as f64,     // rx
            radius as f64,     // ry
            0.0,               // x_axis_rotation
            large_arc_flag,    // large_arc_flag
            sweep_flag,        // sweep_flag
            curve.to.x as f64, // x
            curve.to.y as f64, // y
        ]);
    }

    None
}

/// Finds the best-fit circle through a set of points using perpendicular bisectors.
///
/// Uses the first three points to calculate circle center, then verifies all other
/// points lie on the circle within `tolerance`. Returns `None` if points aren't circular.
fn fit_circle_to_points(points: &[Point<f32>], tolerance: f32) -> Option<(Point<f32>, f32)> {
    if points.len() < 3 {
        return None;
    }

    // Use the first three points to estimate circle
    let p1 = points[0];
    let p2 = points[1];
    let p3 = points[2];

    // Calculate center using perpendicular bisectors
    let mid12 = Point::new((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0);
    let mid23 = Point::new((p2.x + p3.x) / 2.0, (p2.y + p3.y) / 2.0);

    let dir12 = Vector::new(-(p2.y - p1.y), p2.x - p1.x); // perpendicular to p1-p2
    let dir23 = Vector::new(-(p3.y - p2.y), p3.x - p2.x); // perpendicular to p2-p3

    // Find intersection of perpendicular bisectors
    let det = dir12.x * dir23.y - dir12.y * dir23.x;
    if det.abs() < 1e-6 {
        return None; // Lines are parallel
    }

    let diff = mid23 - mid12;
    let t = (diff.x * dir23.y - diff.y * dir23.x) / det;

    let center = mid12 + dir12 * t;
    let radius = (p1 - center).length();

    // Verify that all points are approximately on the circle
    for &point in points {
        let distance = (point - center).length();
        if (distance - radius).abs() > tolerance {
            return None;
        }
    }

    Some((center, radius))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_plugin_info() {
        let plugin = ConvertPathDataPlugin::new();
        assert_eq!(plugin.name(), "convertPathData");
        assert_eq!(
            plugin.description(),
            "converts path data to relative or absolute, optimizes segments, simplifies curves"
        );
    }

    #[test]
    fn test_param_validation() {
        let plugin = ConvertPathDataPlugin::new();

        // Test null params
        assert!(plugin.validate_params(&Value::Null).is_ok());

        // Test valid params
        assert!(plugin
            .validate_params(&json!({
                "floatPrecision": 2,
                "removeUseless": false
            }))
            .is_ok());

        // Test invalid params
        assert!(plugin
            .validate_params(&json!({
                "invalidParam": true
            }))
            .is_err());
    }

    #[test]
    fn test_parse_simple_path() {
        let path = "M10 20 L30 40";
        let commands = parse_path_data(path).unwrap();
        assert_eq!(commands.len(), 2);
        assert_eq!(commands[0].cmd_type, CommandType::MoveTo);
        assert_eq!(commands[0].params, vec![10.0, 20.0]);
        assert_eq!(commands[1].cmd_type, CommandType::LineTo);
        assert_eq!(commands[1].params, vec![30.0, 40.0]);
    }

    #[test]
    fn test_parse_relative_path() {
        let path = "m10 20 l30 40";
        let commands = parse_path_data(path).unwrap();
        assert_eq!(commands.len(), 2);
        assert_eq!(commands[0].cmd_type, CommandType::MoveTo);
        assert!(!commands[0].is_absolute);
        assert_eq!(commands[1].cmd_type, CommandType::LineTo);
        assert!(!commands[1].is_absolute);
    }

    #[test]
    fn test_format_number() {
        assert_eq!(format_number(1.0, 3, true), "1");
        assert_eq!(format_number(1.234567, 3, true), "1.235");
        assert_eq!(format_number(0.5, 1, false), ".5");
        assert_eq!(format_number(-0.5, 1, false), "-.5");
    }

    #[test]
    fn test_parse_dot_separator_bug() {
        // Test M 10.5.5 - should be MoveTo(10.5, 0.5)
        let path1 = "M 10.5.5";
        let commands1 = parse_path_data(path1).unwrap();
        assert_eq!(commands1.len(), 1);
        assert_eq!(commands1[0].cmd_type, CommandType::MoveTo);
        assert_eq!(commands1[0].params.len(), 2);
        assert_eq!(commands1[0].params[0], 10.5);
        assert_eq!(commands1[0].params[1], 0.5);

        // Test M -7.1.6 - should be MoveTo(-7.1, 0.6)
        let path2 = "M -7.1.6";
        let commands2 = parse_path_data(path2).unwrap();
        assert_eq!(commands2.len(), 1);
        assert_eq!(commands2[0].cmd_type, CommandType::MoveTo);
        assert_eq!(commands2[0].params.len(), 2);
        assert_eq!(commands2[0].params[0], -7.1);
        assert_eq!(commands2[0].params[1], 0.6);
    }

    #[test]
    fn test_optimize_removes_useless_lineto() {
        let path = "M10 10 L10 10 L20 20";
        let config = ConvertPathDataConfig {
            float_precision: 3,
            transform_precision: 5,
            remove_useless: true,
            collapse_repeated: true,
            utilize_absolute: true,
            leading_zero: true,
            negative_extra_space: true,
            make_arcs: MakeArcsConfig::Enabled(false),
            straight_curves: false,
            convert_to_q: false,
            curve_tolerance: 0.1,
            arc_tolerance: 0.5,
        };
        let optimized = optimize_path_data(path, &config).unwrap();
        // Should remove the L10 10 as it's the same as current position
        assert!(!optimized.contains("L10 10"));
    }

    #[test]
    fn test_curve_straightening() {
        // Create a nearly straight cubic curve
        let curve = CubicBezierSegment {
            from: Point::new(0.0, 0.0),
            ctrl1: Point::new(1.0, 0.01), // Very slight deviation
            ctrl2: Point::new(2.0, -0.01),
            to: Point::new(3.0, 0.0),
        };

        assert!(is_curve_nearly_straight(&curve, 0.1));
        assert!(!is_curve_nearly_straight(&curve, 0.001));
    }

    #[test]
    fn test_quadratic_curve_straightening() {
        // Create a nearly straight quadratic curve
        let curve = QuadraticBezierSegment {
            from: Point::new(0.0, 0.0),
            ctrl: Point::new(1.5, 0.01), // Very slight deviation
            to: Point::new(3.0, 0.0),
        };

        assert!(is_quadratic_curve_nearly_straight(&curve, 0.1));
        assert!(!is_quadratic_curve_nearly_straight(&curve, 0.001));
    }

    #[test]
    fn test_circle_fitting() {
        // Create points on a circle
        let center = Point::new(10.0, 10.0);
        let radius = 5.0;
        let points = vec![
            Point::new(center.x + radius, center.y),
            Point::new(center.x, center.y + radius),
            Point::new(center.x - radius, center.y),
            Point::new(center.x, center.y - radius),
        ];

        if let Some((fitted_center, fitted_radius)) = fit_circle_to_points(&points, 0.1) {
            assert!((fitted_center.x - center.x).abs() < 0.1);
            assert!((fitted_center.y - center.y).abs() < 0.1);
            assert!((fitted_radius - radius).abs() < 0.1);
        } else {
            panic!("Should be able to fit circle to points on circle");
        }
    }

    #[test]
    fn test_advanced_config_validation() {
        let plugin = ConvertPathDataPlugin::new();

        // Test advanced features config
        assert!(plugin
            .validate_params(&json!({
                "floatPrecision": 2,
                "makeArcs": true,
                "straightCurves": true,
                "convertToQ": true,
                "curveTolerance": 0.05,
                "arcTolerance": 0.3
            }))
            .is_ok());
    }

    #[test]
    fn test_collapse_repeated_commands() {
        // Test collapsing horizontal line commands
        let commands = vec![
            PathCommand {
                cmd_type: CommandType::HorizontalLineTo,
                is_absolute: false,
                params: vec![10.0],
            },
            PathCommand {
                cmd_type: CommandType::HorizontalLineTo,
                is_absolute: false,
                params: vec![20.0],
            },
        ];

        let result = collapse_repeated_commands(commands);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].params[0], 30.0);

        // Test collapsing vertical line commands
        let commands = vec![
            PathCommand {
                cmd_type: CommandType::VerticalLineTo,
                is_absolute: false,
                params: vec![5.0],
            },
            PathCommand {
                cmd_type: CommandType::VerticalLineTo,
                is_absolute: false,
                params: vec![15.0],
            },
        ];

        let result = collapse_repeated_commands(commands);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].params[0], 20.0);

        // Test NOT collapsing commands with different signs
        let commands = vec![
            PathCommand {
                cmd_type: CommandType::HorizontalLineTo,
                is_absolute: false,
                params: vec![10.0],
            },
            PathCommand {
                cmd_type: CommandType::HorizontalLineTo,
                is_absolute: false,
                params: vec![-5.0],
            },
        ];

        let result = collapse_repeated_commands(commands);
        assert_eq!(result.len(), 2); // Should NOT collapse due to different signs
    }

    #[test]
    fn test_should_use_absolute() {
        // Test case where absolute is shorter
        let cmd = PathCommand {
            cmd_type: CommandType::LineTo,
            is_absolute: true,
            params: vec![5.0, 5.0],
        };

        // Current position is far from target, so relative will be long
        assert!(should_use_absolute(&cmd, 1000.0, 1000.0, 3));

        // Test case where relative is shorter
        let cmd = PathCommand {
            cmd_type: CommandType::LineTo,
            is_absolute: true,
            params: vec![1001.0, 1001.0],
        };

        // Current position is close to target, so relative will be short
        assert!(!should_use_absolute(&cmd, 1000.0, 1000.0, 3));
    }

    #[test]
    fn test_format_params() {
        // Test basic parameter formatting
        let params = vec![10.0, 20.0, 30.0];
        let result = format_params(&params, 3, true, true);
        assert_eq!(result, "10 20 30");

        // Test with negative numbers and space saving
        let params = vec![10.0, -20.0, 30.0];
        let result = format_params(&params, 3, true, false);
        assert_eq!(result, "10-20 30");

        // Test precision formatting
        let params = vec![10.123456, 20.999];
        let result = format_params(&params, 2, true, true);
        assert_eq!(result, "10.12 21");
    }

    #[test]
    fn test_can_collapse_commands() {
        // Test same type commands can collapse
        let cmd1 = PathCommand {
            cmd_type: CommandType::HorizontalLineTo,
            is_absolute: false,
            params: vec![10.0],
        };
        let cmd2 = PathCommand {
            cmd_type: CommandType::HorizontalLineTo,
            is_absolute: false,
            params: vec![20.0],
        };

        assert!(can_collapse_commands(&cmd1, &cmd2));

        // Test different type commands cannot collapse
        let cmd1 = PathCommand {
            cmd_type: CommandType::HorizontalLineTo,
            is_absolute: false,
            params: vec![10.0],
        };
        let cmd2 = PathCommand {
            cmd_type: CommandType::VerticalLineTo,
            is_absolute: false,
            params: vec![20.0],
        };

        assert!(!can_collapse_commands(&cmd1, &cmd2));

        // Test different absolute/relative cannot collapse
        let cmd1 = PathCommand {
            cmd_type: CommandType::HorizontalLineTo,
            is_absolute: true,
            params: vec![10.0],
        };
        let cmd2 = PathCommand {
            cmd_type: CommandType::HorizontalLineTo,
            is_absolute: false,
            params: vec![20.0],
        };

        assert!(!can_collapse_commands(&cmd1, &cmd2));

        // Test LineTo collapsing (only relative)
        let cmd1 = PathCommand {
            cmd_type: CommandType::LineTo,
            is_absolute: false,
            params: vec![10.0, 20.0],
        };
        let cmd2 = PathCommand {
            cmd_type: CommandType::LineTo,
            is_absolute: false,
            params: vec![5.0, 5.0],
        };

        assert!(can_collapse_commands(&cmd1, &cmd2));

        // Test LineTo absolute cannot collapse
        let cmd1 = PathCommand {
            cmd_type: CommandType::LineTo,
            is_absolute: true,
            params: vec![10.0, 20.0],
        };
        let cmd2 = PathCommand {
            cmd_type: CommandType::LineTo,
            is_absolute: true,
            params: vec![15.0, 25.0],
        };

        assert!(!can_collapse_commands(&cmd1, &cmd2));
    }
}