altium-format 0.1.7

Core altium-cli library for reading and writing Altium Designer files.
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
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: 2026 Alexander Kiselev <alex@akiselev.com>
//
//! PCB footprint library operations.
//!
//! High-level operations for exploring and manipulating Altium PCB footprint library (.PcbLib) files.

// cmd_* functions mix presentation and business logic; separation punted until usage patterns clarify abstraction boundaries (premature abstraction risk)

use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Cursor};
use std::path::{Path, PathBuf};

use png;
use resvg;
use serde::{Deserialize, Serialize};
use serde_json;

use crate::dump::fmt_coord_val;
use crate::footprint::{
    AsciiOptions, FootprintBuilder, PadRowDirection, SvgOptions, render_ascii, render_svg,
};
use crate::io::PcbLib;
use crate::records::pcb::{PcbPad, PcbPadShape, PcbRecord, PcbText};
use crate::types::{Layer, Unit};

use super::util::alphanumeric_sort;
use crate::ops::output::*;

fn open_pcblib(path: &Path) -> Result<PcbLib, Box<dyn std::error::Error>> {
    let file = File::open(path)?;
    Ok(PcbLib::open(BufReader::new(file))?)
}

/// Categorize a footprint by its pattern name.
fn categorize_footprint(pattern: &str, description: &str) -> &'static str {
    let pattern_lower = pattern.to_lowercase();
    let desc_lower = description.to_lowercase();

    // Package types
    if pattern_lower.contains("qfp")
        || pattern_lower.contains("tqfp")
        || pattern_lower.contains("lqfp")
    {
        return "QFP";
    }
    if pattern_lower.contains("qfn")
        || pattern_lower.contains("dfn")
        || pattern_lower.contains("mlf")
    {
        return "QFN/DFN";
    }
    if pattern_lower.contains("bga")
        || pattern_lower.contains("csbga")
        || pattern_lower.contains("wlcsp")
    {
        return "BGA";
    }
    if pattern_lower.contains("soic")
        || pattern_lower.contains("so-")
        || pattern_lower.contains("sop")
    {
        return "SOIC/SOP";
    }
    if pattern_lower.contains("ssop")
        || pattern_lower.contains("tssop")
        || pattern_lower.contains("msop")
    {
        return "SSOP/TSSOP";
    }
    if pattern_lower.contains("sot") {
        return "SOT";
    }
    if pattern_lower.contains("dip") || pattern_lower.contains("pdip") {
        return "DIP";
    }
    if pattern_lower.contains("to-")
        || pattern_lower.contains("to2")
        || pattern_lower.contains("to3")
        || pattern_lower.contains("dpak")
        || pattern_lower.contains("d2pak")
    {
        return "TO/DPAK";
    }

    // Passive components
    if pattern_lower.starts_with("0402")
        || pattern_lower.starts_with("0603")
        || pattern_lower.starts_with("0805")
        || pattern_lower.starts_with("1206")
        || pattern_lower.starts_with("1210")
        || pattern_lower.starts_with("0201")
        || pattern_lower.starts_with("1812")
        || pattern_lower.starts_with("2010")
        || pattern_lower.starts_with("2512")
    {
        return "Chip (SMD)";
    }
    if pattern_lower.contains("cap") || desc_lower.contains("capacitor") {
        return "Capacitor";
    }
    if pattern_lower.contains("res") || desc_lower.contains("resistor") {
        return "Resistor";
    }
    if pattern_lower.contains("ind")
        || pattern_lower.contains("ferrite")
        || desc_lower.contains("inductor")
    {
        return "Inductor";
    }

    // Connectors
    if pattern_lower.contains("header")
        || pattern_lower.contains("conn")
        || pattern_lower.contains("socket")
        || pattern_lower.contains("pin")
        || pattern_lower.contains("terminal")
    {
        return "Connector";
    }
    if pattern_lower.contains("usb") {
        return "USB";
    }
    if pattern_lower.contains("rj45") || pattern_lower.contains("ethernet") {
        return "RJ45/Ethernet";
    }

    // Diodes/LEDs
    if pattern_lower.contains("diode")
        || pattern_lower.contains("sod")
        || pattern_lower.contains("sma")
        || pattern_lower.contains("smb")
        || pattern_lower.contains("smc")
    {
        return "Diode";
    }
    if pattern_lower.contains("led") {
        return "LED";
    }

    // Crystal/Oscillator
    if pattern_lower.contains("crystal")
        || pattern_lower.contains("xtal")
        || pattern_lower.contains("osc")
    {
        return "Crystal/Oscillator";
    }

    // Test points
    if pattern_lower.contains("test") || pattern_lower.contains("tp") {
        return "Test Point";
    }

    // Through-hole
    if pattern_lower.contains("th")
        || pattern_lower.contains("axial")
        || pattern_lower.contains("radial")
    {
        return "Through-Hole";
    }

    "Other"
}

/// Get pad shape name.
fn pad_shape_name(shape: PcbPadShape) -> &'static str {
    shape.name()
}

/// Get record type name.
fn record_type_name(record: &PcbRecord) -> &'static str {
    match record {
        PcbRecord::Arc(_) => "Arc",
        PcbRecord::Pad(_) => "Pad",
        PcbRecord::Via(_) => "Via",
        PcbRecord::Track(_) => "Track",
        PcbRecord::Text(_) => "Text",
        PcbRecord::Fill(_) => "Fill",
        PcbRecord::Region(_) => "Region",
        PcbRecord::ComponentBody(_) => "ComponentBody",
        PcbRecord::Polygon(_) => "Polygon",
        PcbRecord::Unknown { .. } => "Unknown",
    }
}

/// Format layer name.
fn layer_name(layer: &Layer) -> String {
    match layer.to_byte() {
        1 => "Top".to_string(),
        32 => "Bottom".to_string(),
        74 => "Multi".to_string(),
        _ => format!("L{}", layer.to_byte()),
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// HIGH-LEVEL COMMANDS
// ═══════════════════════════════════════════════════════════════════════════

/// Complete library overview.
pub fn cmd_overview(path: &Path) -> Result<PcbLibOverview, Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    // ─────────────────────────────────────────────────────────────────────────
    // 1. FOOTPRINTS BY CATEGORY
    // ─────────────────────────────────────────────────────────────────────────
    let mut categories: HashMap<&'static str, Vec<FootprintSummaryExt>> = HashMap::new();

    for comp in lib.iter() {
        let category = categorize_footprint(&comp.pattern, &comp.description);
        categories
            .entry(category)
            .or_default()
            .push(FootprintSummaryExt {
                name: comp.pattern.clone(),
                description: comp.description.clone(),
                pad_count: comp.pad_count(),
            });
    }

    // Sort categories by importance
    let category_order = [
        "QFP",
        "QFN/DFN",
        "BGA",
        "SOIC/SOP",
        "SSOP/TSSOP",
        "SOT",
        "DIP",
        "TO/DPAK",
        "Chip (SMD)",
        "Capacitor",
        "Resistor",
        "Inductor",
        "Connector",
        "USB",
        "RJ45/Ethernet",
        "Diode",
        "LED",
        "Crystal/Oscillator",
        "Test Point",
        "Through-Hole",
        "Other",
    ];

    let mut footprints_by_category = Vec::new();
    for category in category_order.iter() {
        if let Some(footprints) = categories.remove(*category) {
            footprints_by_category.push((category.to_string(), footprints));
        }
    }

    // Add any uncategorized
    for (category, footprints) in categories {
        if !footprints.is_empty() {
            footprints_by_category.push((category.to_string(), footprints));
        }
    }

    // ─────────────────────────────────────────────────────────────────────────
    // 2. PAD STATISTICS
    // ─────────────────────────────────────────────────────────────────────────
    let mut total_pads = 0;
    let mut smd_pads = 0;
    let mut th_pads = 0;
    let mut pad_shapes: HashMap<&'static str, usize> = HashMap::new();

    for comp in lib.iter() {
        for pad in comp.pads() {
            total_pads += 1;
            if pad.has_hole() {
                th_pads += 1;
            } else {
                smd_pads += 1;
            }
            *pad_shapes
                .entry(pad_shape_name(pad.shape_top()))
                .or_insert(0) += 1;
        }
    }

    let mut pad_shapes_vec: Vec<_> = pad_shapes
        .into_iter()
        .map(|(k, v)| (k.to_string(), v))
        .collect();
    pad_shapes_vec.sort_by(|a, b| b.1.cmp(&a.1));

    // ─────────────────────────────────────────────────────────────────────────
    // 3. COMMON HOLE SIZES
    // ─────────────────────────────────────────────────────────────────────────
    let mut hole_sizes: HashMap<String, usize> = HashMap::new();
    for comp in lib.iter() {
        for pad in comp.pads() {
            if pad.has_hole() && pad.hole_size.to_raw() > 0 {
                let size_str = fmt_coord_val(&pad.hole_size);
                *hole_sizes.entry(size_str).or_insert(0) += 1;
            }
        }
    }

    let mut hole_sizes_vec: Vec<_> = hole_sizes.into_iter().collect();
    hole_sizes_vec.sort_by(|a, b| b.1.cmp(&a.1));

    // ─────────────────────────────────────────────────────────────────────────
    // 4. LARGEST FOOTPRINTS
    // ─────────────────────────────────────────────────────────────────────────
    let mut by_pads: Vec<_> = lib.iter().collect();
    by_pads.sort_by_key(|b| std::cmp::Reverse(b.pad_count()));

    let largest_footprints = by_pads
        .iter()
        .take(10)
        .map(|comp| FootprintSummaryExt {
            name: comp.pattern.clone(),
            description: comp.description.clone(),
            pad_count: comp.pad_count(),
        })
        .collect();

    Ok(PcbLibOverview {
        path: path.display().to_string(),
        total_footprints: lib.components.len(),
        unique_id: lib.unique_id.clone(),
        footprints_by_category,
        pad_statistics: PadStatistics {
            total_pads,
            smd_pads,
            th_pads,
            pad_shapes: pad_shapes_vec,
        },
        hole_sizes: hole_sizes_vec.into_iter().take(10).collect(),
        largest_footprints,
    })
}

/// List all footprints.
pub fn cmd_list(path: &Path) -> Result<PcbLibFootprintList, Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    let footprints = lib
        .iter()
        .map(|comp| FootprintSummaryExt {
            name: comp.pattern.clone(),
            description: comp.description.clone(),
            pad_count: comp.pad_count(),
        })
        .collect();

    Ok(PcbLibFootprintList {
        path: path.display().to_string(),
        total_footprints: lib.components.len(),
        footprints,
    })
}

