calcit 0.12.30

Interpreter and js codegen for Calcit
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
use argh::FromArgs;

pub const CALCIT_VERSION: &str = env!("CARGO_PKG_VERSION");

#[derive(FromArgs, PartialEq, Debug, Clone)]
/// Top-level command.
pub struct ToplevelCalcit {
  #[argh(subcommand)]
  pub subcommand: Option<CalcitCommand>,
  /// enable watch mode for direct run mode (default behavior is run once)
  #[argh(switch, short = 'w')]
  pub watch: bool,
  /// check-only mode: validate without execution or codegen
  #[argh(switch)]
  pub check_only: bool,
  /// disable stack trace for errors
  #[argh(switch)]
  pub disable_stack: bool,
  /// skip arity check in js codegen
  #[argh(switch)]
  pub skip_arity_check: bool,
  /// warn on dynamic method calls that cannot be monomorphized
  #[argh(switch)]
  pub warn_dyn_method: bool,
  /// print FFI dylib calls and callbacks for debugging native crashes
  #[argh(switch)]
  pub trace_ffi: bool,
  /// entry file path, defaults to "js-out/"
  #[argh(option, default = "String::from(\"js-out/\")")]
  pub emit_path: String,
  /// specify `init_fn` which is main function
  #[argh(option)]
  pub init_fn: Option<String>,
  /// specify `reload_fn` which is called after hot reload
  #[argh(option)]
  pub reload_fn: Option<String>,
  /// specify with config entry
  #[argh(option)]
  pub entry: Option<String>,
  #[argh(switch)]
  /// force reloading libs data during code reload
  pub reload_libs: bool,
  #[argh(option)]
  /// specify a path to watch assets changes
  pub watch_dir: Option<String>,
  /// input source file, defaults to "compact.cirru"
  #[argh(positional, default = "String::from(\"compact.cirru\")")]
  pub input: String,
  /// print version only
  #[argh(switch)]
  pub version: bool,
  /// show full tips output in all commands
  #[argh(switch)]
  pub tips: bool,
  /// control tips verbosity: minimal (default), full, none
  #[argh(option)]
  pub tips_level: Option<String>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum CalcitCommand {
  /// emit JavaScript rather than interpreting
  EmitJs(EmitJsCommand),
  /// emit Cirru EDN representation of program to program-ir.cirru
  EmitIr(EmitIrCommand),
  /// evaluate snippet
  Eval(EvalCommand),
  /// analyze code structure and helpers (call-graph, count-calls, check-examples)
  Analyze(AnalyzeCommand),
  /// query project information (namespaces, definitions, configs)
  Query(QueryCommand),
  /// documentation tools (API docs, guidebook)
  Docs(DocsCommand),
  /// Cirru syntax tools (parse, format)
  Cirru(CirruCommand),
  /// fetch available Calcit libraries from registry
  Libs(LibsCommand),
  /// edit project code (definitions, namespaces, modules, configs)
  Edit(EditCommand),
  /// fine-grained tree operations (view and modify AST nodes)
  Tree(TreeCommand),
}

/// emit JavaScript rather than interpreting
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "js")]
pub struct EmitJsCommand {
  /// enable watch mode (default behavior is run once)
  #[argh(switch, short = 'w')]
  pub watch: bool,
  /// check-only mode for JS emit
  #[argh(switch)]
  pub check_only: bool,
}

/// emit Cirru EDN representation of program to program-ir.cirru
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "ir")]
pub struct EmitIrCommand {
  /// enable watch mode (default behavior is run once)
  #[argh(switch, short = 'w')]
  pub watch: bool,
}

/// run program
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "eval")]
pub struct EvalCommand {
  /// evaluate a snippet
  #[argh(positional)]
  pub snippet: String,
  /// entry file path
  #[argh(option)]
  pub dep: Vec<String>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Analyze subcommand - code structure analysis
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "analyze")]
/// analyze code structure and helpers (call-graph, count-calls, check-examples, check-types, js-escape)
pub struct AnalyzeCommand {
  #[argh(subcommand)]
  pub subcommand: AnalyzeSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum AnalyzeSubcommand {
  /// analyze call graph structure from entry point
  CallGraph(CallGraphCommand),
  /// count call occurrences from entry point
  CountCalls(CountCallsCommand),
  /// check examples in namespace
  CheckExamples(CheckExamplesCommand),
  /// check type-information coverage in namespace definitions
  CheckTypes(CheckTypesCommand),
  /// escape a Calcit symbol into JavaScript-safe identifier form
  JsEscape(JsEscapeCommand),
  /// decode escaped JavaScript identifier back to Calcit symbol (best-effort)
  JsUnescape(JsUnescapeCommand),
}

/// escape a Calcit symbol into JavaScript-safe identifier form
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "js-escape")]
pub struct JsEscapeCommand {
  /// original Calcit symbol
  #[argh(positional)]
  pub symbol: String,
}

