thru-core 0.2.13

Shared implementation for the Thru CLI
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
//! CLI argument parsing and command definitions

use clap::{Parser, Subcommand, ValueEnum};
use std::path::PathBuf;

/// Parse and validate chunk size (1024-31000 bytes)
fn parse_chunk_size(s: &str) -> Result<usize, String> {
    let size: usize = s
        .parse()
        .map_err(|_| format!("'{}' is not a valid number", s))?;
    if size < 1024 {
        return Err(format!("chunk size {} is too small (minimum: 1024)", size));
    }
    if size > 31000 {
        return Err(format!("chunk size {} is too large (maximum: 31000)", size));
    }
    Ok(size)
}

/// Thru CLI - Command-line interface for the Thru blockchain
#[derive(Parser)]
#[command(name = "thru")]
#[command(about = "Command-line interface for the Thru blockchain")]
#[command(version = thru_base::get_version!())]
pub struct Cli {
    /// Output results in JSON format
    #[arg(long, global = true)]
    pub json: bool,

    /// Suppress non-essential output (disables version check notifications)
    #[arg(long, global = true)]
    pub quiet: bool,

    /// Override RPC URL for this invocation
    #[arg(long = "url", global = true)]
    pub url: Option<String>,

    /// Use a named network profile for this invocation
    #[arg(long = "network", global = true)]
    pub network: Option<String>,

    #[command(subcommand)]
    pub command: Commands,
}

/// Available CLI commands
#[derive(Subcommand)]
pub enum Commands {
    /// Get version information from the Thru node
    #[command(name = "getversion")]
    GetVersion,

    /// Get health status of the Thru node
    #[command(name = "gethealth")]
    GetHealth,

    /// Get cluster block heights
    #[command(name = "getheight")]
    GetHeight,

    /// Get account information for a specific account
    #[command(name = "getaccountinfo")]
    GetAccountInfo {
        /// Account identifier (key name from config or public key)
        /// If omitted, uses the 'default' key from config
        account: Option<String>,

        /// Starting offset in account data to display (in bytes)
        #[arg(long)]
        data_start: Option<usize>,

        /// Length of account data to display (in bytes)
        #[arg(long)]
        data_len: Option<usize>,
    },

    /// Get balance for a specific account
    #[command(name = "getbalance")]
    GetBalance {
        /// Account identifier (key name from config or public key)
        /// If omitted, uses the 'default' key from config
        account: Option<String>,
    },

    /// Get slot metrics (state counters, collected fees)
    #[command(name = "getslotmetrics")]
    GetSlotMetrics {
        /// Start slot number (required)
        slot: u64,

        /// End slot number (optional, if provided returns range of slots)
        end_slot: Option<u64>,
    },

    /// Transfer tokens between accounts
    #[command(name = "transfer")]
    Transfer {
        /// Source key name from configuration
        src: String,

        /// Destination (key name from config or public address in taXX format)
        dst: String,

        /// Amount to transfer
        value: u64,
    },

    /// Program upload and management commands
    #[command(name = "uploader")]
    Uploader {
        #[command(subcommand)]
        subcommand: UploaderCommands,
    },

    /// ABI management commands
    #[command(name = "abi")]
    Abi {
        #[command(subcommand)]
        subcommand: AbiCommands,
    },

    /// Key management commands
    #[command(name = "keys")]
    Keys {
        #[command(subcommand)]
        subcommand: KeysCommands,
    },

    /// Account management commands
    #[command(name = "account")]
    Account {
        #[command(subcommand)]
        subcommand: AccountCommands,
    },

    /// Program management commands
    #[command(name = "program")]
    Program {
        #[command(subcommand)]
        subcommand: ProgramCommands,
    },

    /// Transaction signing and execution commands
    #[command(name = "txn")]
    Txn {
        #[command(subcommand)]
        subcommand: TxnCommands,
    },

    /// Utility commands for format conversion
    #[command(name = "util")]
    Util {
        #[command(subcommand)]
        subcommand: UtilCommands,
    },

    /// Token program commands
    #[command(name = "token")]
    Token {
        #[command(subcommand)]
        subcommand: TokenCommands,
    },

    /// Faucet program commands
    #[command(name = "faucet")]
    Faucet {
        #[command(subcommand)]
        subcommand: FaucetCommands,
    },

    /// Registrar program commands
    #[command(name = "registrar")]
    Registrar {
        #[command(subcommand)]
        subcommand: RegistrarCommands,
    },

    /// Name service program commands
    #[command(name = "nameservice")]
    NameService {
        #[command(subcommand)]
        subcommand: NameServiceCommands,
    },

    /// Wrapped Thru (WTHRU) program commands
    #[command(name = "wthru")]
    Wthru {
        #[command(subcommand)]
        subcommand: WthruCommands,
    },

    /// Developer tools for toolchain and project management
    #[command(name = "dev")]
    Dev {
        #[command(subcommand)]
        subcommand: DevCommands,
    },

    /// Network profile management commands
    #[command(name = "network")]
    Network {
        #[command(subcommand)]
        subcommand: NetworkCommands,
    },

    /// Debug commands for transaction analysis
    #[command(name = "debug")]
    Debug {
        #[command(subcommand)]
        subcommand: DebugCommands,
    },
}

/// Program-related subcommands
#[derive(Subcommand)]
pub enum ProgramCommands {
    /// Create a new program from a program binary
    Create {
        /// Manager program public key (optional)
        #[arg(long)]
        manager: Option<String>,

        /// Make the program ephemeral
        #[arg(long)]
        ephemeral: bool,

        /// Seed for meta account derivation
        seed: String,

        /// Authority account name from config (optional, defaults to 'default')
        #[arg(long)]
        authority: Option<String>,

        /// Program file to upload and create managed program from
        program_file: String,

        /// Chunk size for upload (1024-31000 bytes, default: 30720)
        #[arg(long, value_parser = parse_chunk_size, default_value = "30720")]
        chunk_size: usize,
    },

    /// Upgrade an existing managed program
    Upgrade {
        /// Manager program public key (optional)
        #[arg(long)]
        manager: Option<String>,

        /// Make the program ephemeral
        #[arg(long)]
        ephemeral: bool,

        /// Seed for meta and program account derivation
        seed: String,

        /// Program file to upload and upgrade managed program with
        program_file: String,

        /// Chunk size for upload (1024-31000 bytes, default: 30720)
        #[arg(long, value_parser = parse_chunk_size, default_value = "30720")]
        chunk_size: usize,
    },