/// Search for footprints.
pub fn cmd_search(
    path: &Path,
    query: &str,
) -> Result<PcbLibSearchResults, Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    let query_lower = query.to_lowercase();
    let has_wildcard = query.contains('*');

    let matches: Vec<_> = lib
        .iter()
        .filter(|comp| {
            let name = comp.pattern.to_lowercase();
            let desc = comp.description.to_lowercase();

            if has_wildcard {
                let pattern = query_lower.replace('*', "");
                name.contains(&pattern) || desc.contains(&pattern)
            } else {
                name.contains(&query_lower) || desc.contains(&query_lower)
            }
        })
        .map(|comp| FootprintSummaryExt {
            name: comp.pattern.clone(),
            description: comp.description.clone(),
            pad_count: comp.pad_count(),
        })
        .collect();

    Ok(PcbLibSearchResults {
        query: query.to_string(),
        total_matches: matches.len(),
        results: matches,
    })
}

// ═══════════════════════════════════════════════════════════════════════════
// DETAILED COMMANDS
// ═══════════════════════════════════════════════════════════════════════════

/// Library info and statistics.
pub fn cmd_info(path: &Path) -> Result<PcbLibInfo, Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    // Count primitive types across all footprints
    let mut primitive_counts: HashMap<&'static str, usize> = HashMap::new();
    let mut total_primitives = 0;

    for comp in lib.iter() {
        for prim in &comp.primitives {
            let name = record_type_name(prim);
            *primitive_counts.entry(name).or_insert(0) += 1;
            total_primitives += 1;
        }
    }

    let mut primitive_types: Vec<_> = primitive_counts
        .into_iter()
        .map(|(k, v)| (k.to_string(), v))
        .collect();
    primitive_types.sort_by(|a, b| b.1.cmp(&a.1));

    Ok(PcbLibInfo {
        path: path.display().to_string(),
        footprint_count: lib.components.len(),
        unique_id: lib.unique_id.clone(),
        total_primitives,
        primitive_types,
    })
}

/// Footprint details.
pub fn cmd_footprint(
    path: &Path,
    name: &str,
    show_primitives: bool,
) -> Result<PcbLibFootprintDetail, Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    let name_lower = name.to_lowercase();
    let comp = lib
        .iter()
        .find(|c| c.pattern.to_lowercase() == name_lower)
        .ok_or_else(|| format!("Footprint '{}' not found", name))?;

    // Bounds
    let bounds = comp.calculate_bounds();

    // List pads
    let mut pads: Vec<&PcbPad> = comp.pads().collect();
    pads.sort_by(|a, b| alphanumeric_sort(&a.designator, &b.designator));

    let pad_details = pads
        .iter()
        .map(|pad| {
            let size = pad.size_top();
            let size_str = format!("{}x{}", fmt_coord_val(&size.x), fmt_coord_val(&size.y));
            let hole_str = if pad.has_hole() {
                Some(fmt_coord_val(&pad.hole_size))
            } else {
                None
            };
            PadDetail {
                designator: pad.designator.clone(),
                shape: pad_shape_name(pad.shape_top()).to_string(),
                size: size_str,
                hole: hole_str,
                layer: layer_name(&pad.common.layer),
            }
        })
        .collect();

    let primitive_counts = if show_primitives {
        let mut prim_counts: HashMap<&'static str, usize> = HashMap::new();
        for prim in &comp.primitives {
            *prim_counts.entry(record_type_name(prim)).or_insert(0) += 1;
        }
        let mut counts: Vec<_> = prim_counts
            .into_iter()
            .map(|(k, v)| (k.to_string(), v))
            .collect();
        counts.sort_by(|a, b| b.1.cmp(&a.1));
        Some(counts)
    } else {
        None
    };

    Ok(PcbLibFootprintDetail {
        pattern: comp.pattern.clone(),
        description: comp.description.clone(),
        height: if comp.height.to_raw() > 0 {
            fmt_coord_val(&comp.height)
        } else {
            String::new()
        },
        pad_count: comp.pad_count(),
        total_primitives: comp.primitive_count(),
        bounding_box: BoundingBox {
            width: fmt_coord_val(&bounds.width()),
            height: fmt_coord_val(&bounds.height()),
        },
        pads: pad_details,
        primitive_counts,
    })
}

/// List pads.
pub fn cmd_pads(
    path: &Path,
    footprint_filter: Option<String>,
    by_shape: bool,
) -> Result<PcbLibPadList, Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    let filter_lower = footprint_filter.as_ref().map(|s| s.to_lowercase());

    let mut all_pads: Vec<PadWithFootprint> = Vec::new();

    for comp in lib.iter() {
        if let Some(ref filter) = filter_lower {
            if !comp.pattern.to_lowercase().contains(filter) {
                continue;
            }
        }

        for pad in comp.pads() {
            let size = pad.size_top();
            let size_str = format!("{}x{}", fmt_coord_val(&size.x), fmt_coord_val(&size.y));
            let hole_str = if pad.has_hole() {
                Some(fmt_coord_val(&pad.hole_size))
            } else {
                None
            };
            all_pads.push(PadWithFootprint {
                footprint_name: comp.pattern.clone(),
                designator: pad.designator.clone(),
                size: size_str,
                hole: hole_str,
                shape: pad_shape_name(pad.shape_top()).to_string(),
            });
        }
    }

    let pads_by_shape = if by_shape {
        let mut by_shape: HashMap<String, Vec<PadWithFootprint>> = HashMap::new();
        for pad in &all_pads {
            by_shape
                .entry(pad.shape.clone())
                .or_default()
                .push(pad.clone());
        }

        let shape_order = ["Round", "Rectangular", "Rounded Rect", "Octagonal"];
        let mut result = Vec::new();
        for shape in shape_order {
            if let Some(pads) = by_shape.remove(shape) {
                result.push((shape.to_string(), pads));
            }
        }
        // Add remaining shapes
        for (shape, pads) in by_shape {
            result.push((shape, pads));
        }
        Some(result)
    } else {
        None
    };

    Ok(PcbLibPadList {
        path: path.display().to_string(),
        total_pads: all_pads.len(),
        pads: all_pads,
        pads_by_shape,
    })
}

/// Show primitives for a footprint.
pub fn cmd_primitives(
    path: &Path,
    name: &str,
) -> Result<PcbLibPrimitiveList, Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    let name_lower = name.to_lowercase();
    let comp = lib
        .iter()
        .find(|c| c.pattern.to_lowercase() == name_lower)
        .ok_or_else(|| format!("Footprint '{}' not found", name))?;

    let primitives = comp
        .primitives
        .iter()
        .map(|prim| match prim {
            PcbRecord::Pad(p) => {
                let size = p.size_top();
                let hole = if p.has_hole() {
                    Some(fmt_coord_val(&p.hole_size))
                } else {
                    None
                };
                PrimitiveDetail::Pad {
                    designator: p.designator.clone(),
                    shape: pad_shape_name(p.shape_top()).to_string(),
                    size: format!("{}x{}", fmt_coord_val(&size.x), fmt_coord_val(&size.y)),
                    hole,
                }
            }
            PcbRecord::Track(t) => PrimitiveDetail::Track {
                start_x: fmt_coord_val(&t.start.x),
                start_y: fmt_coord_val(&t.start.y),
                end_x: fmt_coord_val(&t.end.x),
                end_y: fmt_coord_val(&t.end.y),
                width: fmt_coord_val(&t.width),
            },
            PcbRecord::Arc(a) => PrimitiveDetail::Arc {
                center_x: fmt_coord_val(&a.location.x),
                center_y: fmt_coord_val(&a.location.y),
                radius: fmt_coord_val(&a.radius),
                start_angle: a.start_angle,
                end_angle: a.end_angle,
            },
            PcbRecord::Text(t) => PrimitiveDetail::Text {
                text: t.text.clone(),
                x: fmt_coord_val(&t.base.corner1.x),
                y: fmt_coord_val(&t.base.corner1.y),
            },
            PcbRecord::Fill(f) => PrimitiveDetail::Fill {
                x1: fmt_coord_val(&f.base.corner1.x),
                y1: fmt_coord_val(&f.base.corner1.y),
                x2: fmt_coord_val(&f.base.corner2.x),
                y2: fmt_coord_val(&f.base.corner2.y),
            },
            PcbRecord::Region(r) => PrimitiveDetail::Region {
                vertex_count: r.outline.len(),
                layer: layer_name(&r.common.layer),
            },
            PcbRecord::ComponentBody(b) => PrimitiveDetail::ComponentBody {
                vertex_count: b.outline.len(),
                height: fmt_coord_val(&b.overall_height),
            },
            _ => PrimitiveDetail::Other {
                primitive_type: record_type_name(prim).to_string(),
            },
        })
        .collect();

    Ok(PcbLibPrimitiveList {
        footprint_name: comp.pattern.clone(),
        total_primitives: comp.primitive_count(),
        primitives,
    })
}

/// Analyze hole sizes.
pub fn cmd_holes(path: &Path) -> Result<PcbLibHoleAnalysis, Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    let mut hole_sizes: HashMap<String, Vec<String>> = HashMap::new();

    for comp in lib.iter() {
        for pad in comp.pads() {
            if pad.has_hole() && pad.hole_size.to_raw() > 0 {
                let size_str = fmt_coord_val(&pad.hole_size);
                hole_sizes
                    .entry(size_str)
                    .or_default()
                    .push(comp.pattern.clone());
            }
        }
    }

    let mut hole_size_infos: Vec<_> = hole_sizes
        .into_iter()
        .map(|(size, footprints)| {
            // Deduplicate footprint names
            let unique_footprints: std::collections::HashSet<_> = footprints.into_iter().collect();
            let count = unique_footprints.len();
            let example_footprints: Vec<_> = unique_footprints.into_iter().take(3).collect();

            HoleSizeInfo {
                size,
                count,
                example_footprints,
            }
        })
        .collect();

    // Sort by count (descending)
    hole_size_infos.sort_by(|a, b| b.count.cmp(&a.count));

    Ok(PcbLibHoleAnalysis {
        path: path.display().to_string(),
        hole_sizes: hole_size_infos,
    })
}