/// decode escaped JavaScript identifier back to Calcit symbol (best-effort)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "js-unescape")]
pub struct JsUnescapeCommand {
  /// escaped JavaScript identifier
  #[argh(positional)]
  pub symbol: String,
}

/// check type-information coverage in namespace definitions
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "check-types")]
pub struct CheckTypesCommand {
  /// exact namespace to analyze
  #[argh(option)]
  pub ns: Option<String>,
  /// namespace prefix scope filter
  #[argh(option)]
  pub ns_prefix: Option<String>,
  /// coverage levels to include, comma-separated: none,partial,full
  #[argh(option)]
  pub only: Option<String>,
  /// include dependency/core namespaces
  #[argh(switch)]
  pub deps: bool,
}

/// check examples in namespace
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "check-examples")]
pub struct CheckExamplesCommand {
  /// target namespace to check examples
  #[argh(option)]
  pub ns: String,
}

/// analyze call tree structure from entry point
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "call-graph")]
pub struct CallGraphCommand {
  /// directly specify root definition to analyze (format: ns/def). If omitted, uses init-fn from config
  #[argh(option)]
  pub root: Option<String>,
  /// only show definitions whose namespace starts with this prefix
  #[argh(option)]
  pub ns_prefix: Option<String>,
  /// include core/library calls in the output
  #[argh(switch)]
  pub include_core: bool,
  /// maximum depth to traverse (0 = unlimited)
  #[argh(option, default = "0")]
  pub max_depth: usize,
  /// show unused definitions for the selected entry
  #[argh(switch)]
  pub show_unused: bool,
  /// output format: "text" (default, LLM-friendly) or "json"
  #[argh(option, default = "String::from(\"text\")")]
  pub format: String,
}

/// count call occurrences from entry point
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "count-calls")]
pub struct CountCallsCommand {
  /// directly specify root definition to analyze (format: ns/def). If omitted, uses init-fn from config
  #[argh(option)]
  pub root: Option<String>,
  /// only show definitions whose namespace starts with this prefix
  #[argh(option)]
  pub ns_prefix: Option<String>,
  /// include core/library calls in the count
  #[argh(switch)]
  pub include_core: bool,
  /// output format: "text" (default) or "json"
  #[argh(option, default = "String::from(\"text\")")]
  pub format: String,
  /// sort by: "count" (default, descending) or "name"
  #[argh(option, default = "String::from(\"count\")")]
  pub sort: String,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Query subcommand - project information queries
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "query")]
/// query project information (namespaces, definitions, configs)
pub struct QueryCommand {
  #[argh(subcommand)]
  pub subcommand: QuerySubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum QuerySubcommand {
  /// list namespaces (or show ns details if namespace provided)
  Ns(QueryNsCommand),
  /// list definitions in a namespace
  Defs(QueryDefsCommand),
  /// get package name
  Pkg(QueryPkgCommand),
  /// read project configs
  Config(QueryConfigCommand),
  /// read .calcit-error.cirru file
  Error(QueryErrorCommand),
  /// list modules in the project
  Modules(QueryModulesCommand),
  /// read a definition's full code
  Def(QueryDefCommand),
  /// peek definition signature without full body
  Peek(QueryPeekCommand),
  /// read examples of a definition
  Examples(QueryExamplesCommand),
  /// find symbol across namespaces
  Find(QueryFindCommand),
  /// find usages of a definition
  Usages(QueryUsagesCommand),
  /// search for leaf nodes (strings) in definition
  Search(QuerySearchCommand),
  /// search for structural expressions (Cirru expr or JSON array) in definition
  SearchExpr(QuerySearchExprCommand),
  /// read a definition's schema (type information)
  Schema(QuerySchemaCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "schema")]
/// read a definition's schema (type information)
pub struct QuerySchemaCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// also output JSON format for programmatic consumption
  #[argh(switch, short = 'j')]
  pub json: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "ns")]
/// list namespaces, or show ns details if namespace provided
pub struct QueryNsCommand {
  /// namespace to show details (optional, lists all if omitted)
  #[argh(positional)]
  pub namespace: Option<String>,
  /// include dependency and core namespaces
  #[argh(switch)]
  pub deps: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "defs")]