    /// Pause or unpause a managed program
    SetPause {
        /// Manager program public key (optional)
        #[arg(long)]
        manager: Option<String>,

        /// Make the program ephemeral
        #[arg(long)]
        ephemeral: bool,

        /// Seed for meta and program account derivation
        seed: String,

        /// Set paused state (true to pause, false to unpause)
        paused: String,
    },

    /// Destroy a managed program and its meta account
    Destroy {
        /// Manager program public key (optional)
        #[arg(long)]
        manager: Option<String>,

        /// Make the program ephemeral
        #[arg(long)]
        ephemeral: bool,

        /// Seed for meta and program account derivation
        seed: String,

        /// Fee payer account name from config (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,
    },

    /// Finalize a managed program (make it immutable)
    Finalize {
        /// Manager program public key (optional)
        #[arg(long)]
        manager: Option<String>,

        /// Make the program ephemeral
        #[arg(long)]
        ephemeral: bool,

        /// Seed for meta and program account derivation
        seed: String,

        /// Fee payer account name from config (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,
    },

    /// Set authority candidate for a managed program
    SetAuthority {
        /// Manager program public key (optional)
        #[arg(long)]
        manager: Option<String>,

        /// Make the program ephemeral
        #[arg(long)]
        ephemeral: bool,

        /// Seed for meta and program account derivation
        seed: String,

        /// New authority candidate public key
        authority_candidate: String,
    },

    /// Claim authority for a managed program
    ClaimAuthority {
        /// Manager program public key (optional)
        #[arg(long)]
        manager: Option<String>,

        /// Make the program ephemeral
        #[arg(long)]
        ephemeral: bool,

        /// Seed for meta and program account derivation
        seed: String,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,
    },

    /// Get the program derived address
    DeriveAddress {
        /// Program public key
        program_id: String,

        /// Seed (hex string or UTF-8 string)
        seed: String,

        /// Ephemeral flag
        #[arg(long)]
        ephemeral: bool,
    },

    /// Derive both meta and program account addresses from a seed
    DeriveManagerAccounts {
        /// Manager program public key (optional, uses config default if not specified)
        #[arg(long)]
        manager: Option<String>,

        /// Seed for account derivation (UTF-8 string, max 32 bytes)
        seed: String,

        /// Ephemeral flag
        #[arg(long)]
        ephemeral: bool,
    },

    /// Convert a UTF-8 seed string into zero-padded 32-byte hex
    SeedToHex {
        /// Seed string (UTF-8, maximum 32 bytes)
        seed: String,
    },

    /// Derive the managed program account address from a seed
    DeriveProgramAccount {
        /// Manager program public key (optional, uses config default if not specified)
        #[arg(long)]
        manager: Option<String>,

        /// Seed for account derivation (UTF-8 string, max 32 bytes)
        seed: String,

        /// Ephemeral flag
        #[arg(long)]
        ephemeral: bool,
    },

    /// Check status of program and related accounts
    Status {
        /// Manager program public key (optional, uses config default if not specified)
        #[arg(long)]
        manager: Option<String>,

        /// Seed for account derivation (UTF-8 string, max 32 bytes)
        seed: String,

        /// Ephemeral flag
        #[arg(long)]
        ephemeral: bool,
    },
}

/// ABI-related subcommands
#[derive(Subcommand)]
pub enum AbiCommands {
    /// On-chain ABI account management commands
    #[command(name = "account")]
    Account {
        #[command(subcommand)]
        subcommand: AbiAccountCommands,
    },

    /// Generate code from ABI type definitions
    Codegen {
        /// Input YAML files containing type definitions
        #[arg(short = 'f', long = "files", value_name = "FILE", required = true)]
        files: Vec<PathBuf>,

        /// Include directories for imported type files
        #[arg(short = 'i', long = "include-dir", value_name = "DIR")]
        include_dirs: Vec<PathBuf>,

        /// Target language for code generation
        #[arg(short = 'l', long = "language", value_enum)]
        language: AbiLanguage,

        /// Output directory for generated code
        #[arg(
            short = 'o',
            long = "output",
            value_name = "DIR",
            default_value = "generated"
        )]
        output_dir: PathBuf,

        /// Enable verbose output
        #[arg(short = 'v', long = "verbose")]
        verbose: bool,
    },

    /// Analyze ABI type definitions and show detailed type information
    Analyze {
        /// Input YAML files containing type definitions
        #[arg(short = 'f', long = "files", value_name = "FILE", required = true)]
        files: Vec<PathBuf>,

        /// Include directories for imported type files
        #[arg(short = 'i', long = "include-dir", value_name = "DIR")]
        include_dirs: Vec<PathBuf>,

        /// Print the shared layout IR after analysis
        #[arg(long = "print-ir")]
        print_ir: bool,

        /// Format to use when printing the shared layout IR
        #[arg(long = "ir-format", value_enum, default_value = "json")]
        ir_format: AbiIrFormat,

        /// Print the generated legacy + IR footprint helpers for a specific type
        #[arg(long = "print-footprint", value_name = "TYPE")]
        print_footprint: Option<String>,

        /// Print the generated legacy + IR validate helpers for a specific type
        #[arg(long = "print-validate", value_name = "TYPE")]
        print_validate: Option<String>,
    },

    /// Parse ABI binary data and print JSON reflection results
    Reflect {
        /// ABI file(s) to load
        #[arg(short = 'f', long = "abi-file", required = true)]
        abi_files: Vec<PathBuf>,

        /// Include directories for resolving imports
        #[arg(short = 'i', long = "include-dir")]
        include_dirs: Vec<PathBuf>,

        /// Type name to parse
        #[arg(short = 't', long = "type-name", required = true)]
        type_name: String,

        /// Binary data file to parse
        #[arg(short = 'd', long = "data-file", required = true)]
        data_file: PathBuf,

        /// Pretty print JSON output
        #[arg(short = 'p', long = "pretty")]
        pretty: bool,

        /// Show only values (no type information)
        #[arg(
            long = "values-only",
            conflicts_with_all = ["validate_only", "include_byte_offsets"]
        )]
        values_only: bool,

        /// Only validate buffer without decoding
        #[arg(
            long = "validate-only",
            conflicts_with_all = ["values_only", "include_byte_offsets"]
        )]
        validate_only: bool,

        /// Print dynamic parameters inferred from the buffer
        #[arg(long = "show-params")]
        show_params: bool,

        /// Include byte offset information in the output
        #[arg(
            long = "include-byte-offsets",
            conflicts_with_all = ["validate_only", "values_only"]
        )]
        include_byte_offsets: bool,
    },

    /// Flatten an ABI file by resolving all imports
    Flatten {
        /// Input ABI file
        #[arg(short = 'f', long = "file", required = true)]
        file: PathBuf,

        /// Include directories for resolving imports
        #[arg(short = 'i', long = "include-dir")]
        include_dirs: Vec<PathBuf>,

        /// Output file path
        #[arg(short = 'o', long = "output", required = true)]
        output: PathBuf,

        /// Verbose output
        #[arg(short = 'v', long = "verbose")]
        verbose: bool,
    },

    /// Prepare an ABI file for on-chain publishing
    #[command(name = "prep-for-publish")]
    PrepForPublish {
        /// Input ABI file
        #[arg(short = 'f', long = "file", required = true)]
        file: PathBuf,

        /// Include directories for resolving local imports
        #[arg(short = 'i', long = "include-dir")]
        include_dirs: Vec<PathBuf>,

        /// Target network for validation (e.g., "mainnet", "testnet")
        #[arg(short = 'n', long = "target-network", required = true)]
        target_network: String,

        /// Output file path
        #[arg(short = 'o', long = "output", required = true)]
        output: PathBuf,

        /// Verbose output
        #[arg(short = 'v', long = "verbose")]
        verbose: bool,
    },

    /// Create a dependency manifest for WASM consumption
    Bundle {
        /// Input ABI file
        #[arg(short = 'f', long = "file", required = true)]
        file: PathBuf,

        /// Include directories for resolving imports
        #[arg(short = 'i', long = "include-dir")]
        include_dirs: Vec<PathBuf>,

        /// Output manifest file path (JSON)
        #[arg(short = 'o', long = "output", required = true)]
        output: PathBuf,

        /// Verbose output
        #[arg(short = 'v', long = "verbose")]
        verbose: bool,
    },
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug)]
pub enum AbiAccountType {
    /// ABI account for a managed program
    Program,
    /// ABI account for an unmanaged target program
    #[value(name = "third-party")]
    ThirdParty,
    /// ABI account not associated with a program
    Standalone,
}