/// Export as JSON.
pub fn cmd_json(path: &Path, full: bool) -> Result<PcbLibJson, Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    let footprints: Vec<FootprintJsonData> = lib
        .iter()
        .map(|comp| {
            let pads = if full {
                Some(
                    comp.pads()
                        .map(|pad| {
                            let size = pad.size_top();
                            PadJsonData {
                                designator: pad.designator.clone(),
                                shape: pad_shape_name(pad.shape_top()).to_string(),
                                size_x: fmt_coord_val(&size.x),
                                size_y: fmt_coord_val(&size.y),
                                hole_size: if pad.has_hole() {
                                    Some(fmt_coord_val(&pad.hole_size))
                                } else {
                                    None
                                },
                                layer: layer_name(&pad.common.layer),
                            }
                        })
                        .collect(),
                )
            } else {
                None
            };

            FootprintJsonData {
                name: comp.pattern.clone(),
                description: comp.description.clone(),
                pad_count: comp.pad_count(),
                primitive_count: comp.primitive_count(),
                pads,
            }
        })
        .collect();

    Ok(PcbLibJson {
        file: path.display().to_string(),
        footprint_count: lib.components.len(),
        unique_id: lib.unique_id.clone(),
        footprints,
    })
}

// ═══════════════════════════════════════════════════════════════════════════
// MEASUREMENT COMMAND IMPLEMENTATION
// ═══════════════════════════════════════════════════════════════════════════

use crate::footprint::{
    Measurement, analyze_pitch, generate_report, measure_dimensions, measure_pad,
    measure_pad_distance, minimum_pad_clearance, pad_to_silkscreen_clearance,
};

/// Measure distances and dimensions in a footprint.
pub fn cmd_measure(
    path: &Path,
    name: &str,
    measure_type: &str,
    pad1: Option<String>,
    pad2: Option<String>,
    pad: Option<String>,
    output_json: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    let name_lower = name.to_lowercase();
    let component = lib
        .iter()
        .find(|c| c.pattern.to_lowercase() == name_lower || matches_pattern(&c.pattern, name))
        .ok_or_else(|| format!("Footprint '{}' not found", name))?;

    match measure_type.to_lowercase().as_str() {
        "all" | "report" => {
            let report = generate_report(component);

            if output_json {
                print_measurement_report_json(&report)?;
            } else {
                print_measurement_report(&report);
            }
        }
        "distance" | "dist" => {
            let p1 = pad1.ok_or("--pad1 required for distance measurement")?;
            let p2 = pad2.ok_or("--pad2 required for distance measurement")?;

            let dist = measure_pad_distance(component, &p1, &p2).ok_or_else(|| {
                format!("Could not measure distance between pads {} and {}", p1, p2)
            })?;

            if output_json {
                print_distance_json(&dist)?;
            } else {
                println!("Distance: {} to {}", dist.pad1, dist.pad2);
                println!("  Center-to-center: {}", dist.center_to_center.display());
                println!("  Edge-to-edge:     {}", dist.edge_to_edge.display());
            }
        }
        "pitch" => {
            let pitches = analyze_pitch(component);

            if output_json {
                print_pitch_json(&pitches)?;
            } else if pitches.is_empty() {
                println!("No regular pitch detected (footprint may have irregular pad spacing)");
            } else {
                println!("Pitch Analysis for: {}", component.pattern);
                println!("═══════════════════════════════════════════════════════════════");
                for pitch_info in &pitches {
                    println!(
                        "\n{} pitch: {}",
                        pitch_info.direction,
                        pitch_info.pitch.display()
                    );
                    println!("  {} pad pairs with this spacing", pitch_info.count);
                    for (p1, p2, dist) in pitch_info.pad_pairs.iter().take(5) {
                        println!("    {}{}: {}", p1, p2, dist.display());
                    }
                    if pitch_info.pad_pairs.len() > 5 {
                        println!("    ... and {} more pairs", pitch_info.pad_pairs.len() - 5);
                    }
                }
            }
        }
        "dimensions" | "dims" | "bounds" => {
            let dims = measure_dimensions(component);

            if output_json {
                print_dimensions_json(&dims)?;
            } else {
                println!("Dimensions for: {}", component.pattern);
                println!("═══════════════════════════════════════════════════════════════");
                println!("  Width:  {}", dims.width.display());
                println!("  Height: {}", dims.height.display());
                println!(
                    "  X range: {} to {}",
                    dims.min_x.display(),
                    dims.max_x.display()
                );
                println!(
                    "  Y range: {} to {}",
                    dims.min_y.display(),
                    dims.max_y.display()
                );
            }
        }
        "clearance" | "clear" => {
            let pad_clear = minimum_pad_clearance(component);
            let silk_clear = pad_to_silkscreen_clearance(component);

            if output_json {
                print_clearance_json(pad_clear.as_ref(), silk_clear.as_ref())?;
            } else {
                println!("Clearance Analysis for: {}", component.pattern);
                println!("═══════════════════════════════════════════════════════════════");

                if let Some(pc) = pad_clear {
                    println!("\nMinimum pad-to-pad clearance: {}", pc.clearance.display());
                    println!("  Location: {}", pc.location);
                } else {
                    println!("\nNo pad-to-pad clearance (single pad or overlapping pads)");
                }

                if let Some(sc) = silk_clear {
                    println!("\nPad-to-silkscreen clearance: {}", sc.clearance.display());
                    println!("  Location: {}", sc.location);
                } else {
                    println!("\nNo silkscreen elements found");
                }
            }
        }
        "pad" => {
            let des = pad.ok_or("--pad required for pad measurement")?;
            let info =
                measure_pad(component, &des).ok_or_else(|| format!("Pad '{}' not found", des))?;

            if output_json {
                print_pad_json(&info)?;
            } else {
                println!("Pad {} info:", info.designator);
                println!("═══════════════════════════════════════════════════════════════");
                println!("  Position: ({}, {})", info.x.display(), info.y.display());
                println!(
                    "  Size:     {} x {}",
                    info.width.display(),
                    info.height.display()
                );
                println!("  Shape:    {}", info.shape);
                if let Some(hole) = &info.hole {
                    println!("  Hole:     {}", hole.display());
                } else {
                    println!("  Type:     SMD");
                }
            }
        }
        "pads" => {
            let report = generate_report(component);

            if output_json {
                print_all_pads_json(&report.pads)?;
            } else {
                println!("All Pads for: {}", component.pattern);
                println!("═══════════════════════════════════════════════════════════════");
                println!(
                    "\n{:<6} {:>10} {:>10} {:>10} {:>10} {:>10} Shape",
                    "Pad", "X (mm)", "Y (mm)", "W (mm)", "H (mm)", "Hole"
                );
                println!(
                    "{:-<6} {:->10} {:->10} {:->10} {:->10} {:->10} {:-<12}",
                    "", "", "", "", "", "", ""
                );

                for pad_info in &report.pads {
                    let hole_str = pad_info
                        .hole
                        .as_ref()
                        .map(|h| format!("{:.3}", h.mm))
                        .unwrap_or_else(|| "-".to_string());

                    println!(
                        "{:<6} {:>10.3} {:>10.3} {:>10.3} {:>10.3} {:>10} {}",
                        pad_info.designator,
                        pad_info.x.mm,
                        pad_info.y.mm,
                        pad_info.width.mm,
                        pad_info.height.mm,
                        hole_str,
                        pad_info.shape
                    );
                }
            }
        }
        _ => {
            return Err(format!(
                "Unknown measurement type: '{}'. Use: all, distance, pitch, dimensions, clearance, pad, pads",
                measure_type
            ).into());
        }
    }

    Ok(())
}

/// Print full measurement report in human-readable format.
fn print_measurement_report(report: &crate::footprint::MeasurementReport) {
    println!("╔═══════════════════════════════════════════════════════════════╗");
    println!("║                  FOOTPRINT MEASUREMENT REPORT                  ║");
    println!("╚═══════════════════════════════════════════════════════════════╝");
    println!("\nFootprint: {}", report.name);

    // Dimensions
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ DIMENSIONS                                                       │");
    println!("└─────────────────────────────────────────────────────────────────┘");
    println!("  Width:  {}", report.dimensions.width.display());
    println!("  Height: {}", report.dimensions.height.display());

    if let Some(span) = &report.row_span {
        println!("  Row span: {}", span.display());
    }

    // Pads summary
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!(
        "│ PADS ({} total)                                                   │",
        report.pads.len()
    );
    println!("└─────────────────────────────────────────────────────────────────┘");

    println!(
        "\n{:<6} {:>10} {:>10} {:>10} {:>10} Shape",
        "Pad", "X (mm)", "Y (mm)", "W (mm)", "H (mm)"
    );
    println!(
        "{:-<6} {:->10} {:->10} {:->10} {:->10} {:-<12}",
        "", "", "", "", "", ""
    );

    for pad in &report.pads {
        println!(
            "{:<6} {:>10.3} {:>10.3} {:>10.3} {:>10.3} {}",
            pad.designator, pad.x.mm, pad.y.mm, pad.width.mm, pad.height.mm, pad.shape
        );
    }

    // Pitch analysis
    if !report.pitch.is_empty() {
        println!("\n┌─────────────────────────────────────────────────────────────────┐");
        println!("│ PITCH ANALYSIS                                                   │");
        println!("└─────────────────────────────────────────────────────────────────┘");

        for pitch_info in &report.pitch {
            println!(
                "\n  {} pitch: {}",
                pitch_info.direction,
                pitch_info.pitch.display()
            );
            println!("    {} adjacent pad pairs", pitch_info.count);
        }
    }

    // Clearances
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ CLEARANCES                                                       │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    if let Some(pc) = &report.min_pad_clearance {
        println!("\n  Minimum pad-to-pad gap: {}", pc.clearance.display());
        println!("    {}", pc.location);
    }

    if let Some(sc) = &report.silkscreen_clearance {
        println!("\n  Pad-to-silkscreen: {}", sc.clearance.display());
        println!("    {}", sc.location);
    }
}