/// list definitions in a namespace
pub struct QueryDefsCommand {
  /// namespace to query
  #[argh(positional)]
  pub namespace: String,
}

// read-ns merged into ns command

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "pkg")]
/// get package name
pub struct QueryPkgCommand {}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "config")]
/// read project configs (init_fn, reload_fn, version)
pub struct QueryConfigCommand {}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "error")]
/// read .calcit-error.cirru file for error stack traces
pub struct QueryErrorCommand {}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "modules")]
/// list modules in the project
pub struct QueryModulesCommand {}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "def")]
/// read a definition's full code
pub struct QueryDefCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// also output JSON format for programmatic consumption
  #[argh(switch, short = 'j')]
  pub json: bool,
  /// preferred nodes per display fragment when large expressions are chunked
  #[argh(option, default = "56")]
  pub chunk_target_nodes: usize,
  /// stop recursive chunk splitting once fragments fall below this node count
  #[argh(option, default = "68")]
  pub chunk_max_nodes: usize,
  /// only enable chunked display when total expression nodes reach this threshold
  #[argh(option, default = "88")]
  pub chunk_trigger_nodes: usize,
  /// force raw full-definition display without chunking
  #[argh(switch)]
  pub raw: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "peek")]
/// peek definition signature without full body
pub struct QueryPeekCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "examples")]
/// read examples of a definition
pub struct QueryExamplesCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "find")]
/// find symbol across namespaces (fuzzy match by default; use --exact for precise match)
pub struct QueryFindCommand {
  /// symbol name or pattern to search for (fuzzy match by default)
  #[argh(positional)]
  pub symbol: String,
  /// include dependency namespaces in search
  #[argh(switch)]
  pub deps: bool,
  /// exact match: only match definitions with this exact name
  #[argh(switch)]
  pub exact: bool,
  /// maximum number of results (default 20)
  #[argh(option, short = 'n', default = "20")]
  pub limit: usize,
  /// start index for detailed display window (3 detailed items)
  #[argh(option, long = "detail-offset", default = "0")]
  pub detail_offset: usize,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "usages")]
/// find usages of a definition across the project
pub struct QueryUsagesCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// include dependency namespaces in search
  #[argh(switch)]
  pub deps: bool,
  /// start index for detailed display window (3 detailed items)
  #[argh(option, long = "detail-offset", default = "0")]
  pub detail_offset: usize,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "search")]
/// search for leaf nodes (strings) across project or in specific namespace/definition (fuzzy match by default)
pub struct QuerySearchCommand {
  /// string pattern to search for in leaf nodes
  #[argh(positional)]
  pub pattern: String,
  /// filter search to specific namespace or namespace/definition (optional)
  #[argh(option, short = 'f', long = "filter")]
  pub filter: Option<String>,
  /// exact match: only match nodes equal to the pattern (default is contains-match)
  #[argh(switch)]
  pub exact: bool,
  /// maximum search depth (0 = unlimited)
  #[argh(option, short = 'd', default = "0")]
  pub max_depth: usize,
  /// start search from specific path (dot-separated indices preferred, e.g. "2.1.0")
  #[argh(option, short = 'p', long = "start-path")]
  pub start_path: Option<String>,
  /// include modules configured for a specific entry in `entries`
  #[argh(option, long = "entry")]
  pub entry: Option<String>,
  /// start index for detailed display window (3 detailed items)
  #[argh(option, long = "detail-offset", default = "0")]
  pub detail_offset: usize,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "search-expr")]