/// On-chain ABI account subcommands
#[derive(Subcommand)]
pub enum AbiAccountCommands {
    /// Create an ABI account
    Create {
        /// Program type (ephemeral matches the ABI account target)
        #[arg(long)]
        ephemeral: bool,

        /// ABI account type
        #[arg(long = "account-type", value_enum, default_value = "program")]
        account_type: AbiAccountType,

        /// Target program account public key (required for `third-party`)
        #[arg(long = "target-program")]
        target_program: Option<String>,

        /// Fee payer account (optional, defaults to config default)
        #[arg(long = "fee-payer")]
        fee_payer: Option<String>,

        /// Authority account name from config (`program` only, accepted as alias for `publisher`)
        #[arg(long, conflicts_with = "publisher")]
        authority: Option<String>,

        /// Publisher account name from config (`third-party` and `standalone` only)
        #[arg(long, conflicts_with = "authority")]
        publisher: Option<String>,

        /// Managed program seed, third-party 32-byte hex seed, or standalone seed string
        seed: String,

        /// ABI definition file to upload
        abi_file: String,
    },

    /// Upgrade an existing ABI account
    Upgrade {
        #[arg(long)]
        ephemeral: bool,

        #[arg(long = "account-type", value_enum, default_value = "program")]
        account_type: AbiAccountType,

        #[arg(long = "target-program")]
        target_program: Option<String>,

        #[arg(long = "fee-payer")]
        fee_payer: Option<String>,

        #[arg(long, conflicts_with = "publisher")]
        authority: Option<String>,

        #[arg(long, conflicts_with = "authority")]
        publisher: Option<String>,

        seed: String,
        abi_file: String,
    },

    /// Finalize an ABI account so it becomes immutable
    Finalize {
        #[arg(long)]
        ephemeral: bool,

        #[arg(long = "account-type", value_enum, default_value = "program")]
        account_type: AbiAccountType,

        #[arg(long = "target-program")]
        target_program: Option<String>,

        #[arg(long = "fee-payer")]
        fee_payer: Option<String>,

        #[arg(long, conflicts_with = "publisher")]
        authority: Option<String>,

        #[arg(long, conflicts_with = "authority")]
        publisher: Option<String>,

        seed: String,
    },

    /// Close an ABI account and reclaim its balance
    Close {
        #[arg(long)]
        ephemeral: bool,

        #[arg(long = "account-type", value_enum, default_value = "program")]
        account_type: AbiAccountType,

        #[arg(long = "target-program")]
        target_program: Option<String>,

        #[arg(long = "fee-payer")]
        fee_payer: Option<String>,

        #[arg(long, conflicts_with = "publisher")]
        authority: Option<String>,

        #[arg(long, conflicts_with = "authority")]
        publisher: Option<String>,

        seed: String,
    },

    /// Inspect an ABI account's metadata and optionally dump its YAML contents
    Get {
        /// ABI account public key (Thru address)
        abi_account: String,

        /// Include ABI YAML contents in the CLI output
        #[arg(long = "include-data", alias = "data")]
        include_data: bool,

        /// Optional file path to write the ABI YAML contents
        #[arg(long = "out")]
        out: Option<String>,
    },
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug)]
pub enum AbiLanguage {
    C,
    Rust,
    #[value(name = "typescript")]
    TypeScript,
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug)]
pub enum AbiIrFormat {
    Json,
    Protobuf,
}

/// Uploader-related subcommands
#[derive(Subcommand)]
pub enum UploaderCommands {
    /// Upload a program to the blockchain
    Upload {
        /// Custom uploader program public key (optional)
        #[arg(long)]
        uploader: Option<String>,

        /// Chunk size for upload transactions (1024-31000 bytes)
        #[arg(long, value_parser = parse_chunk_size, default_value = "30720")]
        chunk_size: usize,

        /// Seed for account derivation
        seed: String,

        /// Path to the program binary file
        program_file: String,
    },

    /// Clean up program accounts
    Cleanup {
        /// Custom uploader program public key (optional)
        #[arg(long)]
        uploader: Option<String>,

        /// Seed for account derivation
        seed: String,
    },

    /// Check status of uploader accounts
    Status {
        /// Custom uploader program public key (optional)
        #[arg(long)]
        uploader: Option<String>,

        /// Seed for account derivation
        seed: String,
    },
}

/// Key management subcommands
#[derive(Subcommand)]
pub enum KeysCommands {
    /// List all key names
    List,

    /// Add a new key
    Add {
        /// Overwrite existing key
        #[arg(long)]
        overwrite: bool,

        /// Key name (case-insensitive)
        name: String,

        /// Private key (64 hex characters)
        key: String,
    },