// JSON output helpers

fn print_measurement_report_json(
    report: &crate::footprint::MeasurementReport,
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Serialize)]
    struct MeasurementJson {
        mm: f64,
        mils: f64,
    }

    impl From<&Measurement> for MeasurementJson {
        fn from(m: &Measurement) -> Self {
            MeasurementJson {
                mm: m.mm,
                mils: m.mils,
            }
        }
    }

    #[derive(Serialize)]
    struct PadInfoJson {
        designator: String,
        x_mm: f64,
        y_mm: f64,
        width_mm: f64,
        height_mm: f64,
        hole_mm: Option<f64>,
        shape: String,
    }

    #[derive(Serialize)]
    struct PitchJson {
        pitch: MeasurementJson,
        direction: String,
        count: usize,
    }

    #[derive(Serialize)]
    struct ClearanceJson {
        feature1: String,
        feature2: String,
        clearance: MeasurementJson,
        location: String,
    }

    #[derive(Serialize)]
    struct ReportJson {
        name: String,
        dimensions: DimensionsJson,
        pads: Vec<PadInfoJson>,
        pitch: Vec<PitchJson>,
        min_pad_clearance: Option<ClearanceJson>,
        silkscreen_clearance: Option<ClearanceJson>,
        row_span: Option<MeasurementJson>,
    }

    #[derive(Serialize)]
    struct DimensionsJson {
        width: MeasurementJson,
        height: MeasurementJson,
        min_x: MeasurementJson,
        max_x: MeasurementJson,
        min_y: MeasurementJson,
        max_y: MeasurementJson,
    }

    let output = ReportJson {
        name: report.name.clone(),
        dimensions: DimensionsJson {
            width: (&report.dimensions.width).into(),
            height: (&report.dimensions.height).into(),
            min_x: (&report.dimensions.min_x).into(),
            max_x: (&report.dimensions.max_x).into(),
            min_y: (&report.dimensions.min_y).into(),
            max_y: (&report.dimensions.max_y).into(),
        },
        pads: report
            .pads
            .iter()
            .map(|p| PadInfoJson {
                designator: p.designator.clone(),
                x_mm: p.x.mm,
                y_mm: p.y.mm,
                width_mm: p.width.mm,
                height_mm: p.height.mm,
                hole_mm: p.hole.as_ref().map(|h| h.mm),
                shape: p.shape.clone(),
            })
            .collect(),
        pitch: report
            .pitch
            .iter()
            .map(|p| PitchJson {
                pitch: (&p.pitch).into(),
                direction: p.direction.clone(),
                count: p.count,
            })
            .collect(),
        min_pad_clearance: report.min_pad_clearance.as_ref().map(|c| ClearanceJson {
            feature1: c.feature1.clone(),
            feature2: c.feature2.clone(),
            clearance: (&c.clearance).into(),
            location: c.location.clone(),
        }),
        silkscreen_clearance: report.silkscreen_clearance.as_ref().map(|c| ClearanceJson {
            feature1: c.feature1.clone(),
            feature2: c.feature2.clone(),
            clearance: (&c.clearance).into(),
            location: c.location.clone(),
        }),
        row_span: report.row_span.as_ref().map(|s| s.into()),
    };

    let json = serde_json::to_string_pretty(&output).map_err(|e| e.to_string())?;
    println!("{}", json);
    Ok(())
}

fn print_distance_json(
    dist: &crate::footprint::PadDistance,
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Serialize)]
    struct DistanceJson {
        pad1: String,
        pad2: String,
        center_to_center_mm: f64,
        center_to_center_mils: f64,
        edge_to_edge_mm: f64,
        edge_to_edge_mils: f64,
    }

    let output = DistanceJson {
        pad1: dist.pad1.clone(),
        pad2: dist.pad2.clone(),
        center_to_center_mm: dist.center_to_center.mm,
        center_to_center_mils: dist.center_to_center.mils,
        edge_to_edge_mm: dist.edge_to_edge.mm,
        edge_to_edge_mils: dist.edge_to_edge.mils,
    };

    let json = serde_json::to_string_pretty(&output).map_err(|e| e.to_string())?;
    println!("{}", json);
    Ok(())
}

fn print_pitch_json(
    pitches: &[crate::footprint::PitchAnalysis],
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Serialize)]
    struct PitchJson {
        direction: String,
        pitch_mm: f64,
        pitch_mils: f64,
        pad_pair_count: usize,
    }

    let output: Vec<PitchJson> = pitches
        .iter()
        .map(|p| PitchJson {
            direction: p.direction.clone(),
            pitch_mm: p.pitch.mm,
            pitch_mils: p.pitch.mils,
            pad_pair_count: p.count,
        })
        .collect();

    let json = serde_json::to_string_pretty(&output).map_err(|e| e.to_string())?;
    println!("{}", json);
    Ok(())
}

fn print_dimensions_json(
    dims: &crate::footprint::FootprintDimensions,
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Serialize)]
    struct DimsJson {
        width_mm: f64,
        width_mils: f64,
        height_mm: f64,
        height_mils: f64,
        min_x_mm: f64,
        max_x_mm: f64,
        min_y_mm: f64,
        max_y_mm: f64,
    }

    let output = DimsJson {
        width_mm: dims.width.mm,
        width_mils: dims.width.mils,
        height_mm: dims.height.mm,
        height_mils: dims.height.mils,
        min_x_mm: dims.min_x.mm,
        max_x_mm: dims.max_x.mm,
        min_y_mm: dims.min_y.mm,
        max_y_mm: dims.max_y.mm,
    };

    let json = serde_json::to_string_pretty(&output).map_err(|e| e.to_string())?;
    println!("{}", json);
    Ok(())
}

fn print_clearance_json(
    pad_clear: Option<&crate::footprint::ClearanceResult>,
    silk_clear: Option<&crate::footprint::ClearanceResult>,
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Serialize)]
    struct ClearanceJson {
        feature1: String,
        feature2: String,
        clearance_mm: f64,
        clearance_mils: f64,
        location: String,
    }

    #[derive(Serialize)]
    struct Output {
        pad_to_pad: Option<ClearanceJson>,
        pad_to_silkscreen: Option<ClearanceJson>,
    }

    let output = Output {
        pad_to_pad: pad_clear.map(|c| ClearanceJson {
            feature1: c.feature1.clone(),
            feature2: c.feature2.clone(),
            clearance_mm: c.clearance.mm,
            clearance_mils: c.clearance.mils,
            location: c.location.clone(),
        }),
        pad_to_silkscreen: silk_clear.map(|c| ClearanceJson {
            feature1: c.feature1.clone(),
            feature2: c.feature2.clone(),
            clearance_mm: c.clearance.mm,
            clearance_mils: c.clearance.mils,
            location: c.location.clone(),
        }),
    };

    let json = serde_json::to_string_pretty(&output).map_err(|e| e.to_string())?;
    println!("{}", json);
    Ok(())
}

fn print_pad_json(info: &crate::footprint::PadInfo) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Serialize)]
    struct PadJson {
        designator: String,
        x_mm: f64,
        y_mm: f64,
        width_mm: f64,
        height_mm: f64,
        hole_mm: Option<f64>,
        shape: String,
        is_smd: bool,
    }

    let output = PadJson {
        designator: info.designator.clone(),
        x_mm: info.x.mm,
        y_mm: info.y.mm,
        width_mm: info.width.mm,
        height_mm: info.height.mm,
        hole_mm: info.hole.as_ref().map(|h| h.mm),
        shape: info.shape.clone(),
        is_smd: info.hole.is_none(),
    };

    let json = serde_json::to_string_pretty(&output).map_err(|e| e.to_string())?;
    println!("{}", json);
    Ok(())
}

fn print_all_pads_json(
    pads: &[crate::footprint::PadInfo],
) -> Result<(), Box<dyn std::error::Error>> {
    #[derive(Serialize)]
    struct PadJson {
        designator: String,
        x_mm: f64,
        y_mm: f64,
        width_mm: f64,
        height_mm: f64,
        hole_mm: Option<f64>,
        shape: String,
    }

    let output: Vec<PadJson> = pads
        .iter()
        .map(|p| PadJson {
            designator: p.designator.clone(),
            x_mm: p.x.mm,
            y_mm: p.y.mm,
            width_mm: p.width.mm,
            height_mm: p.height.mm,
            hole_mm: p.hole.as_ref().map(|h| h.mm),
            shape: p.shape.clone(),
        })
        .collect();

    let json = serde_json::to_string_pretty(&output).map_err(|e| e.to_string())?;
    println!("{}", json);
    Ok(())
}

// ═══════════════════════════════════════════════════════════════════════════
// CREATION/EDITING COMMAND IMPLEMENTATIONS
// ═══════════════════════════════════════════════════════════════════════════

/// Embedded blank PcbLib template.
const BLANK_PCBLIB_TEMPLATE: &[u8] = include_bytes!("../../data/blank/PcbLib1.PcbLib");

use crate::footprint::{ChipSpec, IpcDensity};
use crate::records::pcb::{PcbArc, PcbComponent, PcbFlags, PcbPrimitiveCommon, PcbTrack};
use crate::types::{Coord, CoordPoint};

/// Create a new empty PcbLib file.
pub fn cmd_create(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
    if path.exists() {
        return Err(format!("File already exists: {}", path.display()).into());
    }

    std::fs::write(path, BLANK_PCBLIB_TEMPLATE)
        .map_err(|e| format!("Error creating file: {}", e))?;

    println!("Created empty PcbLib: {}", path.display());
    Ok(())
}

fn load_blank_pcblib() -> Result<PcbLib, Box<dyn std::error::Error>> {
    Ok(PcbLib::open(Cursor::new(BLANK_PCBLIB_TEMPLATE))?)
}