/// search for structural expressions (Cirru expr or JSON array) across project or in specific namespace/definition (fuzzy match by default)
pub struct QuerySearchExprCommand {
  /// pattern to search for (Cirru one-liner or JSON array with -j)
  #[argh(positional)]
  pub pattern: String,
  /// filter search to specific namespace or namespace/definition (optional)
  #[argh(option, short = 'f', long = "filter")]
  pub filter: Option<String>,
  /// exact match: only match structurally identical expressions (default is prefix/contains match)
  #[argh(switch)]
  pub exact: bool,
  /// maximum search depth (0 = unlimited)
  #[argh(option, short = 'd', default = "0")]
  pub max_depth: usize,
  /// treat pattern as JSON array instead of Cirru expr
  #[argh(switch, short = 'j')]
  pub json: bool,
  /// include modules configured for a specific entry in `entries`
  #[argh(option, long = "entry")]
  pub entry: Option<String>,
  /// start index for detailed display window (3 detailed items)
  #[argh(option, long = "detail-offset", default = "0")]
  pub detail_offset: usize,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Docs subcommand - documentation tools
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "docs")]
/// documentation tools (guidebook)
pub struct DocsCommand {
  #[argh(subcommand)]
  pub subcommand: DocsSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum DocsSubcommand {
  /// search guidebook documentation by keyword
  Search(DocsSearchCommand),
  /// read markdown headings or sections by heading query
  Read(DocsReadCommand),
  /// read cached Agents guide (auto-refresh daily)
  Agents(DocsAgentsCommand),
  /// read a specific line range from a guidebook document
  ReadLines(DocsReadLinesCommand),
  /// list all guidebook documentation topics
  List(DocsListCommand),
  /// check ```cirru code blocks in a markdown file via eval
  CheckMd(DocsCheckMdCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "search")]
/// search guidebook documentation by keyword
pub struct DocsSearchCommand {
  /// keyword to search
  #[argh(positional)]
  pub keyword: String,
  /// number of context lines to show before and after match (default: 5)
  #[argh(option, short = 'c', default = "5")]
  pub context: usize,
  /// filter by filename (optional)
  #[argh(option, short = 'f')]
  pub filename: Option<String>,
  /// search scope: core, modules, or all (default: core; with --module defaults to modules)
  #[argh(option)]
  pub scope: Option<String>,
  /// search docs for a specific installed module (e.g. respo.calcit)
  #[argh(option)]
  pub module: Option<String>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "read")]
/// read markdown headings or sections by heading query
pub struct DocsReadCommand {
  /// filename to read (e.g., "syntax.md")
  #[argh(positional)]
  pub filename: String,
  /// heading keyword(s) for fuzzy match, can pass multiple; if omitted, list all markdown headings
  #[argh(positional)]
  pub headings: Vec<String>,
  /// do not include nested subheadings when showing matched parent heading content
  #[argh(switch)]
  pub no_subheadings: bool,
  /// show full file content directly
  #[argh(switch)]
  pub full: bool,
  /// show line numbers in heading list and section titles
  #[argh(switch)]
  pub with_lines: bool,
  /// read scope: core, modules, or all (default: core; with --module defaults to modules)
  #[argh(option)]
  pub scope: Option<String>,
  /// read docs from a specific installed module (e.g. respo.calcit)
  #[argh(option)]
  pub module: Option<String>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "agents")]
/// read Agents.md with local cache (~/.config/calcit/Agents.md), refresh if older than 1 day
pub struct DocsAgentsCommand {
  /// heading keyword(s) for fuzzy match, can pass multiple; if omitted, list all markdown headings
  #[argh(positional)]
  pub headings: Vec<String>,
  /// do not include nested subheadings when showing matched parent heading content
  #[argh(switch)]
  pub no_subheadings: bool,
  /// show full file content directly
  #[argh(switch)]
  pub full: bool,
  /// show line numbers in heading list and section titles
  #[argh(switch)]
  pub with_lines: bool,
  /// force refresh from remote and ignore cache age
  #[argh(switch)]
  pub refresh: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "read-lines")]
/// read a specific line range from a guidebook document
pub struct DocsReadLinesCommand {
  /// filename to read (e.g., "syntax.md")
  #[argh(positional)]
  pub filename: String,
  /// starting line number (default: 0)
  #[argh(option, short = 's', default = "0")]
  pub start: usize,
  /// number of lines to read (default: 80)
  #[argh(option, short = 'n', default = "80")]
  pub lines: usize,
  /// read scope: core, modules, or all (default: core; with --module defaults to modules)
  #[argh(option)]
  pub scope: Option<String>,
  /// read docs from a specific installed module (e.g. respo.calcit)
  #[argh(option)]
  pub module: Option<String>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "list")]