    /// Get a key value
    Get {
        /// Key name to retrieve
        name: String,
    },

    /// Generate a new random key
    Generate {
        /// Overwrite existing key
        #[arg(long)]
        overwrite: bool,

        /// Key name for the new key
        name: String,
    },

    /// Remove a key
    #[command(name = "rm")]
    Remove {
        /// Key name to remove
        name: String,
    },
}

/// Network profile management subcommands
#[derive(Subcommand)]
pub enum NetworkCommands {
    /// Add a new named network profile
    Add {
        /// Network profile name (case-insensitive)
        name: String,

        /// RPC endpoint URL
        #[arg(long)]
        url: String,

        /// Optional authorization token
        #[arg(long = "auth-token")]
        auth_token: Option<String>,
    },

    /// Set the default network profile
    #[command(name = "set-default")]
    SetDefault {
        /// Network profile name to use as default
        name: String,
    },

    /// Update fields on an existing network profile
    Set {
        /// Network profile name to update
        name: String,

        /// New RPC endpoint URL
        #[arg(long)]
        url: Option<String>,

        /// New authorization token (use empty string to clear)
        #[arg(long = "auth-token")]
        auth_token: Option<String>,
    },

    /// List all configured network profiles
    List,

    /// Remove a network profile
    #[command(name = "rm")]
    Remove {
        /// Network profile name to remove
        name: String,
    },
}

/// Transaction management subcommands
#[derive(Subcommand)]
pub enum TxnCommands {
    /// Create and sign a transaction, output as base64 string
    Sign {
        /// Program public key (ta... format or key name from config)
        program: String,

        /// Instruction data as hex string
        instruction_data: String,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Transaction fee (optional, defaults to 1)
        #[arg(long, default_value = "1")]
        fee: u64,

        /// Compute units (optional, defaults to 1000000000)
        #[arg(long, default_value = "1000000000")]
        compute_units: u32,

        /// State units (optional, defaults to 10000)
        #[arg(long, default_value = "10000")]
        state_units: u16,

        /// Memory units (optional, defaults to 10000)
        #[arg(long, default_value = "10000")]
        memory_units: u16,

        /// Expiry after (optional, defaults to 100)
        #[arg(long, default_value = "100")]
        expiry_after: u32,

        /// Read-write account addresses in ascending order (optional)
        #[arg(long)]
        readwrite_accounts: Vec<String>,

        /// Read-only account addresses in ascending order (optional)
        #[arg(long)]
        readonly_accounts: Vec<String>,
    },

    /// Create, sign and execute a transaction, print response
    Execute {
        /// Program public key (ta... format or key name from config)
        program: String,

        /// Instruction data as hex string
        instruction_data: String,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Transaction fee (optional, defaults to 1)
        #[arg(long, default_value = "1")]
        fee: u64,

        /// Compute units (optional, defaults to 1000000000)
        #[arg(long, default_value = "300000000")]
        compute_units: u32,

        /// State units (optional, defaults to 10000)
        #[arg(long, default_value = "10000")]
        state_units: u16,

        /// Memory units (optional, defaults to 10000)
        #[arg(long, default_value = "10000")]
        memory_units: u16,

        /// Expiry after (optional, defaults to 100)
        #[arg(long, default_value = "100")]
        expiry_after: u32,

        /// Transaction timeout in seconds (optional, defaults to 30)
        #[arg(long, default_value = "30")]
        timeout: u64,

        /// Read-write account addresses in ascending order (optional)
        #[arg(long)]
        readwrite_accounts: Vec<String>,

        /// Read-only account addresses in ascending order (optional)
        #[arg(long)]
        readonly_accounts: Vec<String>,
    },

    /// Create a cryptographic state proof for a given account
    #[command(name = "make-state-proof")]
    MakeStateProof {
        /// Type of proof to create (creating, updating, existing)
        proof_type: String,

        /// Account public key for which to create the state proof
        account: String,

        /// Slot to create the proof for (optional)
        #[arg(long)]
        slot: Option<u64>,
    },

    /// Get transaction details by signature
    Get {
        /// Transaction signature (ts... format or 128 hex characters)
        signature: String,

        /// Number of retry attempts (1-60, default: 1)
        #[arg(long = "retry-count", value_name = "COUNT", default_value = "1", value_parser = clap::value_parser!(u32).range(1..=60))]
        retry_count: u32,
    },

    /// Sort public keys for inclusion in transaction account lists
    Sort {
        /// Public keys to sort (hex or ta... format)
        pubkeys: Vec<String>,
    },
}

/// Account management subcommands
#[derive(Subcommand)]
pub enum AccountCommands {
    /// Create a new account with fee payer proof
    Create {
        /// Key name from configuration (optional, defaults to 'default')
        key_name: Option<String>,
    },

    /// Get account information (alias to getaccountinfo)
    Info {
        /// Key name from configuration (optional, defaults to 'default')
        key_name: Option<String>,
    },

    /// List transactions involving an account
    #[command(name = "transactions")]
    Transactions {
        /// Account identifier (key name from config or public key, defaults to 'default')
        account: Option<String>,

        /// Maximum number of transactions to return (defaults to server setting)
        #[arg(long = "page-size")]
        page_size: Option<u32>,

        /// Page token to continue from a previous request
        #[arg(long = "page-token")]
        page_token: Option<String>,
    },

    /// Compress an account
    Compress {
        /// Target account to compress (key name from config or ta... address)
        target_account: String,
        /// Fee payer account (key name from config or ta... address, optional - defaults to 'default')
        fee_payer: Option<String>,
    },

    /// Decompress an account
    Decompress {
        /// Target account to decompress (key name from config or ta... address)
        target_account: String,
        /// Fee payer account (key name from config or ta... address, optional - defaults to 'default')
        fee_payer: Option<String>,
    },

    /// Prepare account decompression - get account data and proof
    PrepareDecompression {
        /// Account address or key name from configuration
        account: String,
    },
}

/// Utility subcommands
#[derive(Subcommand)]
pub enum UtilCommands {
    /// Format conversion commands
    #[command(name = "convert")]
    Convert {
        #[command(subcommand)]
        subcommand: ConvertCommands,
    },
}

/// Format conversion subcommands
#[derive(Subcommand)]
pub enum ConvertCommands {
    /// Public key conversion commands
    #[command(name = "pubkey")]
    Pubkey {
        #[command(subcommand)]
        subcommand: PubkeyConvertCommands,
    },

    /// Signature conversion commands
    #[command(name = "signature")]
    Signature {
        #[command(subcommand)]
        subcommand: SignatureConvertCommands,
    },
}