/// Add a new footprint to a library.
pub fn cmd_add_footprint(
    path: &Path,
    name: &str,
    description: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut lib = open_or_create_pcblib(path)?;

    // Check if footprint already exists
    if lib.components.iter().any(|c| c.pattern == name) {
        return Err(format!("Footprint '{}' already exists", name).into());
    }

    let mut det = ();
    let mut component = PcbComponent::new_deterministic(name, &mut det);
    if let Some(desc) = description {
        component.set_description(desc);
    }

    lib.components.push(component);
    save_pcblib(path, &lib)?;

    println!("Added footprint '{}' to {}", name, path.display());
    Ok(())
}

/// Add a pad to a footprint.
#[allow(clippy::too_many_arguments)]
pub fn cmd_add_pad(
    path: &Path,
    footprint: &str,
    designator: &str,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
    shape_str: &str,
    hole: f64,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut lib = open_pcblib(path)?;

    let component = lib
        .components
        .iter_mut()
        .find(|c| c.pattern == footprint)
        .ok_or_else(|| format!("Footprint '{}' not found", footprint))?;

    // Parse shape
    let shape = match shape_str.to_lowercase().as_str() {
        "round" => PcbPadShape::Round,
        "rectangular" | "rect" => PcbPadShape::Rectangular,
        "rounded_rect" | "roundedrect" => PcbPadShape::RoundedRectangle,
        "octagonal" | "oct" => PcbPadShape::Octagonal,
        _ => return Err(format!("Unknown pad shape: {}", shape_str).into()),
    };

    // Create pad using FootprintBuilder helper
    let mut builder = FootprintBuilder::new(footprint);
    if hole > 0.0 {
        builder.add_th_pad(designator, x, y, width.max(height), hole, shape);
    } else {
        builder.add_smd_pad(designator, x, y, width, height, shape);
    }

    // Extract the pad from the built component
    let mut det = ();
    let temp = builder.build_deterministic(&mut det);
    if let Some(PcbRecord::Pad(pad)) = temp.primitives.into_iter().next() {
        component.add_primitive(PcbRecord::Pad(pad));
    }

    save_pcblib(path, &lib)?;
    println!(
        "Added pad '{}' to footprint '{}' at ({}, {}) mm",
        designator, footprint, x, y
    );
    Ok(())
}

/// Add a silkscreen line to a footprint.
pub fn cmd_add_silkscreen(
    path: &Path,
    footprint: &str,
    x1: f64,
    y1: f64,
    x2: f64,
    y2: f64,
    width: f64,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut lib = open_pcblib(path)?;

    let component = lib
        .components
        .iter_mut()
        .find(|c| c.pattern == footprint)
        .ok_or_else(|| format!("Footprint '{}' not found", footprint))?;

    let track = PcbTrack {
        common: PcbPrimitiveCommon {
            layer: Layer::TOP_OVERLAY,
            flags: PcbFlags::UNLOCKED | PcbFlags::UNKNOWN8,
            unique_id: None,
        },
        start: CoordPoint::from_mms(x1, y1),
        end: CoordPoint::from_mms(x2, y2),
        width: Coord::from_mms(width),
        unknown: vec![0u8; 16],
    };

    component.add_primitive(PcbRecord::Track(track));
    save_pcblib(path, &lib)?;

    println!("Added silkscreen line to footprint '{}'", footprint);
    Ok(())
}

/// Add a silkscreen arc to a footprint.
#[allow(clippy::too_many_arguments)]
pub fn cmd_add_arc(
    path: &Path,
    footprint: &str,
    x: f64,
    y: f64,
    radius: f64,
    start_angle: f64,
    end_angle: f64,
    width: f64,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut lib = open_pcblib(path)?;

    let component = lib
        .components
        .iter_mut()
        .find(|c| c.pattern == footprint)
        .ok_or_else(|| format!("Footprint '{}' not found", footprint))?;

    let arc = PcbArc {
        common: PcbPrimitiveCommon {
            layer: Layer::TOP_OVERLAY,
            flags: PcbFlags::UNLOCKED | PcbFlags::UNKNOWN8,
            unique_id: None,
        },
        location: CoordPoint::from_mms(x, y),
        radius: Coord::from_mms(radius),
        start_angle,
        end_angle,
        width: Coord::from_mms(width),
    };

    component.add_primitive(PcbRecord::Arc(arc));
    save_pcblib(path, &lib)?;

    println!(
        "Added silkscreen arc to footprint '{}' (center: ({}, {}) mm, radius: {} mm, {:.0}° to {:.0}°)",
        footprint, x, y, radius, start_angle, end_angle
    );
    Ok(())
}

/// Generate a standard chip/passive footprint.
pub fn cmd_gen_chip(
    path: &Path,
    size: &str,
    density_str: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut lib = open_or_create_pcblib(path)?;

    let spec = match size.to_uppercase().as_str() {
        "0201" => ChipSpec::chip_0201(),
        "0402" => ChipSpec::chip_0402(),
        "0603" => ChipSpec::chip_0603(),
        "0805" => ChipSpec::chip_0805(),
        "1206" => ChipSpec::chip_1206(),
        _ => {
            return Err(format!(
                "Unknown chip size: {}. Supported: 0201, 0402, 0603, 0805, 1206",
                size
            )
            .into());
        }
    };

    let density = parse_density(density_str)?;
    let mut det = ();
    let component = spec.to_footprint(density).build_deterministic(&mut det);
    let name = component.pattern.clone();

    // Check if already exists
    if lib.components.iter().any(|c| c.pattern == name) {
        return Err(format!("Footprint '{}' already exists", name).into());
    }

    lib.components.push(component);
    save_pcblib(path, &lib)?;

    println!(
        "Generated chip footprint '{}' with {} density",
        name, density_str
    );
    Ok(())
}

fn parse_density(s: &str) -> Result<IpcDensity, Box<dyn std::error::Error>> {
    match s.to_lowercase().as_str() {
        "most" | "a" | "dense" => Ok(IpcDensity::MostDense),
        "nominal" | "b" | "normal" => Ok(IpcDensity::Nominal),
        "least" | "c" | "loose" => Ok(IpcDensity::LeastDense),
        _ => Err(format!("Unknown density: {}. Use: most, nominal, least", s).into()),
    }
}

pub fn cmd_render_svg(
    path: &Path,
    name: &str,
    output: Option<PathBuf>,
    scale: f64,
    light: bool,
    no_grid: bool,
    no_designators: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    use std::fs;

    let lib = open_pcblib(path)?;

    // Find the footprint
    let name_lower = name.to_lowercase();
    let component = lib
        .iter()
        .find(|c| c.pattern.to_lowercase() == name_lower || matches_pattern(&c.pattern, name))
        .ok_or_else(|| format!("Footprint '{}' not found", name))?;

    // Build options
    let mut options = if light {
        SvgOptions::light()
    } else {
        SvgOptions::default()
    };
    options.scale = scale;
    options.show_grid = !no_grid;
    options.show_designators = !no_designators;

    // Render to SVG
    let svg = render_svg(component, &options);

    // Determine output path
    let output_path = output.unwrap_or_else(|| {
        PathBuf::from(format!(
            "{}.svg",
            component.pattern.replace(['/', '\\', ' '], "_")
        ))
    });

    // Write to file
    fs::write(&output_path, &svg).map_err(|e| format!("Error writing SVG: {}", e))?;

    println!(
        "Rendered footprint '{}' to {}",
        component.pattern,
        output_path.display()
    );
    println!("  Size: {} bytes", svg.len());
    println!("  Theme: {}", if light { "light" } else { "dark" });
    println!("  Scale: {} px/mil", scale);

    Ok(())
}

pub fn cmd_render_png(
    path: &Path,
    name: &str,
    output: Option<PathBuf>,
    scale: f64,
    target_width: Option<u32>,
) -> Result<(), Box<dyn std::error::Error>> {
    use std::fs::File;
    use std::io::BufWriter;

    let lib = open_pcblib(path)?;

    // Find the footprint
    let name_lower = name.to_lowercase();
    let component = lib
        .iter()
        .find(|c| c.pattern.to_lowercase() == name_lower || matches_pattern(&c.pattern, name))
        .ok_or_else(|| format!("Footprint '{}' not found", name))?;

    // Use Altium-style colors (dark background, colored layers)
    let options = SvgOptions {
        scale,
        show_grid: false, // No grid for PNG
        show_designators: true,
        ..Default::default()
    };

    // Render to SVG first
    let svg_data = render_svg(component, &options);

    // Parse SVG and render to PNG using resvg
    let tree = resvg::usvg::Tree::from_str(&svg_data, &resvg::usvg::Options::default())
        .map_err(|e| format!("Error parsing SVG: {}", e))?;

    // Calculate dimensions
    let svg_size = tree.size();
    let (width, height) = if let Some(w) = target_width {
        let h = (w as f32 * svg_size.height() / svg_size.width()) as u32;
        (w, h)
    } else {
        (svg_size.width() as u32, svg_size.height() as u32)
    };

    // Create pixmap and render
    let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height)
        .ok_or_else(|| "Failed to create pixmap".to_string())?;

    // Fill with dark background
    pixmap.fill(resvg::tiny_skia::Color::from_rgba8(30, 30, 30, 255));

    // Render SVG onto pixmap
    let scale_x = width as f32 / svg_size.width();
    let scale_y = height as f32 / svg_size.height();
    let transform = resvg::tiny_skia::Transform::from_scale(scale_x, scale_y);

    resvg::render(&tree, transform, &mut pixmap.as_mut());

    // Determine output path
    let output_path = output.unwrap_or_else(|| {
        PathBuf::from(format!(
            "{}.png",
            component.pattern.replace(['/', '\\', ' '], "_")
        ))
    });

    // Write PNG
    let file = File::create(&output_path).map_err(|e| format!("Error creating file: {}", e))?;
    let writer = BufWriter::new(file);
    let mut encoder = png::Encoder::new(writer, width, height);
    encoder.set_color(png::ColorType::Rgba);
    encoder.set_depth(png::BitDepth::Eight);

    let mut png_writer = encoder
        .write_header()
        .map_err(|e| format!("Error writing PNG header: {}", e))?;
    png_writer
        .write_image_data(pixmap.data())
        .map_err(|e| format!("Error writing PNG data: {}", e))?;

    println!(
        "Rendered footprint '{}' to {}",
        component.pattern,
        output_path.display()
    );
    println!("  Size: {}x{} pixels", width, height);

    Ok(())
}