/// list all guidebook documentation topics
pub struct DocsListCommand {}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "check-md")]
/// check ```cirru code blocks in a markdown file via eval
pub struct DocsCheckMdCommand {
  /// path to the markdown file to check
  #[argh(positional)]
  pub file: String,
  /// entry .cirru file for eval context (default: demos/compact.cirru)
  #[argh(option, short = 'd', default = "String::from(\"demos/compact.cirru\")")]
  pub entry: String,
  /// dependency module path for eval context, can be provided multiple times; paths ending with '/' load compact.cirru
  #[argh(option)]
  pub dep: Vec<String>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Cirru subcommand - syntax tools
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "cirru")]
/// Cirru syntax tools (parse, format, edn)
pub struct CirruCommand {
  #[argh(subcommand)]
  pub subcommand: CirruSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum CirruSubcommand {
  /// parse Cirru code to JSON
  Parse(CirruParseCommand),
  /// format JSON to Cirru code
  Format(CirruFormatCommand),
  /// parse Cirru EDN to JSON
  ParseEdn(CirruParseEdnCommand),
  /// show Cirru syntax guide for LLM code generation
  ShowGuide(CirruShowGuideCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "parse")]
/// parse Cirru code to JSON
pub struct CirruParseCommand {
  /// cirru code to parse
  #[argh(positional)]
  pub code: String,
  /// parse input as a single-line Cirru expression (one-liner parser, default is multi-line)
  #[argh(switch, short = 'e', long = "expr-one")]
  pub expr_one_liner: bool,
  /// perform basic syntax validation after parsing (checks keywords, strings, numbers)
  #[argh(switch, short = 'v', long = "validate")]
  pub validate: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "format")]
/// format JSON to Cirru code
pub struct CirruFormatCommand {
  /// JSON data to format (as string)
  #[argh(positional)]
  pub json: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "parse-edn")]
/// parse Cirru EDN to JSON
pub struct CirruParseEdnCommand {
  /// cirru EDN to parse
  #[argh(positional)]
  pub edn: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "show-guide")]
/// show Cirru syntax guide for LLM code generation
pub struct CirruShowGuideCommand {}

// ═══════════════════════════════════════════════════════════════════════════════
// Libs subcommand - library registry
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "libs")]
/// fetch available Calcit libraries from registry
pub struct LibsCommand {
  #[argh(subcommand)]
  pub subcommand: Option<LibsSubcommand>,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum LibsSubcommand {
  /// show README of a library
  Readme(LibsReadmeCommand),
  /// search libraries by keyword
  Search(LibsSearchCommand),
  /// scan markdown files in a module directory
  ScanMd(LibsScanMdCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "readme")]
/// show README of a library from local ~/.config/calcit/modules or GitHub
pub struct LibsReadmeCommand {
  /// package name to look up
  #[argh(positional)]
  pub package: String,
  /// heading keyword(s) for fuzzy match, can pass multiple; if omitted, list markdown headings
  #[argh(positional)]
  pub headings: Vec<String>,
  /// optional file path relative to package directory (e.g., "Skills.md")
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// do not include nested subheadings when showing matched parent heading content
  #[argh(switch)]
  pub no_subheadings: bool,
  /// show full file content directly
  #[argh(switch)]
  pub full: bool,
  /// show line numbers in heading list and section titles
  #[argh(switch)]
  pub with_lines: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "search")]
/// search libraries by keyword in name or description
pub struct LibsSearchCommand {
  /// keyword to search
  #[argh(positional)]
  pub keyword: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "scan-md")]
/// scan markdown files in a module directory
pub struct LibsScanMdCommand {
  /// module name to scan
  #[argh(positional)]
  pub module: String,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Edit subcommand - code editing operations
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "edit")]
/// edit project code (definitions, namespaces, modules, configs)
pub struct EditCommand {
  #[argh(subcommand)]
  pub subcommand: EditSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum EditSubcommand {
  /// rewrite snapshot file in canonical format without semantic changes
  Format(EditFormatCommand),
  /// add or update a definition
  Def(EditDefCommand),
  /// move a definition to another namespace
  MvDef(EditMvDefCommand),
  /// delete a definition
  RmDef(EditRmDefCommand),
  /// update definition documentation
  Doc(EditDocCommand),
  /// update definition schema payload (inside quote)
  Schema(EditSchemaCommand),
  /// set definition examples
  Examples(EditExamplesCommand),
  /// add a single example to definition
  AddExample(EditAddExampleCommand),
  /// remove an example from definition by index
  RmExample(EditRmExampleCommand),
  /// add a new namespace
  AddNs(EditAddNsCommand),
  /// delete a namespace
  RmNs(EditRmNsCommand),
  /// update namespace imports (replace all)
  Imports(EditImportsCommand),
  /// add a single import rule to namespace
  AddImport(EditAddImportCommand),
  /// remove an import rule from namespace
  RmImport(EditRmImportCommand),
  /// update namespace documentation
  NsDoc(EditNsDocCommand),
  /// create a new module
  AddModule(EditAddModuleCommand),
  /// delete a module
  RmModule(EditRmModuleCommand),
  /// update project configs
  Config(EditConfigCommand),
  /// describe incremental code changes and export them to .calcit-error.cirru
  Inc(EditIncCommand),
  /// copy node from one path to another within a definition
  Cp(EditCpCommand),
  /// move node from one path to another within a definition (removes source)
  Mv(EditMvNodeCommand),
  /// rename a definition within its namespace (no overwrite)
  Rename(EditRenameCommand),
  /// extract a sub-expression into a new definition and replace in-place with the new name
  SplitDef(EditSplitDefCommand),
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "format")]
/// rewrite target snapshot file in canonical format
pub struct EditFormatCommand {}