/// Public key conversion subcommands
#[derive(Subcommand)]
pub enum PubkeyConvertCommands {
    /// Convert hex public key to thru format (ta...)
    #[command(name = "hex-to-thrufmt")]
    HexToThruFmt {
        /// Hex-encoded public key (64 hex characters)
        hex_pubkey: String,
    },

    /// Convert thru format public key (ta...) to hex
    #[command(name = "thrufmt-to-hex")]
    ThruFmtToHex {
        /// Thru format public key (46 characters starting with ta)
        thrufmt_pubkey: String,
    },
}

/// Signature conversion subcommands
#[derive(Subcommand)]
pub enum SignatureConvertCommands {
    /// Convert hex signature to thru format (ts...)
    #[command(name = "hex-to-thrufmt")]
    HexToThruFmt {
        /// Hex-encoded signature (128 hex characters)
        hex_signature: String,
    },

    /// Convert thru format signature (ts...) to hex
    #[command(name = "thrufmt-to-hex")]
    ThruFmtToHex {
        /// Thru format signature (90 characters starting with ts)
        thrufmt_signature: String,
    },
}

/// Token program subcommands
#[derive(Subcommand)]
pub enum TokenCommands {
    /// Initialize a new token mint
    InitializeMint {
        /// Creator address (must be authorized to create)
        creator: String,

        /// Mint authority address (optional, defaults to creator)
        #[arg(long)]
        mint_authority: Option<String>,

        /// Freeze authority address (optional)
        #[arg(long)]
        freeze_authority: Option<String>,

        /// Number of decimal places
        #[arg(long, default_value = "9")]
        decimals: u8,

        /// Token ticker symbol (max 8 characters)
        ticker: String,

        /// Seed for mint account derivation (32 bytes hex)
        seed: String,

        /// State proof for mint account creation (hex encoded, optional - will auto-generate if not provided)
        #[arg(long)]
        state_proof: Option<String>,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Initialize a new token account
    InitializeAccount {
        /// Mint account address
        mint: String,

        /// Account owner address
        owner: String,

        /// Seed for token account derivation (32 bytes hex)
        seed: String,

        /// State proof for token account creation (hex encoded, optional - will auto-generate if not provided)
        #[arg(long)]
        state_proof: Option<String>,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Transfer tokens between accounts
    Transfer {
        /// Source token account address
        from: String,

        /// Destination token account address
        to: String,

        /// Amount to transfer
        amount: u64,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Mint new tokens to an account
    MintTo {
        /// Mint account address
        mint: String,

        /// Destination token account address
        to: String,

        /// Mint authority address
        authority: String,

        /// Amount to mint
        amount: u64,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Burn tokens from an account
    Burn {
        /// Token account address
        account: String,

        /// Mint account address
        mint: String,

        /// Account authority address
        authority: String,

        /// Amount to burn
        amount: u64,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Close a token account
    CloseAccount {
        /// Token account address
        account: String,

        /// Destination for remaining balance
        destination: String,

        /// Account authority address
        authority: String,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Freeze a token account
    FreezeAccount {
        /// Token account address
        account: String,

        /// Mint account address
        mint: String,

        /// Freeze authority address
        authority: String,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Unfreeze a token account
    ThawAccount {
        /// Token account address
        account: String,

        /// Mint account address
        mint: String,

        /// Freeze authority address
        authority: String,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Derive token account address from mint, owner, and seed
    DeriveTokenAccount {
        /// Mint account address
        mint: String,

        /// Account owner address
        owner: String,

        /// Seed for derivation (32 bytes hex, optional - defaults to all zeros)
        #[arg(long)]
        seed: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Derive mint account address from creator and seed
    DeriveMintAccount {
        /// Creator address
        creator: String,

        /// Seed for derivation (32 bytes hex)
        seed: String,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },
}

/// Faucet program subcommands
#[derive(Subcommand)]
pub enum FaucetCommands {
    /// Deposit tokens into the faucet
    Deposit {
        /// Account identifier (key name or ta.../hex pubkey) to use as depositor (must match fee payer)
        account: String,

        /// Amount to deposit
        amount: u64,

        /// Fee payer account name (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,
    },

    /// Withdraw tokens from the faucet
    Withdraw {
        /// Account identifier (key name or ta.../hex pubkey) to use as recipient
        account: String,

        /// Amount to withdraw (max 10000 per transaction)
        amount: u64,

        /// Fee payer account name (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,
    },
}

/// Thru registrar program subcommands
#[derive(Subcommand)]
pub enum RegistrarCommands {
    /// Initialize the .thru registry
    InitializeRegistry {
        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,

        /// Root registrar account address
        root_registrar_account: String,

        /// Treasurer token account address
        treasurer_account: String,

        /// Token mint address (the mint itself, not a holder account)
        token_mint_account: String,

        /// Token program address
        #[arg(long = "token-program")]
        token_program: Option<String>,

        /// Price per year in base units
        price_per_year: u64,

        /// Root domain name (e.g., "thru")
        #[arg(default_value = "thru")]
        root_domain_name: String,

        /// State proof for config account creation (hex encoded, optional - will auto-generate if not provided)
        #[arg(long)]
        config_proof: Option<String>,

        /// State proof for registrar account creation (hex encoded, optional - will auto-generate if not provided)
        #[arg(long)]
        registrar_proof: Option<String>,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override thru registrar program address (ta... or hex)
        #[arg(long = "thru-registrar-program", alias = "thru-name-service-program")]
        thru_registrar_program: Option<String>,
    },

    /// Purchase a .thru domain
    PurchaseDomain {
        /// Domain name without .thru suffix (e.g., "example")
        domain_name: String,

        /// Number of years to purchase (must be > 0)
        years: u8,

        /// Config account address (must exist and be initialized)
        config_account: String,

        /// Payer token account (must be an account for the registry mint owned by fee payer)
        payer_token_account: String,

        /// State proof for lease account creation (hex encoded, optional - will auto-generate if not provided)
        #[arg(long)]
        lease_proof: Option<String>,

        /// State proof for domain account creation (hex encoded, optional - will auto-generate if not provided)
        #[arg(long)]
        domain_proof: Option<String>,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override thru registrar program address (ta... or hex)
        #[arg(long = "thru-registrar-program", alias = "thru-name-service-program")]
        thru_registrar_program: Option<String>,
    },

    /// Renew an existing domain lease
    RenewLease {
        /// Lease account address
        lease_account: String,

        /// Number of years to extend the lease (must be > 0)
        years: u8,

        /// Config account address (must exist and be initialized)
        config_account: String,

        /// Payer token account (must be an account for the registry mint owned by fee payer)
        payer_token_account: String,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override thru registrar program address (ta... or hex)
        #[arg(long = "thru-registrar-program", alias = "thru-name-service-program")]
        thru_registrar_program: Option<String>,
    },

    /// Claim an expired domain
    ClaimExpiredDomain {
        /// Lease account address
        lease_account: String,

        /// Number of years to claim the domain (must be > 0)
        years: u8,

        /// Config account address (must exist and be initialized)
        config_account: String,

        /// Payer token account (must be an account for the registry mint owned by fee payer)
        payer_token_account: String,

        /// Fee payer account (optional, defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override thru registrar program address (ta... or hex)
        #[arg(long = "thru-registrar-program", alias = "thru-name-service-program")]
        thru_registrar_program: Option<String>,
    },
}

/// Name service program subcommands
#[derive(Subcommand)]
pub enum NameServiceCommands {
    /// Append a key/value record to a domain
    #[command(name = "append-record")]
    AppendRecord {
        /// Domain account address
        domain_account: String,

        /// Record key (<=32 bytes)
        key: String,

        /// Record value (<=256 bytes)
        value: String,

        /// Owner account pubkey (defaults to fee payer)
        #[arg(long)]
        owner: Option<String>,

        /// Fee payer account (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,
    },

    /// Delete a key/value record from a domain
    #[command(name = "delete-record")]
    DeleteRecord {
        /// Domain account address
        domain_account: String,

        /// Record key to delete
        key: String,

        /// Owner account pubkey (defaults to fee payer)
        #[arg(long)]
        owner: Option<String>,

        /// Fee payer account (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,
    },

    /// Derive config account address
    DeriveConfigAccount {
        /// Override thru registrar program address (ta... or hex)
        #[arg(long = "thru-registrar-program", alias = "thru-name-service-program")]
        thru_registrar_program: Option<String>,
    },

    /// Derive a domain account address from parent and name
    #[command(name = "derive-domain-account")]
    DeriveDomainAccount {
        /// Parent registrar or domain account address
        parent_account: String,

        /// Domain name segment (e.g., "example")
        domain_name: String,

        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,
    },

    /// Derive lease account address from domain name
    DeriveLeaseAccount {
        /// Domain name without .thru suffix (e.g., "example")
        domain_name: String,

        /// Override thru registrar program address (ta... or hex)
        #[arg(long = "thru-registrar-program", alias = "thru-name-service-program")]
        thru_registrar_program: Option<String>,
    },

    /// Derive a root registrar account address from the root name
    #[command(name = "derive-registrar-account")]
    DeriveRegistrarAccount {
        /// Root domain name segment
        root_name: String,

        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,
    },

    /// Initialize a root registrar for the base name service program
    #[command(name = "init-root")]
    InitRoot {
        /// Root domain name (e.g., "thru")
        root_name: String,

        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,

        /// Registrar account address (derived automatically if omitted)
        #[arg(long)]
        registrar_account: Option<String>,

        /// Authority account pubkey (defaults to fee payer)
        #[arg(long)]
        authority: Option<String>,

        /// State proof for registrar account creation (hex encoded, optional - auto-generated if not provided)
        #[arg(long)]
        proof: Option<String>,

        /// Fee payer account (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,
    },

    /// List records stored on a domain
    #[command(name = "list-records")]
    ListRecords {
        /// Domain account address
        domain_account: String,

        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,
    },

    /// Register a subdomain under a parent registrar or domain
    #[command(name = "register-subdomain")]
    RegisterSubdomain {
        /// Subdomain name segment (e.g., "example")
        domain_name: String,

        /// Parent registrar or domain account address
        parent_account: String,

        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,

        /// Domain account address (derived automatically if omitted)
        #[arg(long)]
        domain_account: Option<String>,

        /// Owner account pubkey (defaults to fee payer)
        #[arg(long)]
        owner: Option<String>,

        /// Authority account pubkey (defaults to owner)
        #[arg(long)]
        authority: Option<String>,

        /// State proof for domain account creation (hex encoded, optional - auto-generated if not provided)
        #[arg(long)]
        proof: Option<String>,

        /// Fee payer account (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,
    },

    /// Resolve a domain account and optionally retrieve a record value
    #[command(name = "resolve")]
    Resolve {
        /// Domain account address
        domain_account: String,

        /// Optional record key to fetch
        #[arg(long)]
        key: Option<String>,

        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,
    },

    /// Unregister (delete) a subdomain
    #[command(name = "unregister-subdomain")]
    UnregisterSubdomain {
        /// Domain account address
        domain_account: String,

        /// Owner account pubkey (defaults to fee payer)
        #[arg(long)]
        owner: Option<String>,

        /// Fee payer account (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Name service program address
        #[arg(long = "name-service-program")]
        name_service_program: Option<String>,
    },
}

/// WTHRU program subcommands
#[derive(Subcommand)]
pub enum WthruCommands {
    /// Initialize the WTHRU mint and vault accounts
    Initialize {
        /// Fee payer account name (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override WTHRU program address (ta... or hex)
        #[arg(long = "program")]
        program: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },

    /// Deposit native THRU and receive WTHRU tokens
    Deposit {
        /// Destination WTHRU token account address
        dest_token_account: String,

        /// Amount of native THRU to wrap (lamports)
        amount: u64,

        /// Fee payer account name (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override WTHRU program address (ta... or hex)
        #[arg(long = "program")]
        program: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,

        /// Skip the native transfer (only run the deposit instruction)
        #[arg(long = "skip-transfer")]
        skip_transfer: bool,
    },

    /// Withdraw native THRU by burning WTHRU tokens
    Withdraw {
        /// Source WTHRU token account address
        wthru_token_account: String,

        /// Recipient native account address (ta...)
        recipient: String,

        /// Amount of WTHRU to unwrap (lamports)
        amount: u64,

        /// Fee payer/owner account name (defaults to 'default')
        #[arg(long)]
        fee_payer: Option<String>,

        /// Override WTHRU program address (ta... or hex)
        #[arg(long = "program")]
        program: Option<String>,

        /// Override token program address (ta... or hex)
        #[arg(long = "token-program")]
        token_program: Option<String>,
    },
}

/// Developer tools subcommands
#[derive(Subcommand)]
pub enum DevCommands {
    /// Toolchain management commands
    #[command(name = "toolchain")]
    Toolchain {
        #[command(subcommand)]
        subcommand: ToolchainCommands,
    },

    /// SDK management commands
    #[command(name = "sdk")]
    Sdk {
        #[command(subcommand)]
        subcommand: SdkCommands,
    },

    /// Initialize new projects
    #[command(name = "init")]
    Init {
        #[command(subcommand)]
        subcommand: InitCommands,
    },
}

/// Toolchain management subcommands
#[derive(Subcommand)]
pub enum ToolchainCommands {
    /// Install toolchain from GitHub releases
    Install {
        /// Toolchain version (optional, defaults to latest)
        #[arg(long)]
        version: Option<String>,

        /// Installation path (optional, defaults to ~/.thru/sdk/toolchain/)
        #[arg(long)]
        path: Option<String>,

        /// GitHub repository (format: owner/repo, defaults to Unto-Labs/thru)
        #[arg(long)]
        repo: Option<String>,
    },

    /// Update toolchain to latest version
    Update {
        /// Installation path (optional, defaults to ~/.thru/sdk/toolchain/)
        #[arg(long)]
        path: Option<String>,

        /// GitHub repository (format: owner/repo, defaults to Unto-Labs/thru)
        #[arg(long)]
        repo: Option<String>,
    },

    /// Uninstall toolchain
    Uninstall {
        /// Installation path (optional, defaults to ~/.thru/sdk/toolchain/)
        #[arg(long)]
        path: Option<String>,

        /// Skip confirmation prompt
        #[arg(long)]
        force: bool,
    },

    /// Get toolchain installation path
    Path {
        /// Installation path (optional, defaults to ~/.thru/sdk/toolchain/)
        #[arg(long)]
        path: Option<String>,
    },
}

/// SDK management subcommands
#[derive(Subcommand)]
pub enum SdkCommands {
    /// Install SDK from GitHub releases
    Install {
        /// SDK language (c, cpp, rust)
        language: String,

        /// SDK version (optional, defaults to latest)
        #[arg(long)]
        version: Option<String>,

        /// Installation path (optional, defaults to ~/.thru/sdk/{language}/)
        #[arg(long)]
        path: Option<String>,

        /// GitHub repository (format: owner/repo, defaults to Unto-Labs/thru)
        #[arg(long)]
        repo: Option<String>,
    },

    /// Update SDK to latest version
    Update {
        /// SDK language (c, cpp, rust)
        language: String,

        /// Installation path (optional, defaults to ~/.thru/sdk/{language}/)
        #[arg(long)]
        path: Option<String>,

        /// GitHub repository (format: owner/repo, defaults to Unto-Labs/thru)
        #[arg(long)]
        repo: Option<String>,
    },

    /// Uninstall SDK
    Uninstall {
        /// SDK language (c, cpp, rust)
        language: String,

        /// Installation path (optional, defaults to ~/.thru/sdk/{language}/)
        #[arg(long)]
        path: Option<String>,

        /// Skip confirmation prompt
        #[arg(long)]
        force: bool,
    },

    /// Get SDK installation path
    Path {
        /// SDK language (c, cpp, rust)
        language: String,

        /// Installation path (optional, defaults to ~/.thru/sdk/{language}/)
        #[arg(long)]
        path: Option<String>,
    },
}

/// Project initialization subcommands
#[derive(Subcommand)]
pub enum InitCommands {
    /// Initialize a new C project
    #[command(name = "c")]
    C {
        /// Project name
        project_name: String,

        /// Project directory (optional, defaults to current directory)
        #[arg(long)]
        path: Option<String>,
    },

    /// Initialize a new C++ project (not yet implemented)
    #[command(name = "cpp")]
    Cpp {
        /// Project name
        project_name: String,

        /// Project directory (optional, defaults to current directory)
        #[arg(long)]
        path: Option<String>,
    },

    /// Initialize a new Rust project (not yet implemented)
    #[command(name = "rust")]
    Rust {
        /// Project name
        project_name: String,

        /// Project directory (optional, defaults to current directory)
        #[arg(long)]
        path: Option<String>,
    },
}

/// Debug subcommands
#[derive(Subcommand)]
pub enum DebugCommands {
    /// Re-execute a transaction in a simulated environment
    #[command(name = "re-execute")]
    ReExecute {
        /// Transaction signature (ts... format or 128 hex characters)
        signature: String,

        /// Include account state snapshots before execution
        #[arg(long)]
        include_state_before: bool,

        /// Include account state snapshots after execution
        #[arg(long)]
        include_state_after: bool,

        /// Include full account data in state snapshots
        #[arg(long)]
        include_account_data: bool,

        /// Save VM execution trace to file
        #[arg(long, value_name = "FILE")]
        output_trace: Option<String>,

        /// Include full memory dump (stack + heap pages)
        #[arg(long)]
        include_memory_dump: bool,
    },

    /// Resolve DWARF debug info for a DebugReExecute response
    ///
    /// Takes a program .elf (built with -g) and either a response JSON file or a
    /// transaction signature (calls DebugReExecute via gRPC). Produces a source-level
    /// error report with file:line mappings, call stack, variables, and annotated trace.
    #[command(name = "resolve")]
    Resolve {
        /// Path to the program .elf file with DWARF debug info
        #[arg(long)]
        elf: std::path::PathBuf,

        /// Path to the DebugReExecuteResponse JSON file (mutually exclusive with --signature)
        #[arg(long, group = "input")]
        response: Option<std::path::PathBuf>,

        /// Transaction signature to re-execute via gRPC (mutually exclusive with --response)
        #[arg(long, group = "input")]
        signature: Option<String>,

        /// Number of trace lines to include before the fault
        #[arg(long, default_value = "20")]
        trace_tail: usize,

        /// Source context lines above/below the fault line
        #[arg(long, default_value = "5")]
        context: u32,
    },
}

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

    #[test]
    fn parses_abi_codegen_command() {
        let cli = Cli::try_parse_from([
            "thru",
            "abi",
            "codegen",
            "-f",
            "input.abi.yaml",
            "-l",
            "rust",
        ])
        .expect("codegen command should parse");

        match cli.command {
            Commands::Abi {
                subcommand:
                    AbiCommands::Codegen {
                        files,
                        include_dirs,
                        language,
                        output_dir,
                        verbose,
                    },
            } => {
                assert_eq!(files, vec![PathBuf::from("input.abi.yaml")]);
                assert!(include_dirs.is_empty());
                assert_eq!(language, AbiLanguage::Rust);
                assert_eq!(output_dir, PathBuf::from("generated"));
                assert!(!verbose);
            }
            _ => panic!("unexpected command"),
        }
    }

    #[test]
    fn parses_abi_account_create_command() {
        let cli = Cli::try_parse_from([
            "thru",
            "abi",
            "account",
            "create",
            "seed-1",
            "program.abi.yaml",
        ])
        .expect("abi account create should parse");

        match cli.command {
            Commands::Abi {
                subcommand:
                    AbiCommands::Account {
                        subcommand:
                            AbiAccountCommands::Create {
                                ephemeral,
                                account_type,
                                target_program,
                                seed,
                                fee_payer,
                                authority,
                                publisher,
                                abi_file,
                            },
                    },
            } => {
                assert!(!ephemeral);
                assert_eq!(account_type, AbiAccountType::Program);
                assert_eq!(target_program, None);
                assert_eq!(seed, "seed-1");
                assert_eq!(fee_payer, None);
                assert_eq!(authority, None);
                assert_eq!(publisher, None);
                assert_eq!(abi_file, "program.abi.yaml");
            }
            _ => panic!("unexpected command"),
        }
    }

    #[test]
    fn parses_abi_account_get_include_data_flag() {
        let cli = Cli::try_parse_from(["thru", "abi", "account", "get", "ta123", "--include-data"])
            .expect("abi account get should parse");

        match cli.command {
            Commands::Abi {
                subcommand:
                    AbiCommands::Account {
                        subcommand:
                            AbiAccountCommands::Get {
                                abi_account,
                                include_data,
                                out,
                            },
                    },
            } => {
                assert_eq!(abi_account, "ta123");
                assert!(include_data);
                assert_eq!(out, None);
            }
            _ => panic!("unexpected command"),
        }
    }

    #[test]
    fn parses_abi_account_upgrade_third_party_command() {
        let cli = Cli::try_parse_from([
            "thru",
            "abi",
            "account",
            "upgrade",
            "--account-type",
            "third-party",
            "--target-program",
            "ta_target",
            "--publisher",
            "alice",
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            "program.abi.yaml",
        ])
        .expect("third-party abi account upgrade should parse");

        match cli.command {
            Commands::Abi {
                subcommand:
                    AbiCommands::Account {
                        subcommand:
                            AbiAccountCommands::Upgrade {
                                account_type,
                                publisher,
                                authority,
                                target_program,
                                seed,
                                abi_file,
                                ..
                            },
                    },
            } => {
                assert_eq!(account_type, AbiAccountType::ThirdParty);
                assert_eq!(publisher.as_deref(), Some("alice"));
                assert_eq!(authority, None);
                assert_eq!(target_program.as_deref(), Some("ta_target"));
                assert_eq!(
                    seed,
                    "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
                );
                assert_eq!(abi_file, "program.abi.yaml");
            }
            _ => panic!("unexpected command"),
        }
    }

    #[test]
    fn parses_abi_account_finalize_standalone_authority_alias() {
        let cli = Cli::try_parse_from([
            "thru",
            "abi",
            "account",
            "finalize",
            "--account-type",
            "standalone",
            "--authority",
            "alice",
            "my-abi-seed",
        ])
        .expect("standalone abi account finalize should parse authority alias");

        match cli.command {
            Commands::Abi {
                subcommand:
                    AbiCommands::Account {
                        subcommand:
                            AbiAccountCommands::Finalize {
                                account_type,
                                target_program,
                                authority,
                                publisher,
                                seed,
                                ..
                            },
                    },
            } => {
                assert_eq!(account_type, AbiAccountType::Standalone);
                assert_eq!(target_program, None);
                assert_eq!(authority.as_deref(), Some("alice"));
                assert_eq!(publisher, None);
                assert_eq!(seed, "my-abi-seed");
            }
            _ => panic!("unexpected command"),
        }
    }

    #[test]
    fn parses_abi_account_close_command() {
        let cli = Cli::try_parse_from([
            "thru",
            "abi",
            "account",
            "close",
            "--fee-payer",
            "bob",
            "--authority",
            "alice",
            "seed-1",
        ])
        .expect("abi account close should parse");

        match cli.command {
            Commands::Abi {
                subcommand:
                    AbiCommands::Account {
                        subcommand:
                            AbiAccountCommands::Close {
                                account_type,
                                target_program,
                                fee_payer,
                                authority,
                                publisher,
                                seed,
                                ..
                            },
                    },
            } => {
                assert_eq!(account_type, AbiAccountType::Program);
                assert_eq!(target_program, None);
                assert_eq!(fee_payer.as_deref(), Some("bob"));
                assert_eq!(authority.as_deref(), Some("alice"));
                assert_eq!(publisher, None);
                assert_eq!(seed, "seed-1");
            }
            _ => panic!("unexpected command"),
        }
    }

    #[test]
    fn rejects_conflicting_abi_account_actor_flags() {
        let result = Cli::try_parse_from([
            "thru",
            "abi",
            "account",
            "create",
            "--account-type",
            "standalone",
            "--authority",
            "alice",
            "--publisher",
            "bob",
            "my-abi-seed",
            "program.abi.yaml",
        ]);

        assert!(
            result.is_err(),
            "conflicting abi account actor flags should fail"
        );
    }

    #[test]
    fn rejects_conflicting_abi_reflect_flags() {
        let result = Cli::try_parse_from([
            "thru",
            "abi",
            "reflect",
            "-f",
            "input.abi.yaml",
            "-t",
            "MyType",
            "-d",
            "data.bin",
            "--validate-only",
            "--values-only",
        ]);

        assert!(result.is_err(), "conflicting reflect flags should fail");
    }

    #[test]
    fn abi_reflect_short_v_is_no_longer_values_only() {
        let result = Cli::try_parse_from([
            "thru",
            "abi",
            "reflect",
            "-f",
            "input.abi.yaml",
            "-t",
            "MyType",
            "-d",
            "data.bin",
            "-v",
        ]);

        assert!(
            result.is_err(),
            "short -v should no longer parse for abi reflect"
        );
    }

    #[test]
    fn parses_abi_prep_for_publish_command() {
        let cli = Cli::try_parse_from([
            "thru",
            "abi",
            "prep-for-publish",
            "-f",
            "root.abi.yaml",
            "--target-network",
            "mainnet",
            "-o",
            "publish.abi.yaml",
        ])
        .expect("prep-for-publish command should parse");

        match cli.command {
            Commands::Abi {
                subcommand:
                    AbiCommands::PrepForPublish {
                        file,
                        include_dirs,
                        target_network,
                        output,
                        verbose,
                    },
            } => {
                assert_eq!(file, PathBuf::from("root.abi.yaml"));
                assert!(include_dirs.is_empty());
                assert_eq!(target_network, "mainnet");
                assert_eq!(output, PathBuf::from("publish.abi.yaml"));
                assert!(!verbose);
            }
            _ => panic!("unexpected command"),
        }
    }
}