pub fn cmd_render_ascii(
    path: &Path,
    name: &str,
    max_width: usize,
    max_height: usize,
) -> Result<(), Box<dyn std::error::Error>> {
    let lib = open_pcblib(path)?;

    // Find the footprint
    let name_lower = name.to_lowercase();
    let component = lib
        .iter()
        .find(|c| c.pattern.to_lowercase() == name_lower || matches_pattern(&c.pattern, name))
        .ok_or_else(|| format!("Footprint '{}' not found", name))?;

    // Build options
    let options = AsciiOptions {
        max_width,
        max_height,
        ..Default::default()
    };

    // Render and print
    let ascii = render_ascii(component, &options);
    println!("{}", ascii);

    Ok(())
}

// Helper functions

fn open_or_create_pcblib(path: &Path) -> Result<PcbLib, Box<dyn std::error::Error>> {
    if path.exists() {
        open_pcblib(path)
    } else {
        load_blank_pcblib()
    }
}

fn save_pcblib(path: &Path, lib: &PcbLib) -> Result<(), Box<dyn std::error::Error>> {
    Ok(lib.save_to_file(path)?)
}

/// Simple wildcard pattern matching (supports * and ?).
fn matches_pattern(text: &str, pattern: &str) -> bool {
    let text = text.to_lowercase();
    let pattern = pattern.to_lowercase();

    fn matches(text: &[char], pattern: &[char]) -> bool {
        match (text.first(), pattern.first()) {
            (None, None) => true,
            (None, Some('*')) => matches(text, &pattern[1..]),
            (None, Some(_)) => false,
            (Some(_), None) => false,
            (Some(_), Some('*')) => {
                // * can match zero or more characters
                matches(text, &pattern[1..]) || matches(&text[1..], pattern)
            }
            (Some(_), Some('?')) => {
                // ? matches exactly one character
                matches(&text[1..], &pattern[1..])
            }
            (Some(t), Some(p)) => *t == *p && matches(&text[1..], &pattern[1..]),
        }
    }

    let text_chars: Vec<char> = text.chars().collect();
    let pattern_chars: Vec<char> = pattern.chars().collect();
    matches(&text_chars, &pattern_chars)
}

// ═══════════════════════════════════════════════════════════════════════════
// JSON INPUT STRUCTURES (for LLM tool calling and structured output)
// ═══════════════════════════════════════════════════════════════════════════

/// JSON schema for a pad in a footprint.
/// All coordinates are in millimeters.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PadJson {
    /// Pad designator (e.g., "1", "2", "A1")
    pub designator: String,
    /// X position in mm (can be negative)
    pub x: f64,
    /// Y position in mm (can be negative)
    pub y: f64,
    /// Pad width in mm
    pub width: f64,
    /// Pad height in mm
    pub height: f64,
    /// Pad shape: "round", "rectangular", "rounded_rect", "octagonal"
    #[serde(default = "default_pad_shape")]
    pub shape: String,
    /// Hole diameter in mm (0 or omit for SMD pad)
    #[serde(default)]
    pub hole: f64,
    /// Rotation angle in degrees (optional)
    #[serde(default)]
    pub rotation: f64,
}

fn default_pad_shape() -> String {
    "rectangular".to_string()
}

/// JSON schema for a silkscreen line.
/// All coordinates are in millimeters.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct LineJson {
    /// Start X in mm
    pub x1: f64,
    /// Start Y in mm
    pub y1: f64,
    /// End X in mm
    pub x2: f64,
    /// End Y in mm
    pub y2: f64,
    /// Line width in mm
    #[serde(default = "default_line_width")]
    pub width: f64,
}

fn default_line_width() -> f64 {
    0.15
}

/// JSON schema for a silkscreen arc.
/// All coordinates are in millimeters.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ArcJson {
    /// Center X in mm
    pub x: f64,
    /// Center Y in mm
    pub y: f64,
    /// Radius in mm
    pub radius: f64,
    /// Start angle in degrees (0 = right, 90 = up)
    pub start_angle: f64,
    /// End angle in degrees
    pub end_angle: f64,
    /// Line width in mm
    #[serde(default = "default_line_width")]
    pub width: f64,
}

/// JSON schema for text on a PCB footprint.
/// All coordinates are in millimeters.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TextJson {
    /// X position in mm
    pub x: f64,
    /// Y position in mm
    pub y: f64,
    /// Text content
    pub text: String,
    /// Text height in mm
    #[serde(default = "default_text_height")]
    pub height: f64,
    /// Rotation angle in degrees
    #[serde(default)]
    pub rotation: f64,
    /// Stroke width in mm (for stroke font)
    #[serde(default = "default_stroke_width")]
    pub stroke_width: f64,
    /// Layer: "top_overlay", "bottom_overlay", "top", "bottom"
    #[serde(default = "default_text_layer")]
    pub layer: String,
    /// Mirror the text
    #[serde(default)]
    pub mirrored: bool,
}

fn default_text_height() -> f64 {
    1.0
}

fn default_stroke_width() -> f64 {
    0.15
}

fn default_text_layer() -> String {
    "top_overlay".to_string()
}

// ═══════════════════════════════════════════════════════════════════════════
// HIGH-LEVEL JSON STRUCTURES (datasheet-style specifications)
// ═══════════════════════════════════════════════════════════════════════════

/// JSON schema for a row of pads.
/// Values can include unit suffixes (mm, mil, in) or be plain numbers (interpreted as mm).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PadRowJson {
    /// Number of pads
    pub count: usize,
    /// Center-to-center distance between pads (with optional unit: "0.5mm", "50mil")
    pub pitch: String,
    /// Pad width (with optional unit)
    pub pad_width: String,
    /// Pad height (with optional unit)
    pub pad_height: String,
    /// Row direction: "horizontal" or "vertical"
    #[serde(default = "default_direction")]
    pub direction: String,
    /// Starting pad designator number
    #[serde(default = "default_start")]
    pub start: u32,
    /// X position of first pad (with optional unit, default "0mm")
    #[serde(default)]
    pub x: String,
    /// Y position of first pad (with optional unit, default "0mm")
    #[serde(default)]
    pub y: String,
    /// Pad shape
    #[serde(default = "default_pad_shape_str")]
    pub shape: String,
    /// Hole diameter for through-hole pads (with optional unit, omit or "0" for SMD)
    #[serde(default)]
    pub hole: String,
    /// Use spacing (edge-to-edge) instead of pitch (center-to-center)
    #[serde(default)]
    pub use_spacing: bool,
}

/// JSON schema for dual rows of pads (SOIC, DIP style).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DualRowJson {
    /// Number of pads on each side
    pub pads_per_side: usize,
    /// Center-to-center distance between adjacent pads (with optional unit)
    pub pitch: String,
    /// Distance between row centers / lead span (with optional unit)
    pub row_spacing: String,
    /// Pad width for SMD (with optional unit)
    #[serde(default)]
    pub pad_width: Option<String>,
    /// Pad height for SMD (with optional unit)
    #[serde(default)]
    pub pad_height: Option<String>,
    /// Pad diameter for through-hole (with optional unit)
    #[serde(default)]
    pub pad_diameter: Option<String>,
    /// Hole diameter for through-hole (with optional unit, omit for SMD)
    #[serde(default)]
    pub hole: Option<String>,
    /// Pad shape
    #[serde(default = "default_pad_shape_str")]
    pub shape: String,
}

/// JSON schema for quad pads (QFP style).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct QuadPadsJson {
    /// Number of pads on each side
    pub pads_per_side: usize,
    /// Center-to-center distance between adjacent pads (with optional unit)
    pub pitch: String,
    /// Distance between opposite row centers / lead span (with optional unit)
    pub span: String,
    /// Pad width - perpendicular to body edge (with optional unit)
    pub pad_width: String,
    /// Pad height - along body edge (with optional unit)
    pub pad_height: String,
    /// Pad shape
    #[serde(default = "default_pad_shape_str")]
    pub shape: String,
}

/// JSON schema for a grid of pads (BGA style).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PadGridJson {
    /// Number of rows (A, B, C, ...)
    pub rows: usize,
    /// Number of columns (1, 2, 3, ...)
    pub cols: usize,
    /// Center-to-center distance between pads (with optional unit)
    pub pitch: String,
    /// Pad diameter (with optional unit)
    pub pad_diameter: String,
    /// Pad shape (default: "round")
    #[serde(default = "default_round_shape")]
    pub shape: String,
    /// Skip pads within this radius from center (with optional unit, for thermal pad)
    #[serde(default)]
    pub skip_center: String,
}

fn default_direction() -> String {
    "horizontal".to_string()
}

fn default_start() -> u32 {
    1
}

fn default_pad_shape_str() -> String {
    "rectangular".to_string()
}

fn default_round_shape() -> String {
    "round".to_string()
}

/// JSON schema for a complete footprint definition.
/// This is the top-level structure for the add-json command.
///
/// Supports both low-level (individual pads) and high-level (datasheet-style) specifications.
/// High-level constructs are processed first, then individual pads are added.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FootprintJson {
    /// Footprint name (pattern)
    pub name: String,
    /// Footprint description (optional)
    #[serde(default)]
    pub description: String,

    // ─── Low-level primitives (individual elements) ───
    /// List of individual pads (coordinates in mm)
    #[serde(default)]
    pub pads: Vec<PadJson>,
    /// List of silkscreen lines
    #[serde(default)]
    pub lines: Vec<LineJson>,
    /// List of silkscreen arcs
    #[serde(default)]
    pub arcs: Vec<ArcJson>,
    /// List of text elements
    #[serde(default)]
    pub texts: Vec<TextJson>,

    // ─── High-level constructs (datasheet-style, with unit support) ───
    /// Rows of equally-spaced pads
    #[serde(default)]
    pub pad_rows: Vec<PadRowJson>,
    /// Dual rows of pads (SOIC, DIP style)
    #[serde(default)]
    pub dual_rows: Vec<DualRowJson>,
    /// Quad arrangements of pads (QFP style)
    #[serde(default)]
    pub quad_pads: Vec<QuadPadsJson>,
    /// Grids of pads (BGA style)
    #[serde(default)]
    pub pad_grids: Vec<PadGridJson>,
}