// --- Definition operations ---

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "def")]
/// add a new definition
pub struct EditDefCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// read syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes; e.g. --leaf -e 'sym' or --leaf -e '|text')
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// overwrite existing definition if it already exists
  #[argh(switch, long = "overwrite")]
  pub overwrite: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "mv-def")]
/// move a definition to another namespace or rename it
pub struct EditMvDefCommand {
  /// source in format "namespace/definition"
  #[argh(positional)]
  pub source: String,
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-def")]
/// delete a definition
pub struct EditRmDefCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "doc")]
/// update definition documentation
pub struct EditDocCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// documentation text
  #[argh(positional)]
  pub doc: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "schema")]
/// update definition schema (validates structure before writing; cr edit format normalises old quote-wrapped schemas to direct map)
pub struct EditSchemaCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// read schema from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// schema as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// schema as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes; e.g. --leaf -e 'sym' or --leaf -e '|text')
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// clear schema field
  #[argh(switch, long = "clear")]
  pub clear: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "examples")]
/// set definition examples (replaces all)
pub struct EditExamplesCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// read examples from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// examples as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// examples as inline JSON array string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON array
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes; e.g. --leaf -e 'sym' or --leaf -e '|text')
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// clear all examples
  #[argh(switch, long = "clear")]
  pub clear: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "add-example")]
/// add a single example to definition
pub struct EditAddExampleCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// position to insert at (default: append to end)
  #[argh(option, long = "at")]
  pub at: Option<usize>,
  /// read example from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// example as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// example as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes; e.g. --leaf -e 'sym' or --leaf -e '|text')
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-example")]
/// remove an example from definition by index
pub struct EditRmExampleCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// index of example to remove (0-based)
  #[argh(positional)]
  pub index: usize,
}

// --- Namespace operations ---

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "add-ns")]
/// add a new namespace (ns syntax_tree input: Cirru by default; use --json-input or -j for JSON)
pub struct EditAddNsCommand {
  /// namespace name to create
  #[argh(positional)]
  pub namespace: String,
  /// read ns syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// ns syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// ns syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes; e.g. --leaf -e 'sym' or --leaf -e '|text')
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-ns")]
/// delete a namespace
pub struct EditRmNsCommand {
  /// namespace to delete
  #[argh(positional)]
  pub namespace: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "imports")]
/// update namespace imports (replaces all)
pub struct EditImportsCommand {
  /// namespace to update
  #[argh(positional)]
  pub namespace: String,
  /// read imports from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// imports as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// imports as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes; e.g. --leaf -e 'sym' or --leaf -e '|text')
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "add-import")]
/// add a single import rule to namespace
pub struct EditAddImportCommand {
  /// namespace to add import rule to
  #[argh(positional)]
  pub namespace: String,
  /// read import rule from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// import rule as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// import rule as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes; e.g. --leaf -e 'sym' or --leaf -e '|text')
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// overwrite existing rule for the same source namespace
  #[argh(switch, short = 'o', long = "overwrite")]
  pub overwrite: bool,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-import")]
/// remove an import rule from namespace
pub struct EditRmImportCommand {
  /// namespace to remove import rule from
  #[argh(positional)]
  pub namespace: String,
  /// source namespace to remove (e.g. "calcit.core")
  #[argh(positional)]
  pub source_ns: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "ns-doc")]
/// update namespace documentation
pub struct EditNsDocCommand {
  /// namespace to update
  #[argh(positional)]
  pub namespace: String,
  /// documentation text
  #[argh(positional)]
  pub doc: String,
}

// --- Module operations ---

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "add-module")]
/// create a new module (adds to configs.modules)
pub struct EditAddModuleCommand {
  /// module path to add (e.g. "calcit-test/")
  #[argh(positional)]
  pub module_path: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rm-module")]
/// delete a module
pub struct EditRmModuleCommand {
  /// module path to delete
  #[argh(positional)]
  pub module_path: String,
}

// --- Config operations ---

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "config")]
/// update project config values
pub struct EditConfigCommand {
  /// config key: "init-fn", "reload-fn", "version"
  #[argh(positional)]
  pub key: String,
  /// config value
  #[argh(positional)]
  pub value: String,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "inc")]
/// record incremental changes (defs and namespaces) for downstream tooling
pub struct EditIncCommand {
  /// namespaces whose entire file should be treated as newly added (e.g. "app.new")
  #[argh(option, long = "added-ns")]
  pub added_ns: Vec<String>,
  /// namespaces that should be treated as removed from the project
  #[argh(option, long = "removed-ns")]
  pub removed_ns: Vec<String>,
  /// namespaces whose ns form/imports changed (stores latest ns block)
  #[argh(option, long = "ns-updated")]
  pub ns_updated: Vec<String>,
  /// definitions that were newly added (format: namespace/definition)
  #[argh(option, long = "added")]
  pub added: Vec<String>,
  /// definitions that were deleted (format: namespace/definition)
  #[argh(option, long = "removed")]
  pub removed: Vec<String>,
  /// definitions that were modified (format: namespace/definition)
  #[argh(option, long = "changed")]
  pub changed: Vec<String>,
}

// ========================================================================
// Code command - fine-grained code tree operations
// ========================================================================

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "tree")]
/// fine-grained code tree operations (view and modify AST nodes)
pub struct TreeCommand {
  #[argh(subcommand)]
  pub subcommand: TreeSubcommand,
}

#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand)]
pub enum TreeSubcommand {
  Show(TreeShowCommand),
  Replace(TreeReplaceCommand),
  ReplaceLeaf(TreeReplaceLeafCommand),
  Delete(TreeDeleteCommand),
  InsertBefore(TreeInsertBeforeCommand),
  InsertAfter(TreeInsertAfterCommand),
  InsertChild(TreeInsertChildCommand),
  AppendChild(TreeAppendChildCommand),
  SwapNext(TreeSwapNextCommand),
  SwapPrev(TreeSwapPrevCommand),
  Unwrap(TreeUnwrapCommand),
  Raise(TreeRaiseCommand),
  Wrap(TreeWrapCommand),
  TargetReplace(TreeTargetReplaceCommand),
  Rewrite(TreeStructuralCommand),
}

/// view tree node at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "show")]
pub struct TreeShowCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (dot-separated preferred, comma-separated also accepted; e.g. "2.1.0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
  /// also output JSON format for programmatic consumption
  #[argh(switch, short = 'j')]
  pub json: bool,
  /// preferred nodes per display fragment when large expressions are chunked
  #[argh(option, default = "56")]
  pub chunk_target_nodes: usize,
  /// stop recursive chunk splitting once fragments fall below this node count
  #[argh(option, default = "68")]
  pub chunk_max_nodes: usize,
  /// only enable chunked display when total expression nodes reach this threshold
  #[argh(option, default = "88")]
  pub chunk_trigger_nodes: usize,
  /// nested chunk layers to expand beyond ROOT (default 1 shows ROOT + direct chunks only)
  #[argh(option, default = "1")]
  pub chunk_expand_depth: usize,
  /// force raw subtree display without chunking
  #[argh(switch)]
  pub raw: bool,
}

/// copy node from one path to another within a definition
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "cp")]
pub struct EditCpCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the source node (comma-separated indices)
  #[argh(option, long = "from")]
  pub from: String,
  /// path to the destination node (comma-separated indices)
  #[argh(option, short = 'p', long = "path")]
  pub path: String,
  /// position relative to the destination node (before, after, append-child, prepend-child, replace)
  #[argh(option, long = "at", default = "String::from(\"after\")")]
  pub at: String,
}

/// move node from one path to another within a definition (removes source)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "mv")]
pub struct EditMvNodeCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the source node (comma-separated indices)
  #[argh(option, long = "from")]
  pub from: String,
  /// path to the destination node (comma-separated indices)
  #[argh(option, short = 'p', long = "path")]
  pub path: String,
  /// position relative to the destination node (before, after, append-child, prepend-child, replace)
  #[argh(option, long = "at", default = "String::from(\"after\")")]
  pub at: String,
}

/// rename a definition within its namespace (no overwrite)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rename")]
pub struct EditRenameCommand {
  /// source in format "namespace/definition"
  #[argh(positional)]
  pub source: String,
  /// new definition name (within same namespace)
  #[argh(positional)]
  pub new_name: String,
}