/// Add a complete footprint from JSON input.
pub fn cmd_add_json(
    path: &Path,
    json_file: Option<String>,
    json_str: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    use std::io::{self, Read as IoRead};

    // Read JSON from file, stdin, or command line
    let json_content = match (json_file, json_str) {
        (_, Some(s)) => s,
        (Some(ref path), None) if path == "-" => {
            let mut buffer = String::new();
            io::stdin()
                .read_to_string(&mut buffer)
                .map_err(|e| format!("Error reading from stdin: {}", e))?;
            buffer
        }
        (Some(ref file_path), None) => std::fs::read_to_string(file_path)
            .map_err(|e| format!("Error reading file '{}': {}", file_path, e))?,
        (None, None) => {
            return Err("Must provide either --file <path> or --json <string>"
                .to_string()
                .into());
        }
    };

    // Parse JSON
    let footprint_def: FootprintJson =
        serde_json::from_str(&json_content).map_err(|e| format!("Invalid JSON: {}", e))?;

    // Open or create library
    let mut lib = open_or_create_pcblib(path)?;

    // Check if footprint already exists
    if lib
        .components
        .iter()
        .any(|c| c.pattern == footprint_def.name)
    {
        return Err(format!("Footprint '{}' already exists", footprint_def.name).into());
    }

    // Create footprint using FootprintBuilder
    let mut builder = FootprintBuilder::new(&footprint_def.name);

    if !footprint_def.description.is_empty() {
        builder = builder.description(&footprint_def.description);
    }

    // ─── Process high-level constructs first (datasheet-style) ───

    // Add pad rows
    for row in &footprint_def.pad_rows {
        let pitch_mm = parse_unit_value_or_mm(&row.pitch)?;
        let pad_width_mm = parse_unit_value_or_mm(&row.pad_width)?;
        let pad_height_mm = parse_unit_value_or_mm(&row.pad_height)?;
        let x_mm = if row.x.is_empty() {
            0.0
        } else {
            parse_unit_value_or_mm(&row.x)?
        };
        let y_mm = if row.y.is_empty() {
            0.0
        } else {
            parse_unit_value_or_mm(&row.y)?
        };
        let hole_mm = if row.hole.is_empty() {
            0.0
        } else {
            parse_unit_value_or_mm(&row.hole)?
        };
        let dir = PadRowDirection::try_parse(&row.direction)
            .ok_or_else(|| format!("Invalid direction '{}' in pad_row", row.direction))?;
        let shape = parse_pad_shape(&row.shape)?;

        if hole_mm > 0.0 {
            let pad_diameter = pad_width_mm.max(pad_height_mm);
            if row.use_spacing {
                let pad_along_row = match dir {
                    PadRowDirection::Horizontal => pad_width_mm,
                    PadRowDirection::Vertical => pad_height_mm,
                };
                let effective_pitch = pitch_mm + pad_along_row;
                builder.add_th_pad_row(
                    row.count,
                    effective_pitch,
                    pad_diameter,
                    hole_mm,
                    x_mm,
                    y_mm,
                    dir,
                    row.start,
                    shape,
                );
            } else {
                builder.add_th_pad_row(
                    row.count,
                    pitch_mm,
                    pad_diameter,
                    hole_mm,
                    x_mm,
                    y_mm,
                    dir,
                    row.start,
                    shape,
                );
            }
        } else if row.use_spacing {
            builder.add_pad_row_with_spacing(
                row.count,
                pitch_mm,
                pad_width_mm,
                pad_height_mm,
                x_mm,
                y_mm,
                dir,
                row.start,
                shape,
            );
        } else {
            builder.add_pad_row(
                row.count,
                pitch_mm,
                pad_width_mm,
                pad_height_mm,
                x_mm,
                y_mm,
                dir,
                row.start,
                shape,
            );
        }
    }

    // Add dual rows
    for dual in &footprint_def.dual_rows {
        let pitch_mm = parse_unit_value_or_mm(&dual.pitch)?;
        let row_spacing_mm = parse_unit_value_or_mm(&dual.row_spacing)?;
        let shape = parse_pad_shape(&dual.shape)?;

        if let Some(ref hole_str) = dual.hole {
            // Through-hole
            let hole_mm = parse_unit_value_or_mm(hole_str)?;
            let pad_dia_mm = if let Some(ref d) = dual.pad_diameter {
                parse_unit_value_or_mm(d)?
            } else if let Some(ref w) = dual.pad_width {
                parse_unit_value_or_mm(w)?
            } else {
                return Err("Through-hole dual_row requires pad_diameter or pad_width"
                    .to_string()
                    .into());
            };
            builder.add_dual_row_th(
                dual.pads_per_side,
                pitch_mm,
                row_spacing_mm,
                pad_dia_mm,
                hole_mm,
                shape,
            );
        } else {
            // SMD
            let pad_width_mm = dual
                .pad_width
                .as_ref()
                .ok_or("SMD dual_row requires pad_width")?;
            let pad_height_mm = dual
                .pad_height
                .as_ref()
                .ok_or("SMD dual_row requires pad_height")?;
            let pad_width_mm = parse_unit_value_or_mm(pad_width_mm)?;
            let pad_height_mm = parse_unit_value_or_mm(pad_height_mm)?;
            builder.add_dual_row_smd(
                dual.pads_per_side,
                pitch_mm,
                row_spacing_mm,
                pad_width_mm,
                pad_height_mm,
                shape,
            );
        }
    }

    // Add quad pads
    for quad in &footprint_def.quad_pads {
        let pitch_mm = parse_unit_value_or_mm(&quad.pitch)?;
        let span_mm = parse_unit_value_or_mm(&quad.span)?;
        let pad_width_mm = parse_unit_value_or_mm(&quad.pad_width)?;
        let pad_height_mm = parse_unit_value_or_mm(&quad.pad_height)?;
        let shape = parse_pad_shape(&quad.shape)?;
        builder.add_quad_pads_smd(
            quad.pads_per_side,
            pitch_mm,
            span_mm,
            pad_width_mm,
            pad_height_mm,
            shape,
        );
    }

    // Add pad grids
    for grid in &footprint_def.pad_grids {
        let pitch_mm = parse_unit_value_or_mm(&grid.pitch)?;
        let pad_diameter_mm = parse_unit_value_or_mm(&grid.pad_diameter)?;
        let skip_center_mm = if grid.skip_center.is_empty() {
            0.0
        } else {
            parse_unit_value_or_mm(&grid.skip_center)?
        };
        let shape = parse_pad_shape(&grid.shape)?;
        builder.add_pad_grid(
            grid.rows,
            grid.cols,
            pitch_mm,
            pad_diameter_mm,
            shape,
            skip_center_mm,
        );
    }

    // ─── Process low-level primitives (individual pads, lines, etc.) ───

    // Add individual pads
    for pad in &footprint_def.pads {
        let shape = parse_pad_shape(&pad.shape)?;

        if pad.hole > 0.0 {
            builder.add_th_pad(
                &pad.designator,
                pad.x,
                pad.y,
                pad.width.max(pad.height),
                pad.hole,
                shape,
            );
        } else {
            builder.add_smd_pad(&pad.designator, pad.x, pad.y, pad.width, pad.height, shape);
        }
    }

    // Add silkscreen lines
    for line in &footprint_def.lines {
        builder.add_silkscreen_line(line.x1, line.y1, line.x2, line.y2, line.width);
    }

    // Add arcs
    for arc in &footprint_def.arcs {
        builder.add_silkscreen_arc(
            arc.x,
            arc.y,
            arc.radius,
            arc.start_angle,
            arc.end_angle,
            arc.width,
        );
    }

    let mut det = ();
    let mut component = builder.build_deterministic(&mut det);

    // Add text elements (not supported by FootprintBuilder, add directly)
    for text_def in &footprint_def.texts {
        let layer = parse_pcb_layer(&text_def.layer)?;

        let text = PcbText::new(
            text_def.x,
            text_def.y,
            &text_def.text,
            text_def.height,
            text_def.stroke_width,
            text_def.rotation,
            text_def.mirrored,
            layer,
        );
        component.add_primitive(PcbRecord::Text(text));
    }

    let pad_count = component.pad_count();
    let line_count = footprint_def.lines.len();
    let arc_count = footprint_def.arcs.len();
    let text_count = footprint_def.texts.len();

    lib.components.push(component);
    save_pcblib(path, &lib)?;

    // Build summary of added primitives
    let mut parts = vec![format!("{} pads", pad_count)];
    if line_count > 0 {
        parts.push(format!("{} lines", line_count));
    }
    if arc_count > 0 {
        parts.push(format!("{} arcs", arc_count));
    }
    if text_count > 0 {
        parts.push(format!("{} texts", text_count));
    }

    println!(
        "Added footprint '{}' with {} to {}",
        footprint_def.name,
        parts.join(", "),
        path.display()
    );

    Ok(())
}

fn parse_pcb_layer(s: &str) -> Result<Layer, String> {
    match s.to_lowercase().replace('_', "").as_str() {
        "topoverlay" | "silkscreen" | "top_overlay" => Ok(Layer::TOP_OVERLAY),
        "bottomoverlay" | "bottom_overlay" => Ok(Layer::BOTTOM_OVERLAY),
        "top" | "toplayer" => Ok(Layer::TOP_LAYER),
        "bottom" | "bottomlayer" => Ok(Layer::BOTTOM_LAYER),
        _ => Err(format!(
            "Unknown layer: {}. Use: top_overlay, bottom_overlay, top, bottom",
            s
        )),
    }
}

fn parse_pad_shape(s: &str) -> Result<PcbPadShape, String> {
    match s.to_lowercase().as_str() {
        "round" => Ok(PcbPadShape::Round),
        "rectangular" | "rect" => Ok(PcbPadShape::Rectangular),
        "rounded_rect" | "roundedrect" | "rounded_rectangle" => Ok(PcbPadShape::RoundedRectangle),
        "octagonal" | "oct" => Ok(PcbPadShape::Octagonal),
        _ => Err(format!(
            "Unknown pad shape: {}. Use: round, rectangular, rounded_rect, octagonal",
            s
        )),
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// HIGH-LEVEL PAD COMMANDS
// ═══════════════════════════════════════════════════════════════════════════

/// Parse a value with unit suffix (e.g., "0.5mm", "50mil", "0.05in").
fn parse_unit_value(s: &str) -> Result<f64, String> {
    let (coord, _unit) =
        Unit::parse_with_unit(s).map_err(|e| format!("Invalid value '{}': {:?}", s, e))?;
    Ok(coord.to_mms())
}

/// Parse a value with optional unit suffix, defaulting to mm for plain numbers.
/// Handles: "0.5mm", "50mil", "0.05in", "0.5" (interpreted as mm)
fn parse_unit_value_or_mm(s: &str) -> Result<f64, String> {
    let s = s.trim();

    // Try parsing with unit suffix first
    if let Ok((coord, _unit)) = Unit::parse_with_unit(s) {
        return Ok(coord.to_mms());
    }

    // If no unit suffix, try as plain number (interpreted as mm)
    s.parse::<f64>().map_err(|_| {
        format!(
            "Invalid value '{}': expected number with optional unit (e.g., '0.5mm', '50mil')",
            s
        )
    })
}

/// Add a row of pads.
#[allow(clippy::too_many_arguments)]
pub fn cmd_add_pad_row(
    path: &Path,
    footprint: &str,
    count: usize,
    pitch: &str,
    pad_width: &str,
    pad_height: &str,
    direction: &str,
    start: u32,
    x: &str,
    y: &str,
    shape_str: &str,
    hole: &str,
    use_spacing: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut lib = open_pcblib(path)?;

    let component = lib
        .components
        .iter_mut()
        .find(|c| c.pattern == footprint)
        .ok_or_else(|| format!("Footprint '{}' not found", footprint))?;

    // Parse all values with units
    let pitch_mm = parse_unit_value(pitch)?;
    let pad_width_mm = parse_unit_value(pad_width)?;
    let pad_height_mm = parse_unit_value(pad_height)?;
    let x_mm = parse_unit_value(x)?;
    let y_mm = parse_unit_value(y)?;
    let hole_mm = parse_unit_value(hole)?;

    let dir = PadRowDirection::try_parse(direction).ok_or_else(|| {
        format!(
            "Invalid direction '{}'. Use: horizontal (h/x) or vertical (v/y)",
            direction
        )
    })?;

    let shape = parse_pad_shape(shape_str)?;

    // Create pad row using FootprintBuilder
    let mut builder = FootprintBuilder::new(footprint);

    if hole_mm > 0.0 {
        // Through-hole pads
        let pad_diameter = pad_width_mm.max(pad_height_mm);
        if use_spacing {
            // Convert spacing to pitch
            let pad_along_row = match dir {
                PadRowDirection::Horizontal => pad_width_mm,
                PadRowDirection::Vertical => pad_height_mm,
            };
            let effective_pitch = pitch_mm + pad_along_row;
            builder.add_th_pad_row(
                count,
                effective_pitch,
                pad_diameter,
                hole_mm,
                x_mm,
                y_mm,
                dir,
                start,
                shape,
            );
        } else {
            builder.add_th_pad_row(
                count,
                pitch_mm,
                pad_diameter,
                hole_mm,
                x_mm,
                y_mm,
                dir,
                start,
                shape,
            );
        }
    } else {
        // SMD pads
        if use_spacing {
            builder.add_pad_row_with_spacing(
                count,
                pitch_mm,
                pad_width_mm,
                pad_height_mm,
                x_mm,
                y_mm,
                dir,
                start,
                shape,
            );
        } else {
            builder.add_pad_row(
                count,
                pitch_mm,
                pad_width_mm,
                pad_height_mm,
                x_mm,
                y_mm,
                dir,
                start,
                shape,
            );
        }
    }

    // Extract pads from the built component and add to existing footprint
    let mut det = ();
    let temp = builder.build_deterministic(&mut det);
    for prim in temp.primitives {
        component.add_primitive(prim);
    }

    save_pcblib(path, &lib)?;

    let term = if use_spacing { "spacing" } else { "pitch" };
    println!(
        "Added {} pads to '{}' ({} {} {}, direction: {})",
        count,
        footprint,
        pitch,
        term,
        if hole_mm > 0.0 { "through-hole" } else { "SMD" },
        direction
    );

    Ok(())
}

/// Add dual rows of pads (SOIC, DIP style).
#[allow(clippy::too_many_arguments)]
pub fn cmd_add_dual_row(
    path: &Path,
    footprint: &str,
    pads_per_side: usize,
    pitch: &str,
    row_spacing: &str,
    pad_width: Option<&str>,
    pad_height: Option<&str>,
    pad_diameter: Option<&str>,
    hole: Option<&str>,
    shape_str: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut lib = open_pcblib(path)?;

    let component = lib
        .components
        .iter_mut()
        .find(|c| c.pattern == footprint)
        .ok_or_else(|| format!("Footprint '{}' not found", footprint))?;

    let pitch_mm = parse_unit_value(pitch)?;
    let row_spacing_mm = parse_unit_value(row_spacing)?;
    let shape = parse_pad_shape(shape_str)?;

    let mut builder = FootprintBuilder::new(footprint);

    // Determine if through-hole or SMD based on hole parameter
    if let Some(hole_str) = hole {
        // Through-hole
        let hole_mm = parse_unit_value(hole_str)?;
        let pad_dia_mm = if let Some(d) = pad_diameter {
            parse_unit_value(d)?
        } else if let Some(w) = pad_width {
            parse_unit_value(w)?
        } else {
            return Err("Through-hole pads require --pad-diameter or --pad-width"
                .to_string()
                .into());
        };

        builder.add_dual_row_th(
            pads_per_side,
            pitch_mm,
            row_spacing_mm,
            pad_dia_mm,
            hole_mm,
            shape,
        );
    } else {
        // SMD
        let pad_w = pad_width.ok_or("SMD pads require --pad-width")?;
        let pad_h = pad_height.ok_or("SMD pads require --pad-height")?;
        let pad_width_mm = parse_unit_value(pad_w)?;
        let pad_height_mm = parse_unit_value(pad_h)?;

        builder.add_dual_row_smd(
            pads_per_side,
            pitch_mm,
            row_spacing_mm,
            pad_width_mm,
            pad_height_mm,
            shape,
        );
    }

    // Add pads to existing footprint
    let mut det = ();
    let temp = builder.build_deterministic(&mut det);
    for prim in temp.primitives {
        component.add_primitive(prim);
    }

    save_pcblib(path, &lib)?;

    let total_pads = pads_per_side * 2;
    let pad_type = if hole.is_some() {
        "through-hole"
    } else {
        "SMD"
    };
    println!(
        "Added dual row ({} {} pads, {} per side) to '{}' (pitch: {}, row spacing: {})",
        total_pads, pad_type, pads_per_side, footprint, pitch, row_spacing
    );

    Ok(())
}

/// Add quad arrangement of pads (QFP style).
#[allow(clippy::too_many_arguments)]
pub fn cmd_add_quad_pads(
    path: &Path,
    footprint: &str,
    pads_per_side: usize,
    pitch: &str,
    span: &str,
    pad_width: &str,
    pad_height: &str,
    shape_str: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut lib = open_pcblib(path)?;

    let component = lib
        .components
        .iter_mut()
        .find(|c| c.pattern == footprint)
        .ok_or_else(|| format!("Footprint '{}' not found", footprint))?;

    let pitch_mm = parse_unit_value(pitch)?;
    let span_mm = parse_unit_value(span)?;
    let pad_width_mm = parse_unit_value(pad_width)?;
    let pad_height_mm = parse_unit_value(pad_height)?;
    let shape = parse_pad_shape(shape_str)?;

    let mut builder = FootprintBuilder::new(footprint);
    builder.add_quad_pads_smd(
        pads_per_side,
        pitch_mm,
        span_mm,
        pad_width_mm,
        pad_height_mm,
        shape,
    );

    // Add pads to existing footprint
    let mut det = ();
    let temp = builder.build_deterministic(&mut det);
    for prim in temp.primitives {
        component.add_primitive(prim);
    }

    save_pcblib(path, &lib)?;

    let total_pads = pads_per_side * 4;
    println!(
        "Added quad arrangement ({} SMD pads, {} per side) to '{}' (pitch: {}, span: {})",
        total_pads, pads_per_side, footprint, pitch, span
    );

    Ok(())
}

/// Add a grid of pads (BGA style).
#[allow(clippy::too_many_arguments)]
pub fn cmd_add_pad_grid(
    path: &Path,
    footprint: &str,
    rows: usize,
    cols: usize,
    pitch: &str,
    pad_diameter: &str,
    shape_str: &str,
    skip_center: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut lib = open_pcblib(path)?;

    let component = lib
        .components
        .iter_mut()
        .find(|c| c.pattern == footprint)
        .ok_or_else(|| format!("Footprint '{}' not found", footprint))?;

    let pitch_mm = parse_unit_value(pitch)?;
    let pad_diameter_mm = parse_unit_value(pad_diameter)?;
    let skip_center_mm = parse_unit_value(skip_center)?;
    let shape = parse_pad_shape(shape_str)?;

    let mut builder = FootprintBuilder::new(footprint);
    builder.add_pad_grid(rows, cols, pitch_mm, pad_diameter_mm, shape, skip_center_mm);

    // Add pads to existing footprint
    let mut det = ();
    let temp = builder.build_deterministic(&mut det);
    let pad_count = temp.primitives.len();
    for prim in temp.primitives {
        component.add_primitive(prim);
    }

    save_pcblib(path, &lib)?;

    let max_pads = rows * cols;
    let skipped = max_pads - pad_count;
    if skipped > 0 {
        println!(
            "Added {}x{} grid ({} pads, {} skipped in center) to '{}' (pitch: {})",
            rows, cols, pad_count, skipped, footprint, pitch
        );
    } else {
        println!(
            "Added {}x{} grid ({} pads) to '{}' (pitch: {})",
            rows, cols, pad_count, footprint, pitch
        );
    }

    Ok(())
}