/// extract a sub-expression into a new definition and replace the original location with the new name
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "split-def")]
pub struct EditSplitDefCommand {
  /// source definition in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node to extract (comma-separated indices, e.g. "3,2,1")
  #[argh(option, short = 'p', long = "path")]
  pub path: String,
  /// name for the new extracted definition (within the same namespace)
  #[argh(option, short = 'n', long = "name")]
  pub new_name: String,
}

/// rewrite node using references; requires `--with name=path` (use `replace` if no references)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "rewrite")]
pub struct TreeStructuralCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// read syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes; e.g. --leaf -e 'sym' or --leaf -e '|text')
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// bind placeholder to original-node path: `--with self=.` , `--with rhs=2`
  #[argh(option, short = 'w', long = "with")]
  pub with: Vec<String>,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// find unique leaf node and replace it; if multiple found, returns error with helpful hints
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "target-replace")]
pub struct TreeTargetReplaceCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// pattern to search for (exact match on leaf nodes)
  #[argh(option, long = "pattern")]
  pub pattern: String,
  /// read syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes)
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// replace node at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "replace")]
pub struct TreeReplaceCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// read syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes; e.g. --leaf -e 'sym' or --leaf -e '|text')
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// find and replace all matching leaf nodes in definition (no path needed)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "replace-leaf")]
pub struct TreeReplaceLeafCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// pattern to search for (exact match on leaf nodes)
  #[argh(option, long = "pattern")]
  pub pattern: String,
  /// read syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node (single symbol or string, no JSON quotes)
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// delete node at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "delete")]
pub struct TreeDeleteCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// insert node before target at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "insert-before")]
pub struct TreeInsertBeforeCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// read syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// parse input as a single-line Cirru expression (one-liner parser)
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat file input as a leaf node (for strings, use Cirru syntax: |text or "text)
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// insert node after target at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "insert-after")]
pub struct TreeInsertAfterCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// read syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// parse input as a single-line Cirru expression (one-liner parser)
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat file input as a leaf node (for strings, use Cirru syntax: |text or "text)
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// insert node as first child of target at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "insert-child")]
pub struct TreeInsertChildCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// read syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// parse input as a single-line Cirru expression (one-liner parser)
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat file input as a leaf node (for strings, use Cirru syntax: |text or "text)
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// append node as last child of target at specific path
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "append-child")]
pub struct TreeAppendChildCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// read syntax_tree from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// syntax_tree as inline Cirru text (or JSON when used with -J/--json-input)
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// syntax_tree as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// parse input as a single-line Cirru expression (one-liner parser)
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat file input as a leaf node (for strings, use Cirru syntax: |text or "text)
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// swap node with next sibling
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "swap-next")]
pub struct TreeSwapNextCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// swap node with previous sibling
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "swap-prev")]
pub struct TreeSwapPrevCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// splice all children of a node into its parent (inverse of wrap/rewrite)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "unwrap")]
pub struct TreeUnwrapCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node to unwrap (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// replace the parent node with this child node (Paredit raise-sexp)
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "raise")]
pub struct TreeRaiseCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the child node to raise (must have at least one element; its parent will be replaced)
  #[argh(option, short = 'p')]
  pub path: String,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}

/// wrap the node at path inside a new expression, using `self` as placeholder for the original node
#[derive(FromArgs, PartialEq, Debug, Clone)]
#[argh(subcommand, name = "wrap")]
pub struct TreeWrapCommand {
  /// target in format "namespace/definition"
  #[argh(positional)]
  pub target: String,
  /// path to the node to wrap (comma-separated indices, e.g. "2,1,0")
  #[argh(option, short = 'p')]
  pub path: String,
  /// wrapping expression with `self` as placeholder for the original node (e.g. 'println self')
  #[argh(option, short = 'e', long = "code")]
  pub code: Option<String>,
  /// read wrapping expression from file (Cirru format by default, use -J for JSON)
  #[argh(option, short = 'f')]
  pub file: Option<String>,
  /// wrapping expression as inline JSON string
  #[argh(option, short = 'j')]
  pub json: Option<String>,
  /// treat file input as JSON
  #[argh(switch, short = 'J', long = "json-input")]
  pub json_input: bool,
  /// treat input as a Cirru leaf node
  #[argh(switch, long = "leaf")]
  pub leaf: bool,
  /// max depth for result preview (0 = unlimited, default 2)
  #[argh(option, short = 'd', default = "2")]
  pub depth: usize,
}