inkhaven 1.3.9

Inkhaven — TUI literary work editor for Typst books
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
pub mod add;
pub mod ai;
pub mod backup;
pub mod build;
pub mod bund;
pub mod delete;
pub mod recover;
pub mod export;
pub mod export_concordance;
pub mod export_timeline;
pub mod import_help;
pub mod import_scrivener;
pub mod import_typst_help;
pub mod init;
pub mod list;
pub mod mv;
pub mod reindex;
pub mod restore;
pub mod search;
pub mod doctor;
pub mod doctor_scan;
pub mod event;
pub mod comments;
pub mod language;
pub mod templates;
pub mod thread;
pub mod tts;
pub mod gen_fixture;
pub mod bench_load;
pub mod bench_report;
pub mod epub;
pub mod audiobook;
pub mod continuity;
pub mod facts_scan;
pub mod pdf;
pub mod replace;
pub mod tension;
pub mod manuscript;
pub mod docx;
pub mod submissions;
pub mod submission;
pub mod plan;
pub mod editorial;
pub mod prompts;
pub mod show_dont_tell;
pub mod stats;
pub(crate) mod book_walk;

use std::path::PathBuf;

use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};

use crate::store::NodeKind;

/// Resolve the target user book for a CLI command.
///
/// User books are top-level `Book` nodes without a
/// `system_tag` (Characters / Places / Threads etc. carry
/// one).  With `--book-name`, match by title or slug
/// (case-insensitive); without it, succeed only when the
/// project has exactly one user book.
///
/// Returns a borrowed node — callers `.clone()` when they
/// need an owned `Node`.  The `Err` is a ready-to-display
/// message prefixed with `context` (the command name);
/// callers map it into their module's error type
/// (`Error::Store` or `anyhow!`).
///
/// The single home for user-book resolution, shared by
/// build / epub / audiobook / manuscript / event /
/// export-timeline.
pub(crate) fn resolve_user_book<'a>(
    h: &'a crate::store::hierarchy::Hierarchy,
    book_name: Option<&str>,
    context: &str,
) -> std::result::Result<&'a crate::store::node::Node, String> {
    use crate::store::node::Node;
    let user_books: Vec<&Node> = h
        .children_of(None)
        .into_iter()
        .filter(|n| n.kind == NodeKind::Book && n.system_tag.is_none())
        .collect();

    match book_name {
        Some(name) => {
            let needle = name.trim().to_ascii_lowercase();
            user_books
                .iter()
                .copied()
                .find(|b| {
                    b.title.to_ascii_lowercase() == needle
                        || b.slug.to_ascii_lowercase() == needle
                })
                .ok_or_else(|| {
                    let listing = user_books
                        .iter()
                        .map(|b| format!("`{}` (slug: {})", b.title, b.slug))
                        .collect::<Vec<_>>()
                        .join(", ");
                    let listing = if listing.is_empty() {
                        "no user books in this project".to_string()
                    } else {
                        listing
                    };
                    format!(
                        "{context}: no book matches `--book-name {name}`. Available: {listing}"
                    )
                })
        }
        None => match user_books.as_slice() {
            [book] => Ok(*book),
            [] => Err(format!(
                "{context}: project has no user books — add one with `inkhaven add book <title>`"
            )),
            _ => Err(format!(
                "{context}: project has {} user books — pass --book-name",
                user_books.len()
            )),
        },
    }
}

/// 1.3.3 — the Prompts-book tier of the CLI prompt resolver: a paragraph
/// in the Prompts system book whose slug or title matches `name` (the
/// `submission-*` / `plan-*` slug).  Gives the CLI generators the same
/// three-tier resolution the TUI has (Prompts book → `prompts.hjson` →
/// built-in).  Returns the body with a leading `= heading` stripped.
pub(crate) fn resolve_book_prompt(
    store: &crate::store::Store,
    h: &crate::store::hierarchy::Hierarchy,
    name: &str,
) -> Option<String> {
    let book = h.iter().find(|n| {
        n.kind == NodeKind::Book
            && n.system_tag.as_deref() == Some(crate::store::SYSTEM_TAG_PROMPTS)
    })?;
    let lower = name.to_lowercase();
    let spaced = lower.replace('-', " ");
    for id in h.collect_subtree(book.id) {
        let Some(node) = h.get(id) else { continue };
        if node.kind != NodeKind::Paragraph {
            continue;
        }
        let s = node.slug.to_lowercase();
        let t = node.title.to_lowercase();
        if s != lower && t != lower && t != spaced {
            continue;
        }
        let bytes = store.get_content(node.id).ok().flatten()?;
        let stripped = strip_typst_heading(&String::from_utf8_lossy(&bytes));
        if !stripped.trim().is_empty() {
            return Some(stripped);
        }
    }
    None
}

/// Drop a single leading `= heading` line (and the blank after it).
fn strip_typst_heading(body: &str) -> String {
    let mut lines = body.lines().peekable();
    if lines.peek().is_some_and(|l| l.trim_start().starts_with("= ")) {
        lines.next();
        if lines.peek().is_some_and(|l| l.trim().is_empty()) {
            lines.next();
        }
    }
    lines.collect::<Vec<_>>().join("\n").trim().to_string()
}

#[derive(Debug, Parser)]
#[command(name = "inkhaven", version, about = "TUI literary work editor for Typst books")]
pub struct Cli {
    /// Path to a project root. For `init`, this is the project to create. For
    /// every other subcommand, defaults to the current directory.  Accepts
    /// `--project`, the longer alias `--project-directory`, and the short
    /// form `-p` (1.2.10+).
    #[arg(long, short = 'p', alias = "project-directory", global = true)]
    pub project: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// Initialize a new inkhaven project at the given path.
    Init {
        /// Project directory to create.
        path: PathBuf,
        /// Overwrite existing configuration if present.
        #[arg(long)]
        force: bool,
        /// Project template to scaffold the
        /// manuscript book + chapters + system-book
        /// seed entries.  Accepts:
        /// `empty` (default, current behavior),
        /// `novel` (three-act manuscript + Characters
        /// stubs), `nonfiction` (intro/parts/
        /// conclusion + Research methodology),
        /// `rpg-sourcebook` (Setting/Rules/
        /// Adventures/Appendices + Places +
        /// Artefacts + Threads seeds), `technical`
        /// (Overview/Reference/Tutorials/Index),
        /// `nanowrimo` (like `novel` but with a
        /// 50000-word goal + next-November pacing).
        /// Run `inkhaven template list` to see all
        /// available templates with descriptions.
        #[arg(long, default_value = "empty")]
        template: String,
    },

    /// Add a node (book / chapter / subchapter / paragraph) to the hierarchy.
    Add {
        /// Node kind.
        #[arg(value_enum)]
        kind: CliNodeKind,
        /// Display title.
        title: String,
        /// Slash-separated slug path to the parent (e.g. `my-book/01-chapter`).
        /// Required for everything except `book` when not using --after.
        #[arg(long)]
        parent: Option<String>,
        /// Override the auto-assigned slug (defaults to slugified title).
        #[arg(long)]
        slug: Option<String>,
        /// Insert the new node immediately after an existing sibling of the
        /// same kind. Pass the sibling's slug path here; --parent is then
        /// implicit (taken from the anchor's parent).
        #[arg(long)]
        after: Option<String>,
    },

    /// Print the hierarchy as a tree.
    List,

    /// Delete a node (and its descendants) by slash-separated slug path.
    Delete {
        /// e.g. `my-book/the-storm/morning-light`
        path: String,
        /// Required confirmation flag — without it we just dry-run.
        #[arg(long)]
        yes: bool,
    },

    /// Reorder a node within its siblings by swapping with the neighbor.
    Mv {
        /// Slash-separated slug path to the node.
        path: String,
        /// `up` or `down`.
        #[arg(value_enum)]
        direction: mv::Direction,
    },

    /// Run a semantic search across the project.
    Search {
        query: String,
        #[arg(short, long, default_value_t = 10)]
        limit: usize,
    },

    /// Re-index all `.typ` files from disk into the document store.
    Reindex {
        /// Remove store records whose file is missing on disk.
        #[arg(long)]
        prune: bool,
        /// Register every orphan .typ file under the deepest hierarchy
        /// branch whose filesystem path matches the orphan's parent dir.
        #[arg(long)]
        adopt: bool,
    },

    /// Export the book(s) to a target format.
    Export {
        #[arg(value_enum, default_value_t = ExportFormat::Typst)]
        format: ExportFormat,
        /// Output path (file for typst, directory for pdf builds).
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Name of the user book to export. Required when the
        /// project holds more than one user book; with a single user
        /// book it can be omitted and that book is used implicitly.
        /// System books (Help / Scripts / Typst / Prompts / Places /
        /// Characters / Notes / Artefacts / Research) are never
        /// included — they're inkhaven internals, not manuscript
        /// content. Matched case-insensitively against `Node.title`;
        /// falls back to slug match.
        #[arg(long)]
        book_name: Option<String>,
        /// Status floor (1.2.4+) — keep only paragraphs whose
        /// status sits at or above this rung on the workflow
        /// ladder. Lowercased: `napkin`, `first`, `second`,
        /// `third`, `final`, `ready`. `--status=ready` ships
        /// only Ready paragraphs (typical "submit to the agent"
        /// workflow). Unset = include every paragraph regardless
        /// of status (including paragraphs with no status set).
        #[arg(long)]
        status: Option<String>,
        /// Tag filter (1.2.6+) — keep only paragraphs that carry
        /// this tag (case-insensitive). Combines with `--status`:
        /// a paragraph must pass both predicates to be exported.
        /// Useful with the project-wide tagging surface
        /// (Ctrl+B ] / Ctrl+B }): tag a subset of paragraphs
        /// `draft`, then `inkhaven export pdf --tag draft` to
        /// ship just that slice.
        #[arg(long)]
        tag: Option<String>,
    },

    /// Run a one-shot AI inference from the command line.
    Ai {
        prompt: String,
        #[arg(short, long)]
        provider: Option<String>,
    },

    /// Import a directory tree into the Help system book. Subdirectories
    /// become chapters / subchapters / (flattened) and files become
    /// paragraphs. Filenames and directory names supply the displayed
    /// titles. Wipes Help's existing contents first.
    ImportHelp {
        /// Source directory whose contents will be ingested under the Help
        /// system book. Files at the root land as paragraphs directly under
        /// Help; subdirectories become chapters (then subchapters, etc.).
        #[arg(long)]
        documents_directory: PathBuf,
    },

    /// Import inkhaven's curated Typst reference into the Help system
    /// book. Creates / refreshes a `Typst reference` chapter so F1
    /// (RAG over Help) can answer typst questions from grounded
    /// context. Offline — the reference is bundled with the binary.
    ImportTypstHelp,

    /// Import a Scrivener (.scriv) project into the current
    /// inkhaven project (1.2.4+). Walks the binder, converts
    /// every Text document's RTF body to Typst, and
    /// materialises the hierarchy as inkhaven nodes. Single-
    /// binary — no Scrivener / pandoc / textutil required.
    ImportScrivener {
        /// Path to the `.scriv` package directory.
        scriv_path: PathBuf,
        /// Override the title used for the user book created
        /// from the Scrivener Draft folder. None → use the
        /// Draft folder's own title.
        #[arg(long)]
        draft_as_book: Option<String>,
        /// Skip everything outside the Draft (Research,
        /// Characters, Places folders Scrivener defaults to).
        #[arg(long)]
        skip_research: bool,
        /// Parse + report without creating any nodes.
        #[arg(long)]
        dry_run: bool,
    },

    /// Zip the project into a dated backup archive
    /// (`blackinkhaven_YYYYDDMM_HHMMSS.zip`).
    Backup {
        /// Output directory for the archive. Created if missing.
        /// Omit to use the project-relative default
        /// (`<parent-of-project>/inkhaven-backups/<project-basename>/`)
        /// — same location the TUI's exit hook writes to.
        #[arg(long)]
        out: Option<PathBuf>,
    },

    /// Restore a backup archive into a fresh directory.
    Restore {
        /// Path to the `.zip` backup file.
        archive: PathBuf,
        /// Destination directory. Must not already contain
        /// `inkhaven.hjson` — pick a fresh directory or wipe the old one
        /// first.
        #[arg(long)]
        to: PathBuf,
    },

    /// Evaluate a Bund expression against the Adam VM and print the
    /// top of the workbench. Phase-0 smoke command — does not open
    /// the project store. Use this to verify the scripting layer
    /// works on your install and to experiment with Bund syntax.
    Bund {
        /// The Bund script to run, e.g. `"40 2 + ."`.
        code: String,
    },

    /// Print a per-paragraph stats table (1.2.4+). Title, slug,
    /// status, word count, target %, last modified. System
    /// books are excluded; `--book-name` scopes to one user book
    /// the same way `inkhaven export` does.
    Stats {
        /// Name of the user book to report on. Required when the
        /// project holds more than one user book; with a single
        /// user book it can be omitted.
        #[arg(long)]
        book_name: Option<String>,
    },

    /// 1.2.12+ — export the project-wide concordance (every
    /// distinct lexical stem with count + KWIC samples) to a file
    /// for use in spreadsheets / analysis pipelines.  Same data the
    /// `Ctrl+B Shift+L` modal shows: stop-words / single-char
    /// tokens / pure digits filtered out; Snowball-stemmed so
    /// `walk` / `walked` / `walking` collapse to one row.  System
    /// books (Prompts / Characters / Places / Lore / Help / Notes /
    /// Artefacts) excluded — same scope as the in-TUI view.
    /// Multilingual via the project's `language` field.
    ExportConcordance {
        /// Output format.  CSV is one row per stem with semicolon-
        /// separated sample slug-paths; JSON is the structured form
        /// for downstream tooling.
        #[arg(value_enum, default_value_t = ConcordanceExportFormat::Csv)]
        format: ConcordanceExportFormat,
        /// Output path.  Required.
        #[arg(short, long)]
        output: PathBuf,
        /// Minimum count threshold.  Stems occurring fewer than
        /// this many times across the project are dropped from
        /// the export.  Default: 1 (everything).
        #[arg(long, default_value_t = 1)]
        min_count: usize,
    },

    /// Print a health report for the inkhaven install (1.2.5+).
    /// Three sections: binary (version + typst engine + font
    /// counts + package cache), project (when run inside an
    /// initialised project: hierarchy shape + word counts), and
    /// notes (actionable warnings like "typst not on PATH"). No
    /// questions asked, pipe-friendly plain-text output.
    ///
    /// 1.2.9+ — `--voices` swaps the default report for a
    /// pipe-friendly list of TTS voices visible to the host
    /// OS (`tts-rs`).  Useful for picking a value for
    /// `editor.tts.voice` in HJSON without leaving the
    /// terminal.
    Doctor {
        /// List every TTS voice the host OS exposes through
        /// `tts-rs`, one per line: `<name>  ·  <locale>`.
        /// Skips the rest of the health report when set.
        #[arg(long)]
        voices: bool,
        /// 1.2.9+ — diagnostic: init the TTS engine, set
        /// the configured voice + rate, speak the given
        /// text synchronously (block until audio drains),
        /// then exit.  Use when `Ctrl+B S` shows the
        /// modal but no audio plays — isolates the engine
        /// path from the rest of inkhaven's runtime.
        #[arg(long, value_name = "TEXT")]
        tts_test: Option<String>,
        /// 1.2.9+ — emit a copy-paste-ready HJSON
        /// snippet of every built-in filter-word list
        /// (English, Russian, French, German, Spanish).
        /// Paste under `editor.style_warnings.filter_words`
        /// to see and edit them in your project HJSON.
        #[arg(long)]
        filter_words_snippet: bool,
        /// 1.2.15+ — run the project scan only,
        /// skipping the dep-version / typst-engine
        /// dump.  Walks the hierarchy + on-disk
        /// files looking for zero-byte paragraphs,
        /// orphan DB rows, missing referenced files,
        /// and corrupt comment sidecars.
        #[arg(long)]
        scan: bool,
        /// 1.2.15+ — emit the scan results as
        /// JSON instead of human prose.  Implies
        /// `--scan`.  Useful for CI gates: `inkhaven
        /// doctor --json | jq -e '.findings == []'`.
        #[arg(long)]
        json: bool,
        /// 1.2.15+ — limit the scan to a single
        /// class.  Accepts: `zero-byte-file`,
        /// `orphan-paragraph-row`, `missing-
        /// referenced-file`, `corrupt-comments-
        /// sidecar`.
        #[arg(long, value_name = "CLASS")]
        class: Option<String>,
        /// 1.2.15+ Phase D.2 — apply per-class
        /// repairs.  Prompts `y/N` per finding
        /// unless `--yes` is also passed.  Every
        /// repair is logged to
        /// `<project>/.inkhaven/doctor.log` with
        /// before/after for audit.
        #[arg(long)]
        autofix: bool,
        /// Pair with `--autofix` to skip the per-
        /// finding prompt.  Intended for CI gates
        /// + scripted cleanup; refuses to start
        /// without `--autofix`.
        #[arg(long)]
        yes: bool,
    },

    /// 1.2.6+ — story-timeline event management. Requires
    /// `timeline.enabled: true` in HJSON.
    #[command(subcommand)]
    Event(EventCommand),

    /// 1.2.8+ — export a book's timeline (events grouped
    /// chronologically per track) to a file. Three formats:
    /// `typst` (a text listing typst users `#include`),
    /// `svg` (a self-contained swim-lane render — circles
    /// for instant events, bars for duration events, a
    /// date axis at the top), and `png` (the same SVG
    /// rasterised through resvg + tiny-skia).
    ExportTimeline {
        /// User-book name (case-insensitive title or slug).
        /// Optional when the project has exactly one user
        /// book; required otherwise. The book's Timeline
        /// chapter is read.
        #[arg(long)]
        book_name: Option<String>,
        /// Output format. Choose one of `typst` (text
        /// listing, default), `svg` (vector swim lane),
        /// or `png` (rasterised SVG).
        #[arg(value_enum, default_value_t = TimelineExportFormat::Typst)]
        format: TimelineExportFormat,
        /// Output path. Required.
        #[arg(short, long)]
        output: PathBuf,
        /// Optional track filter (case-insensitive). When
        /// set, only events on that track land in the
        /// output. Omit to include every track.
        #[arg(long)]
        track: Option<String>,
    },

    /// 1.2.6+ — run the same flow as the TUI's Ctrl+B B
    /// without launching the TUI. Assembles the named user
    /// book into the artefacts directory and (with
    /// `--compile`) runs `typst compile` on the produced root
    /// `.typ`. Pipe-friendly progress on stderr; only the
    /// final PDF path lands on stdout. Useful for CI, batch
    /// builds, and end-to-end verification of the
    /// HJSON-driven `settings.typ`.
    Build {
        /// User-book name (case-insensitive title or slug).
        /// Optional when the project has exactly one user
        /// book; required otherwise.
        #[arg(long)]
        book_name: Option<String>,
        /// Also invoke `typst compile` on the assembled root
        /// `.typ`. Without it the command stops after
        /// writing the artefacts tree.
        #[arg(long)]
        compile: bool,
    },

    /// 1.2.19+ X.1 — export a user book to a
    /// submission-ready Shunn standard manuscript format
    /// typst document (monospace, double-spaced, title
    /// page with rounded word count, running
    /// `Surname / KEYWORD / page` header, scene breaks as
    /// `#`).  The finishing-line companion to the
    /// reader-facing `epub` + `audiobook` exports.
    /// Compile to PDF with `typst compile <out>.typ`.
    Manuscript {
        /// User-book name (case-insensitive title or
        /// slug).  Optional when the project has exactly
        /// one user book.
        #[arg(long)]
        book_name: Option<String>,
        /// Output path.  Defaults to
        /// `<project>/<book-slug>-manuscript.typ`.
        #[arg(long, short = 'o')]
        output: Option<PathBuf>,
        /// Override the title (default: the book's title).
        #[arg(long)]
        title: Option<String>,
        /// Author / byline (default:
        /// `editor.comment_author`).
        #[arg(long)]
        author: Option<String>,
        /// Title-page contact block; use `\n` for line
        /// breaks (default: the author name).
        #[arg(long)]
        contact: Option<String>,
    },

    /// 1.3.1+ SUBMISSION-1 — export a user book to a
    /// Shunn standard-manuscript-format **Word** document
    /// (`.docx`) — the format agents actually require.
    /// Same layout as `manuscript` (double-spaced 12 pt,
    /// title page, `Surname / KEYWORD / page` header from
    /// page 2, scene breaks as `#`), emitted as OOXML.
    Docx {
        /// User-book name (case-insensitive title or
        /// slug).  Optional when the project has exactly
        /// one user book.
        #[arg(long)]
        book_name: Option<String>,
        /// Output path.  Defaults to
        /// `<project>/<book-slug>-manuscript.docx`.
        #[arg(long, short = 'o')]
        output: Option<PathBuf>,
        /// Override the title (default: the book's title).
        #[arg(long)]
        title: Option<String>,
        /// Author / byline (default:
        /// `editor.comment_author`).
        #[arg(long)]
        author: Option<String>,
        /// Title-page contact block; use `\n` for line
        /// breaks (default: the author name).
        #[arg(long)]
        contact: Option<String>,
        /// Body typeface: `times` (default) or `courier`.
        #[arg(long)]
        font: Option<String>,
    },

    /// 1.3.1+ SUBMISSION-1 — the submission tracker:
    /// record where the manuscript went, when, and what
    /// came back (the `.inkhaven/submissions.json`
    /// sidecar).  The generated drafts live in the
    /// `Submissions` system book.
    #[command(subcommand)]
    Submissions(SubmissionsCommand),

    /// 1.3.1+ SUBMISSION-1 — build the submission package
    /// (singular): the AI book `digest` now, the query /
    /// synopsis / comp / logline generators next.
    #[command(subcommand)]
    Submission(SubmissionCommand),

    /// 1.3.2+ PLANNING-1 — the Planning Board (story
    /// structure): `plan init` scaffolds a framework's
    /// beats; coverage/pacing + AI analyze follow.
    #[command(subcommand)]
    Plan(PlanCommand),

    /// 1.3.6 EDITORIAL-1 — **The Editorial Pass**: one ranked revision
    /// worklist unifying every detector (the editorial `doctor` classes +
    /// `plan check`'s structural findings + the Facts-scan sidecar). Reads
    /// what's already computed — no live AI.
    Edit {
        /// Machine-readable output for a CI gate.
        #[arg(long)]
        json: bool,
        /// Restrict to these categories (comma-separated), e.g.
        /// `echo,pacing,structure`.
        #[arg(long, value_delimiter = ',')]
        only: Option<Vec<String>>,
        /// Which book's structure findings to include (defaults to the sole
        /// user book).
        #[arg(long)]
        book_name: Option<String>,
        /// Include findings you've deferred in the cockpit (hidden by
        /// default).
        #[arg(long)]
        show_deferred: bool,
        /// Run the AI scans first (Facts / tension / continuity) to refresh
        /// their sidecars, then aggregate — the semantic tier. Needs a
        /// provider; not combinable with `--json`.
        #[arg(long)]
        deep: bool,
        /// LLM provider override for `--deep`.
        #[arg(long)]
        provider: Option<String>,
    },

    /// 1.2.18+ R.1 — export a user book to a
    /// standards-compliant EPUB 3 file.  Walks the
    /// book's chapters in order, converts the typst
    /// prose to XHTML, and assembles the container.
    /// The reader-facing companion to `inkhaven build`
    /// (which targets typst → PDF).
    Epub {
        /// User-book name (case-insensitive title or
        /// slug).  Optional when the project has exactly
        /// one user book; required otherwise.
        #[arg(long)]
        book_name: Option<String>,
        /// Output path.  Defaults to
        /// `<project>/<book-slug>.epub`.
        #[arg(long, short = 'o')]
        output: Option<PathBuf>,
        /// Override the EPUB title (default: the book's
        /// title).
        #[arg(long)]
        title: Option<String>,
        /// Override the author (default:
        /// `editor.comment_author`, else "Unknown
        /// Author").
        #[arg(long)]
        author: Option<String>,
    },

    /// 1.2.18+ R.2 — synthesise a user book to a
    /// single `.m4b` audiobook with a chapter marker per
    /// Chapter node.  Drives the TTS engine (Piper or
    /// macOS `say`) for per-chapter synthesis, then
    /// `ffmpeg` for the concat + chapter-metadata mux.
    /// Requires ffmpeg + ffprobe on PATH and
    /// `editor.tts.enabled = true`.  Synthesis is
    /// roughly real-time — a batch export, not
    /// interactive.
    Audiobook {
        /// User-book name (case-insensitive title or
        /// slug).  Optional when the project has exactly
        /// one user book.
        #[arg(long)]
        book_name: Option<String>,
        /// Output path.  Defaults to
        /// `<project>/<book-slug>.m4b`.
        #[arg(long, short = 'o')]
        output: Option<PathBuf>,
        /// Override the audiobook title (default: the
        /// book's title).
        #[arg(long)]
        title: Option<String>,
        /// Override the author (default:
        /// `editor.comment_author`).
        #[arg(long)]
        author: Option<String>,
    },

    /// 1.2.19+ C.3 — `inkhaven continuity
    /// <subcommand>`.  Build + inspect the continuity
    /// bible: `extract` runs the AI fact-extraction pass
    /// over the manuscript into
    /// `<project>/.inkhaven/continuity.json`; `list`
    /// dumps it.  The `continuity-drift` doctor scan then
    /// flags attributes that change across chapters.
    #[command(subcommand)]
    Continuity(ContinuityCommand),

    /// 1.2.19+ C.4 — `inkhaven tension <subcommand>`.
    /// `scan` runs the AI pass that tags each chapter's
    /// introduced + resolved tensions into
    /// `<project>/.inkhaven/tensions.json`; `list` dumps
    /// it.  Then `doctor --scan --class
    /// unresolved-tension` (opt-in) flags introduced
    /// tensions with no downstream payoff.
    #[command(subcommand)]
    Tension(TensionCommand),

    /// 1.2.21+ FF.2 — `inkhaven facts <subcommand>`.
    /// `scan` runs the AI pass that checks every chapter's
    /// prose against the Facts book (semantically-retrieved
    /// relevant facts per chapter) and records contradictions
    /// to `<project>/.inkhaven/facts_scan.json`; `list` dumps
    /// them.  `--json` emits the report for CI gates.
    #[command(subcommand)]
    Facts(FactsCommand),

    /// 1.3.0 PDF-1 — `inkhaven pdf <subcommand>`.  Page operations
    /// (extract / split / merge / rotate / reorder / delete), metadata,
    /// and outline over an existing PDF.  Writes are atomic and never
    /// silently overwrite the input.
    #[command(subcommand)]
    Pdf(PdfCommand),

    /// 1.2.22 R.5 — `inkhaven replace <pattern> <replacement>`.
    /// Project-wide find & replace: literal + whole-word by default
    /// (`--substring` opts out, `--regex` for a regex), optional
    /// `--ignore-case`.  `--dry-run` previews; `--yes` applies,
    /// snapshotting each touched paragraph first.  System books are
    /// excluded unless `--include-system`; `--book <name>` narrows to
    /// one.
    Replace {
        /// Text to find (or a regex with `--regex`).
        pattern: String,
        /// Replacement (regex captures `$1`… with `--regex`).
        replacement: String,
        /// Treat the pattern as a regular expression.
        #[arg(long)]
        regex: bool,
        /// Match substrings too (default: whole-word only).
        #[arg(long)]
        substring: bool,
        /// Case-insensitive match.
        #[arg(long)]
        ignore_case: bool,
        /// Limit to one book by name (default: all user books).
        #[arg(long)]
        book: Option<String>,
        /// Include system books (Notes / Facts / …) in the scan.
        #[arg(long)]
        include_system: bool,
        /// Preview matches without changing anything.
        #[arg(long)]
        dry_run: bool,
        /// Apply the replacements (required to write).
        #[arg(long)]
        yes: bool,
    },

    /// Launch the TUI editor (default if no subcommand is given).
    Tui,

    /// 1.2.10+ — launch the standalone TUI configuration
    /// editor for `<project>/inkhaven.hjson`.  Tree-pane
    /// hierarchy on the left, schema-aware widgets on the
    /// right.  Read-only walk-through in Phase 1; typed
    /// editing + save + versioned backups + rollback in
    /// subsequent phases.  See
    /// `Documentation/PROPOSALS/CONFIG_TUI.md`.
    ///
    /// The existing `Ctrl+B 0` in-app HJSON editor stays
    /// as the power-user fallback for raw text editing.
    Config,

    /// 1.2.11+ — launch the standalone TUI prompts
    /// editor for `<project>/prompts.hjson`.  Four-pane
    /// workbench: prompts list (left), prompt editor
    /// (centre, same chord set as the main inkhaven
    /// editor), AI response (right), AI prompt input
    /// (bottom).  Phase 1 ships read-only; editing +
    /// save + AI integration in subsequent phases.
    /// See `Documentation/PROPOSALS/PROMPTS_EDITOR_TUI.md`.
    PromptsEditor,

    /// 1.2.11+ — show-don't-tell tooling.  Currently
    /// hosts `bootstrap`, which uses the configured LLM
    /// to generate the four per-language word lists
    /// (linking_verbs / emotion_adjectives /
    /// manner_adverbs / cognition_verbs) for the
    /// show-don't-tell overlay.  Output is an HJSON
    /// snippet on stdout — never writes to your
    /// `inkhaven.hjson` automatically; review and paste
    /// what you like.  Pattern mirrors
    /// `doctor --filter-words-snippet`.
    #[command(subcommand, name = "show-dont-tell")]
    ShowDontTell(ShowDontTellCommand),

    /// 1.2.12+ Phase B — prompts tooling.  Currently
    /// hosts `bootstrap <lang>`, which uses the
    /// configured LLM to generate per-language
    /// variants of the seven inkhaven embedded
    /// prompts (`grammar-check`, `show-don't-tell`,
    /// `sentence-rhythm-rewrite`, `critique-edit`,
    /// `critique-changes`, `explain-diagnostic`,
    /// `timeline-health`).  Output is an HJSON
    /// snippet ready to paste under
    /// `prompts.hjson`; with `--update` it merges
    /// into the live file in place via the same
    /// `apply_in_place_edits` helper the SDT
    /// bootstrap uses.  See
    /// `Documentation/PROPOSALS/MULTILINGUAL_PROMPTS.md`.
    #[command(subcommand)]
    Prompts(PromptsCommand),

    /// invented-language tooling.
    /// Scaffolds the per-language sub-books inside
    /// the top-level `Language` system book.  See
    /// `Documentation/PROPOSALS/LANGUAGE_BOOK.md`
    /// for the full design (dictionary entry HJSON
    /// schema, grammar-rule schema, phonology,
    /// sample-text, AI translation flow).  Phase A
    /// ships `init` only; phases B-D add lexicon
    /// overlay, AI translation, export, doctor.
    #[command(subcommand)]
    Language(LanguageCommand),
    /// 1.2.14+ — `inkhaven thread <subcommand>`.
    /// Plot-thread management surface — add /
    /// list narrative arcs stored as HJSON-fronted
    /// paragraphs under the `Threads` system book.
    /// See `Documentation/PROPOSALS/1.2.14_PLAN.md`.
    #[command(subcommand)]
    Thread(ThreadCommand),
    /// `inkhaven template
    /// <subcommand>`.  Surfaces information about
    /// the project templates available to
    /// `inkhaven init --template <name>`.
    #[command(subcommand)]
    Template(TemplateCommand),
    /// `inkhaven comments
    /// <subcommand>`.  Headless manipulation of
    /// the per-paragraph sidecar comment files
    /// (`.comments.json`).  Mirrors the in-TUI
    /// `Ctrl+V Shift+C` panel.
    #[command(subcommand)]
    Comments(CommentsCommand),

    /// 1.2.18+ I.1.1 — `inkhaven gen-fixture
    /// <path>` (hidden).  Generates a deterministic
    /// 10K-paragraph synthetic project for the
    /// criterion bench harness.  See
    /// `Documentation/PROPOSALS/1.2.18_PLAN.md`.
    /// Hidden from `--help` because end-user projects
    /// should not run this by accident.
    #[command(hide = true, name = "gen-fixture")]
    GenFixture {
        /// Target directory.  Wiped + recreated; use
        /// `--force` to skip the confirmation prompt.
        path: PathBuf,
        #[arg(long, default_value_t = 5)]
        books: usize,
        #[arg(long, default_value_t = 20)]
        chapters: usize,
        #[arg(long, default_value_t = 100)]
        paragraphs: usize,
        #[arg(long, default_value_t = 450)]
        target_words: u32,
        #[arg(long, default_value_t = 0xC0FFEE_DEAD_BEEFu64)]
        seed: u64,
        #[arg(long)]
        force: bool,
    },

    /// 1.2.18+ I.1.3 — `inkhaven _bench-load`
    /// (hidden).  Opens the project with phase timers
    /// + reports per-phase millis on stdout.  The
    /// in-process bench hook the I.1.2.b plan
    /// anticipated; doubles as the I.1.3 profiling
    /// instrument (a true sampling flamegraph needs
    /// dtrace, which SIP blocks without sudo).  Pair
    /// with `INKHAVEN_PERF_TRACE=1` for the
    /// sub-phase store-open + hierarchy-load breakdown.
    #[command(hide = true, name = "_bench-load")]
    BenchLoad {
        /// Search query for the search-phase timing.
        #[arg(long, default_value = "the harbor")]
        query: String,
        /// Iterations to average flatten + search over.
        #[arg(long, default_value_t = 20)]
        iterations: usize,
    },

    /// 1.2.18+ I.1.7 — `inkhaven _bench-report`
    /// (hidden).  Compares two criterion output trees +
    /// emits a markdown/plain delta table + exits 2 on
    /// any regression past `--threshold`.  Drives the
    /// CI bench gate (`.github/workflows/bench.yml`).
    #[command(hide = true, name = "_bench-report")]
    BenchReport {
        /// Baseline criterion dir (restored from the
        /// main branch's last run).  When absent /
        /// missing, every bench is treated as new (no
        /// regression possible).
        #[arg(long)]
        baseline: Option<PathBuf>,
        /// Current-run criterion dir.  Defaults to
        /// `<target>/criterion`.
        #[arg(long)]
        current: Option<PathBuf>,
        /// Regression threshold as a fraction (0.20 =
        /// 20%).
        #[arg(long, default_value_t = 0.20)]
        threshold: f64,
        /// Emit GitHub-flavoured markdown (for a PR
        /// comment) instead of plain text.
        #[arg(long)]
        markdown: bool,
    },

    /// 1.2.17+ T.7 — `inkhaven tts <subcommand>`.
    /// Headless management of the Piper TTS stack:
    /// engine status, binary install/inspect, voice
    /// list/download/remove, catalog refresh, and
    /// cross-platform synthesis test.  Mirrors the
    /// in-TUI `Ctrl+B Shift+V` voice picker for
    /// scripts, CI gates, and remote-shell users.
    #[command(subcommand)]
    Tts(TtsCommand),

    /// `inkhaven recover <crash-report.hjson>` —
    /// pick up an inkhaven crash report and walk the
    /// rescued-buffer manifest, optionally applying
    /// each rescue back to its on-disk paragraph file
    /// after writing a `.pre-recover-<UTC>` rollback
    /// backup.  Default behaviour prompts y/N/diff
    /// per buffer; `--yes` bypasses the prompt and
    /// applies every rescue.  `--keep` leaves the
    /// report + rescue files in place; default moves
    /// them into `<project>/.inkhaven/recovered/`.
    Recover {
        /// Path to the `inkhaven-crash-<ts>.hjson`
        /// report written by the panic hook.
        report: PathBuf,
        /// Skip prompts; apply every rescue.
        #[arg(long)]
        yes: bool,
        /// Leave the report + rescue files in place
        /// after the walk.  Default moves them into
        /// `<project>/.inkhaven/recovered/`.
        #[arg(long)]
        keep: bool,
    },
}

/// sub-subcommands under
/// `inkhaven comments …`.
#[derive(Debug, Subcommand)]
pub enum CommentsCommand {
    /// Print every comment in the project (or
    /// filtered to a paragraph slug).  Default
    /// shows all; pass `--unresolved-only` to
    /// hide resolved comments.
    List {
        /// Limit to comments under this paragraph
        /// slug-path.
        #[arg(long)]
        paragraph: Option<String>,
        /// Hide resolved comments.
        #[arg(long)]
        unresolved_only: bool,
    },
    /// Mark a comment as resolved.  Identifies
    /// the comment by its UUID.
    Resolve {
        /// Comment UUID.
        id: String,
    },
    /// Re-open (un-resolve) a comment.
    Reopen {
        id: String,
    },
    /// Delete a comment.  Immediate; no undo.
    Delete {
        id: String,
    },
    /// Export every comment in the project as
    /// structured JSON.  Streams to stdout when
    /// `--output` is omitted.
    Export {
        #[arg(long, short = 'o')]
        output: Option<PathBuf>,
    },
}

/// sub-subcommands under
/// `inkhaven template …`.
#[derive(Debug, Subcommand)]
pub enum TemplateCommand {
    /// List every available project template with
    /// a one-line description.  Use the `name`
    /// column as the `--template <name>` value for
    /// `inkhaven init`.
    List,
}

/// Sub-subcommands under `inkhaven event …`.
#[derive(Debug, Subcommand)]
pub enum EventCommand {
    /// Create a new event under the named book's Timeline
    /// chapter (created lazily on first use).
    Add {
        /// Event title (free-form). Becomes the paragraph's
        /// display name + slug seed.
        title: String,
        /// Calendar-formatted start time. See
        /// `timeline.calendar` in HJSON for the syntax
        /// (defaults: sols `Sol N`; gregorian `Y.M.D`;
        /// custom `1A.3.15`).
        #[arg(long)]
        start: String,
        /// Calendar-formatted end time. Omit for an instant
        /// event.
        #[arg(long)]
        end: Option<String>,
        /// Precision override. When unset, inferred from the
        /// shape of `--start` (no day segment → month; no
        /// month → year; season name → season).
        #[arg(long)]
        precision: Option<String>,
        /// Track / POV / parallel-storyline label. Defaults
        /// to `timeline.default_track`.
        #[arg(long)]
        track: Option<String>,
        /// Book slug or title (case-insensitive). Required
        /// when the project holds more than one user book.
        #[arg(long)]
        book_name: Option<String>,
    },
    /// List events in chronological order.
    List {
        /// Filter to a single book.
        #[arg(long)]
        book_name: Option<String>,
        /// Track filter (case-insensitive exact match).
        #[arg(long)]
        track: Option<String>,
    },
    /// Show details for one event by slug-path.
    Show {
        /// Slug-path of the event paragraph.
        path: String,
    },
}

/// 1.2.12+ Phase B — sub-subcommands under
/// `inkhaven prompts …`.
#[derive(Debug, Subcommand)]
pub enum PromptsCommand {
    /// Generate per-language variants of inkhaven's
    /// seven embedded prompts using the configured
    /// LLM.  Emits an HJSON snippet on stdout (default)
    /// or, with `--update`, merges into
    /// `<project>/prompts.hjson` in place — versioned
    /// backup + atomic write + comment preservation
    /// via the shared `apply_in_place_edits` helper.
    /// Mirrors `inkhaven show-dont-tell bootstrap`.
    Bootstrap {
        /// Target language.  One of: english, russian,
        /// french, german, spanish.  Mapped to ISO 639-1
        /// (`en`/`ru`/`fr`/`de`/`es`) for the
        /// `language:` field on each generated prompt
        /// entry — that's the value the prompt resolver
        /// compares against.
        language: String,
        /// Optional genre / register hint folded into
        /// the prompt so the model picks vocabulary at
        /// the right reading level ("literary fiction",
        /// "thriller", "YA fantasy", …).
        #[arg(long)]
        genre: Option<String>,
        /// Override the default LLM provider for this
        /// invocation.  Same semantics as
        /// `inkhaven ai --provider`.
        #[arg(long)]
        provider: Option<String>,
        /// Apply the LLM-generated prompts **in place**
        /// to `prompts.hjson`, merging with any
        /// existing same-name entries (case-insensitive
        /// name match + `language` field match — only
        /// overwrites the exact `(name, language)`
        /// pair, leaves every other entry untouched).
        /// A versioned backup of the pre-patch file
        /// lands under `<project>/.config-backups/`
        /// first.  Without `--update`, prints the
        /// snippet to stdout and touches nothing.
        #[arg(long)]
        update: bool,
    },
}

/// 1.2.19+ C.3 — sub-subcommands under
/// `inkhaven continuity …`.
#[derive(Debug, Subcommand)]
pub enum ContinuityCommand {
    /// Run the AI fact-extraction pass over the
    /// manuscript, writing the continuity bible to
    /// `<project>/.inkhaven/continuity.json`.  Uses the
    /// configured LLM + a per-language prompt.
    Extract {
        /// LLM provider override (defaults to
        /// `llm.default`).
        #[arg(long)]
        provider: Option<String>,
    },
    /// Dump the extracted continuity bible — each
    /// character's facts, by attribute + chapter.
    List,
}

/// 1.2.19+ C.4 — sub-subcommands under
/// `inkhaven tension …`.
#[derive(Debug, Subcommand)]
pub enum TensionCommand {
    /// Run the AI pass that tags each chapter's
    /// introduced + resolved tensions into
    /// `<project>/.inkhaven/tensions.json`.
    Scan {
        /// LLM provider override (defaults to
        /// `llm.default`).
        #[arg(long)]
        provider: Option<String>,
    },
    /// Dump the tension ledger.
    List,
}

/// 1.2.21+ FF.2 — sub-subcommands under
/// `inkhaven facts …`.
#[derive(Debug, Subcommand)]
pub enum FactsCommand {
    /// Run the AI fact-check pass: check every chapter's
    /// prose against the Facts book (relevant facts
    /// retrieved per chapter via semantic search) and write
    /// contradictions to `<project>/.inkhaven/facts_scan.json`.
    Scan {
        /// LLM provider override (defaults to `llm.default`).
        #[arg(long)]
        provider: Option<String>,
        /// Emit the report as JSON (for CI gates).
        #[arg(long)]
        json: bool,
    },
    /// 1.3.8 — internal-consistency check: flag fact pairs that
    /// contradict each other *within* the Facts book (distinct from
    /// `scan`, which checks prose against facts). Writes
    /// `<project>/.inkhaven/facts_check.json`; surfaced in `inkhaven edit`.
    Check {
        #[arg(long)]
        provider: Option<String>,
        #[arg(long)]
        json: bool,
    },
    /// 1.3.8 — copy series-shared facts (a directory of plain-text fact
    /// files) into this project's Facts book. A hard snapshot of the shared
    /// canon, after which `scan` / fact-check see them as local facts.
    Import {
        /// The shared-facts directory (defaults to `facts.shared_path`).
        #[arg(long)]
        from: Option<String>,
        /// Actually write (otherwise prints what it would add).
        #[arg(long)]
        yes: bool,
    },
    /// Dump the last scan's findings (re-runs nothing).
    List {
        /// Emit the report as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Propose world-facts from the manuscript prose and
    /// (after an interactive y/N/a/q review) add the
    /// accepted ones to the Facts book.  Deduped against
    /// existing entries.  Solves the cold-start of an empty
    /// Facts book.
    Extract {
        /// LLM provider override (defaults to `llm.default`).
        #[arg(long)]
        provider: Option<String>,
        /// Accept every proposed fact without prompting.
        #[arg(long)]
        yes: bool,
        /// List the proposed facts without adding any.
        #[arg(long)]
        dry_run: bool,
    },
    /// Scaffold the starter category paragraphs (Climate,
    /// Geography, Seasons, Chronology, Culture, Rules) in
    /// the Facts book — fill-in-the-blanks for a fresh
    /// project.  Idempotent: existing categories are kept.
    /// `--genre` appends genre-specific categories
    /// (fantasy / scifi / mystery / historical).
    Init {
        /// Add the skeleton even if categories already exist.
        #[arg(long)]
        force: bool,
        /// Append genre-specific categories: general (default),
        /// fantasy, scifi, mystery, historical.
        #[arg(long)]
        genre: Option<String>,
    },
}

/// 1.3.0 PDF-1 — `inkhaven pdf …` page operations + metadata + outline
/// over an existing PDF (typically inkhaven's own `Ctrl+B B` output).
/// 1.3.2+ PLANNING-1 — `inkhaven plan …`: the Planning Board (story
/// structure).  `init` scaffolds a framework's beats in P0; `check`
/// (coverage + pacing) and `analyze` (AI) arrive in later phases.
#[derive(Debug, Subcommand)]
pub enum PlanCommand {
    /// Scaffold a story-structure framework's beats into the `Planning`
    /// system book.
    Init {
        /// `three_act` (default) | `save_the_cat` | `story_circle` |
        /// `hero_journey` | `seven_point`.
        #[arg(long)]
        framework: Option<String>,
    },
    /// Diagnose structure against a book: beat coverage (gaps), per-beat
    /// position drift, and per-act word-share pacing.  Deterministic — no
    /// AI.  Map a beat to a chapter by setting `mapped_chapter` in its
    /// Planning-book paragraph.
    Check {
        #[arg(long)]
        book_name: Option<String>,
        #[arg(long)]
        json: bool,
        /// Drift / pacing tolerance in percent (default 10).
        #[arg(long)]
        drift: Option<u32>,
    },
    /// AI structure analysis: over the book digest + the framework, map
    /// the beats to chapters and name the structural problems (the sag,
    /// missing beats).  Builds the digest if needed.
    Analyze {
        #[arg(long)]
        book_name: Option<String>,
        #[arg(long)]
        provider: Option<String>,
    },
    /// Map a beat to a chapter (set its `mapped_chapter`), optionally
    /// linking threads + setting status.  `<beat>` is the beat name or
    /// slug; `<chapter>` is a chapter slug (see `plan check`).
    Map {
        beat: String,
        chapter: String,
        /// Comma-separated thread slugs to link.
        #[arg(long, value_delimiter = ',')]
        threads: Option<Vec<String>>,
        /// `planned` | `drafted` | `done`.
        #[arg(long)]
        status: Option<String>,
        #[arg(long)]
        book_name: Option<String>,
    },
    /// Clear a beat's `mapped_chapter` (turn it back into an open gap).
    Unmap { beat: String },
    /// Plan-first.  `--premise "<logline>"` expands each beat into an
    /// intention (AI); `--chapters` materializes a chapter shell per beat
    /// under the manuscript book (opt-in, refuses to clobber an existing
    /// book) and back-links each beat.  Pass either or both.  Run `plan
    /// init` first.
    Scaffold {
        /// The premise / logline to plan around (fills beat intentions).
        #[arg(long)]
        premise: Option<String>,
        /// Create a chapter shell per beat under the manuscript book.
        #[arg(long)]
        chapters: bool,
        #[arg(long)]
        book_name: Option<String>,
        #[arg(long)]
        framework: Option<String>,
        #[arg(long)]
        provider: Option<String>,
    },
    /// Scene cards (1.3.4) — a finer grain than beats: each scene's
    /// goal / conflict / disaster, with a weak-scene (no-turn) check.
    Scene {
        #[command(subcommand)]
        cmd: PlanSceneCommand,
    },
    /// Sequel cards (1.3.5) — the reactive counterpart to the proactive
    /// scene: reaction / dilemma / decision. A sequel that reaches a
    /// dilemma but never decides stalls the story.
    Sequel {
        #[command(subcommand)]
        cmd: PlanSequelCommand,
    },
    /// Tension second opinion (1.3.5) — an AI intensity reading to compare
    /// against the deterministic curve.
    Tension {
        #[command(subcommand)]
        cmd: PlanTensionCommand,
    },
}

/// `inkhaven plan tension …` — the AI intensity "second opinion".
#[derive(Debug, Subcommand)]
pub enum PlanTensionCommand {
    /// Rate every chapter's dramatic intensity (0–100) with the LLM and
    /// cache it. The `Ctrl+V Shift+K` outline + `plan check` then show it as
    /// a third line beside expected (framework) and actual (obligations).
    Rate {
        #[arg(long)]
        book_name: Option<String>,
        #[arg(long)]
        provider: Option<String>,
        /// Re-rate every chapter even if the cache is still current.
        #[arg(long)]
        refresh: bool,
    },
}

/// `inkhaven plan sequel …` — manage the reactive (reaction/dilemma/
/// decision) cards. They share the Planning book's `Scenes` chapter with
/// scene cards, tagged by kind.
#[derive(Debug, Subcommand)]
pub enum PlanSequelCommand {
    /// Add a sequel card under a chapter.
    Add {
        title: String,
        #[arg(long)]
        chapter: String,
        /// The POV character's emotional response to the prior disaster.
        #[arg(long)]
        reaction: Option<String>,
        /// The bad-options bind it forces.
        #[arg(long)]
        dilemma: Option<String>,
        /// The choice that launches the next goal.
        #[arg(long)]
        decision: Option<String>,
    },
    /// List sequel cards (grouped by chapter) with the no-decision flag.
    List,
    /// Update fields on an existing sequel (matched by title).
    Set {
        title: String,
        #[arg(long)]
        chapter: Option<String>,
        #[arg(long)]
        reaction: Option<String>,
        #[arg(long)]
        dilemma: Option<String>,
        #[arg(long)]
        decision: Option<String>,
        #[arg(long)]
        status: Option<String>,
    },
    /// Remove a sequel card (matched by title).
    Remove { title: String },
}

/// `inkhaven plan scene …` — manage the Planning book's scene cards.
#[derive(Debug, Subcommand)]
pub enum PlanSceneCommand {
    /// Add a scene card under a chapter.
    Add {
        /// Scene title (its identifier within the Planning book).
        title: String,
        /// Chapter slug the scene belongs to.
        #[arg(long)]
        chapter: String,
        /// What the POV character wants.
        #[arg(long)]
        goal: Option<String>,
        /// What stands in the way.
        #[arg(long)]
        conflict: Option<String>,
        /// The turn — how the scene ends worse / changed.
        #[arg(long)]
        disaster: Option<String>,
    },
    /// List scene cards (grouped by chapter) with weak-scene flags.
    List,
    /// Update fields on an existing scene (matched by title).
    Set {
        title: String,
        #[arg(long)]
        chapter: Option<String>,
        #[arg(long)]
        goal: Option<String>,
        #[arg(long)]
        conflict: Option<String>,
        #[arg(long)]
        disaster: Option<String>,
        #[arg(long)]
        status: Option<String>,
    },
    /// Remove a scene card (matched by title).
    Remove { title: String },
    /// AI-scaffold a scene card from a chapter's prose (goal / conflict /
    /// disaster). Pass `--chapter <slug>` for one, or `--all` for every
    /// chapter without a card yet.
    Scaffold {
        #[arg(long)]
        chapter: Option<String>,
        /// Scaffold every chapter that has no card yet.
        #[arg(long)]
        all: bool,
        #[arg(long)]
        book_name: Option<String>,
        #[arg(long)]
        provider: Option<String>,
    },
}

/// 1.3.1+ SUBMISSION-1 P3 — `inkhaven submission …` (singular): the AI
/// package-build side.  `digest` lands in P3.1; the query / synopsis /
/// comps / logline generators arrive in P3.2.
#[derive(Debug, Subcommand)]
pub enum SubmissionCommand {
    /// Build (or show the cached) book digest — the compact whole-book
    /// context the package generators consume: title / author / length /
    /// chapter one-line summaries + the Characters and Threads books.
    /// Cached in `.inkhaven/digest-<slug>.json`, rebuilt when the
    /// manuscript's structure changes or with `--refresh`.
    Digest {
        #[arg(long)]
        book_name: Option<String>,
        /// Rebuild even if the cached digest is still valid.
        #[arg(long)]
        refresh: bool,
        /// Override the LLM provider for the summary pass.
        #[arg(long)]
        provider: Option<String>,
    },
    /// Draft a query letter from the digest into the `Submissions` book.
    Query {
        #[arg(long)]
        book_name: Option<String>,
        #[arg(long)]
        provider: Option<String>,
    },
    /// Draft a synopsis (one page; `--long` for 2–3 pages). Spoils the
    /// ending by design.
    Synopsis {
        #[arg(long)]
        book_name: Option<String>,
        #[arg(long)]
        long: bool,
        #[arg(long)]
        provider: Option<String>,
    },
    /// Suggest comp titles (general-knowledge suggestions, not market
    /// data).
    Comps {
        #[arg(long)]
        book_name: Option<String>,
        #[arg(long)]
        provider: Option<String>,
    },
    /// Draft a logline + elevator pitch.
    Logline {
        #[arg(long)]
        book_name: Option<String>,
        #[arg(long)]
        provider: Option<String>,
    },
}

/// 1.3.1+ SUBMISSION-1 — `inkhaven submissions …` sub-subcommands.
#[derive(Debug, Subcommand)]
pub enum SubmissionsCommand {
    /// Record a new submission.
    Add {
        /// Agency / publication / contest.
        #[arg(long)]
        market: String,
        #[arg(long)]
        agent: Option<String>,
        /// Paragraph slug of the draft used (in the `Submissions` book).
        #[arg(long)]
        draft: Option<String>,
        /// `drafting` (default) | `sent` | `rejected` | `offer` |
        /// `withdrawn`.
        #[arg(long)]
        status: Option<String>,
        /// ISO `YYYY-MM-DD` (defaults to today when `--status sent`).
        #[arg(long)]
        date_sent: Option<String>,
        /// Next-action date (ISO `YYYY-MM-DD`).
        #[arg(long)]
        next: Option<String>,
        #[arg(long)]
        notes: Option<String>,
    },
    /// List the log (optionally `--json`, filtered by `--status` or just
    /// the still-`--open` ones).
    List {
        #[arg(long)]
        json: bool,
        #[arg(long)]
        status: Option<String>,
        /// Only submissions still awaiting a response.
        #[arg(long)]
        open: bool,
    },
    /// Move a record to a new status (stamps a response date for
    /// `rejected` / `offer`).
    Status {
        id: String,
        status: String,
        #[arg(long)]
        response_date: Option<String>,
    },
    /// Append a timestamped note to a submission's event trail
    /// (e.g. "got a call", "requested edits", "moving to round two").
    AddNote {
        id: String,
        /// The note text.
        text: String,
    },
    /// Remove a record.
    Remove { id: String },
}

/// Mutating ops write a `<stem>-<op>.pdf` sibling unless `--out` is
/// given; writes are atomic.  Imposition / cover / barcode / preflight
/// arrive in later phases.
#[derive(Debug, Subcommand)]
pub enum PdfCommand {
    /// Print page count, page-1 size, source, title/author, outline size.
    Info {
        input: std::path::PathBuf,
    },
    /// Impose into print-ready signatures using a named `imposition:`
    /// profile (binding style / sheet size / creep / marks).  The
    /// profile comes through the config cascade (project + global);
    /// `default` and `chapbook` are built in.
    Impose {
        input: std::path::PathBuf,
        /// Imposition profile name.
        #[arg(long, default_value = "default")]
        config: String,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
        /// Preview the plan (signatures / sheets / creep / first-sheet
        /// schematic) without imposing.
        #[arg(long)]
        dry_run: bool,
    },
    /// Keep only the given pages (e.g. `--pages 2-4,7`).
    Extract {
        input: std::path::PathBuf,
        #[arg(long)]
        pages: String,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Delete the given pages.
    Delete {
        input: std::path::PathBuf,
        #[arg(long)]
        pages: String,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Rotate the given pages by 90 / 180 / 270 degrees (added to any
    /// existing rotation).
    Rotate {
        input: std::path::PathBuf,
        #[arg(long)]
        pages: String,
        #[arg(long)]
        degrees: i64,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Reorder pages by a comma-separated 1-based permutation
    /// (e.g. `--mapping 3,1,2`).
    Reorder {
        input: std::path::PathBuf,
        #[arg(long)]
        mapping: String,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Split into pieces by `--every <n>` pages or `--at <p,p,…>`
    /// (split before those 1-based pages).
    Split {
        input: std::path::PathBuf,
        #[arg(long)]
        every: Option<usize>,
        #[arg(long)]
        at: Option<String>,
        #[arg(long)]
        out_dir: Option<std::path::PathBuf>,
    },
    /// Concatenate two or more PDFs into `--out`.
    Merge {
        inputs: Vec<std::path::PathBuf>,
        #[arg(long)]
        out: std::path::PathBuf,
    },
    /// Read (no flags), set (`--title`/`--author`/`--subject`/
    /// `--keywords`), or `--strip` the document metadata.
    Metadata {
        input: std::path::PathBuf,
        #[arg(long)]
        strip: bool,
        #[arg(long)]
        title: Option<String>,
        #[arg(long)]
        author: Option<String>,
        #[arg(long)]
        subject: Option<String>,
        /// Comma-separated keywords.
        #[arg(long)]
        keywords: Option<String>,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// List the document outline (bookmarks).
    Outline {
        input: std::path::PathBuf,
    },
    /// Check a PDF is print-ready (RFC §8.6): effective image DPI, font
    /// embedding, page-size consistency, blank/colour pages.  Profile
    /// (`--profile hand_binding|print_shop|strict`) sets the DPI target;
    /// `--dpi` overrides it.
    Preflight {
        input: std::path::PathBuf,
        #[arg(long, default_value = "hand_binding")]
        profile: String,
        #[arg(long)]
        dpi: Option<u32>,
    },
    /// Generate a standalone EAN-13 ISBN barcode PDF (RFC §8.5).
    Barcode {
        /// 12- or 13-digit ISBN (hyphens/spaces ignored).
        isbn: String,
        #[arg(long)]
        out: std::path::PathBuf,
        /// Bar height in mm (EAN-13 nominal ≈ 22.85).
        #[arg(long)]
        height_mm: Option<f32>,
        /// X-dimension (single module width) in mm (SC2 ≈ 0.33).
        #[arg(long)]
        module_mm: Option<f32>,
        /// Omit the human-readable digits under the bars.
        #[arg(long)]
        no_text: bool,
    },
    /// Generate a full cover-and-spine PDF (RFC §8.4): one landscape page
    /// `[bleed | back | spine | front | bleed]`.  Trim/bleed/stocks come
    /// from the `cover:` config; the spine width is computed from
    /// `--pages` + stocks (or forced with `--spine-mm`).
    Cover {
        #[arg(long)]
        out: std::path::PathBuf,
        /// Interior page count (drives the computed spine width).
        #[arg(long)]
        pages: usize,
        #[arg(long)]
        title: Option<String>,
        #[arg(long)]
        author: Option<String>,
        /// Back-cover blurb (top-left of the back panel).
        #[arg(long)]
        back: Option<String>,
        /// Front-cover art (any format the `image` crate reads).
        #[arg(long)]
        image: Option<std::path::PathBuf>,
        /// How the front art fills its region: `cover` (default, aspect-
        /// preserving full-bleed crop), `fit`, or `stretch`.
        #[arg(long)]
        fit: Option<String>,
        /// ISBN — renders an EAN-13 barcode on the back panel.
        #[arg(long)]
        isbn: Option<String>,
        /// Override the computed spine width (mm).
        #[arg(long)]
        spine_mm: Option<f32>,
        /// Override the config trim width (mm).
        #[arg(long)]
        width_mm: Option<f32>,
        /// Override the config trim height (mm).
        #[arg(long)]
        height_mm: Option<f32>,
    },
    /// Convert to grayscale (RFC §8.7): neutralize content-stream colour
    /// + convert DeviceRGB/CMYK images to DeviceGray, including DCTDecode
    /// (JPEG) photos (re-embedded as grayscale JPEGs).  Best-effort —
    /// CMYK JPEGs / exotic colour spaces are left as-is.
    Grayscale {
        input: std::path::PathBuf,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Losslessly slim a PDF: prune orphan objects + Flate-compress every
    /// uncompressed stream.
    Optimize {
        input: std::path::PathBuf,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Stamp text and/or an image onto a page range (RFC §8.7).
    Watermark {
        input: std::path::PathBuf,
        /// Stamp text (e.g. `DRAFT`).
        #[arg(long)]
        text: Option<String>,
        /// Stamp image (logo); any format the `image` crate reads.
        #[arg(long)]
        image: Option<std::path::PathBuf>,
        /// Constant alpha 0..1 (default 0.18).
        #[arg(long)]
        opacity: Option<f32>,
        /// Text rotation in degrees (default 45).
        #[arg(long)]
        rotation: Option<f32>,
        /// Font size in pt (default 72).
        #[arg(long)]
        size: Option<f32>,
        /// Anchor: `center` | `top-left` | `top-right` | `bottom-left` |
        /// `bottom-right` (default center).
        #[arg(long, default_value = "center")]
        position: String,
        /// Limit to a page range (e.g. `1` or `2-4,7`); default all.
        #[arg(long)]
        pages: Option<String>,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Quick-proof subset: keep `--count` evenly-spaced pages (first +
    /// last always included).
    Sample {
        input: std::path::PathBuf,
        #[arg(long, default_value_t = 8)]
        count: usize,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
}

/// 1.2.17+ T.7 — sub-subcommands under
/// `inkhaven tts …`.  Mirrors the in-TUI
/// `Ctrl+B Shift+V` voice picker + adds engine
/// + binary diagnostics + cross-platform synth
/// testing.
#[derive(Debug, Subcommand)]
pub enum TtsCommand {
    /// `inkhaven tts engine` — print which TTS
    /// backend is active for the project (System
    /// `say` vs. Piper) and why.  Honours
    /// `tts.engine` (`auto` | `piper` | `system`).
    Engine,
    /// `inkhaven tts binary <action>` — Piper
    /// binary management.
    #[command(subcommand)]
    Binary(TtsBinarySubcommand),
    /// `inkhaven tts voice <action>` — voice
    /// catalog browsing + per-voice download /
    /// remove.
    #[command(subcommand)]
    Voice(TtsVoiceSubcommand),
    /// `inkhaven tts catalog <action>` — voice
    /// catalog cache management.
    #[command(subcommand)]
    Catalog(TtsCatalogSubcommand),
    /// `inkhaven tts test "<phrase>" [--voice
    /// <name>]` — cross-platform synthesis test
    /// routed through `TtsEngine::resolve`.
    /// Synthesises to a temp WAV + plays via the
    /// platform default (or `tts.play_command`).
    /// Reports the active backend + binary path
    /// + voice path + bytes-out.  Exits 0 on
    /// success, non-zero on synth or playback
    /// failure.
    Test {
        /// Phrase to speak.  Required.
        phrase: String,
        /// Override `editor.tts.voice` for this
        /// invocation only.  Useful for A/B-ing
        /// voices without editing HJSON.
        #[arg(long)]
        voice: Option<String>,
        /// Synthesise to a file instead of
        /// playing.  Suppresses the playback step.
        #[arg(long, value_name = "PATH")]
        output: Option<PathBuf>,
    },
}

#[derive(Debug, Subcommand)]
pub enum TtsBinarySubcommand {
    /// Print where the Piper binary is on disk
    /// (or "not installed"), plus the resolved
    /// platform identifier + cache root.
    Status,
    /// Explicitly download the platform-
    /// appropriate Piper binary into the user
    /// cache.  Idempotent — re-downloads if the
    /// existing binary is corrupt or missing.
    Download,
}

#[derive(Debug, Subcommand)]
pub enum TtsVoiceSubcommand {
    /// Print every voice in the catalog with a
    /// downloaded / available chip + size.  Falls
    /// back to "voices on disk only" when the
    /// catalog can't be loaded.
    List {
        /// Filter to voices whose canonical key or
        /// language code contains <NEEDLE>.  Case-
        /// insensitive.
        #[arg(long)]
        filter: Option<String>,
        /// Show only voices that are already
        /// downloaded into the project.
        #[arg(long)]
        downloaded: bool,
    },
    /// Download a specific voice by canonical key
    /// (e.g. `en_US-lessac-medium`) or alias.
    /// Atomic install via `crate::io_atomic`;
    /// .gitignore updated per `tts.auto_gitignore`.
    Download {
        /// Voice key or alias.
        name: String,
    },
    /// Delete a downloaded voice + drop it from
    /// the LRU index.  Safe — the catalog itself
    /// is untouched, so the voice can be re-
    /// downloaded.
    Remove {
        /// Voice key as stored on disk.
        name: String,
    },
}

#[derive(Debug, Subcommand)]
pub enum TtsCatalogSubcommand {
    /// Force a catalog refresh — deletes the
    /// cached `voices.json` so the next operation
    /// fetches from `tts.catalog_url`.
    Refresh,
}

/// sub-subcommands under
/// `inkhaven language …`.
#[derive(Debug, Subcommand)]
pub enum LanguageCommand {
    /// Scaffold a new language sub-book under the
    /// top-level `Language` system book.  Creates
    /// the per-language `<Name>` book plus the five
    /// standard chapters (`Meta`, `Dictionary`,
    /// `Grammar`, `Phonology`, `Sample texts`) and
    /// seeds `Meta/overview.typ` with an empty
    /// HJSON config the author fills in.  No
    /// alphabet subchapters are created yet — they
    /// auto-spawn on the first dictionary entry
    /// once `add-word` lands in Phase B.
    Init {
        /// Display name for the language.  Becomes
        /// the per-language book title — `Quenya`,
        /// `Drow`, `Klingon`, etc.  Title-case
        /// recommended; the slug is auto-derived.
        name: String,
    },
    /// add a dictionary entry to
    /// a language's `Dictionary` chapter.  Auto-
    /// creates the alphabet subchapter from the
    /// language's `Meta/overview.alphabet` field
    /// (or A-Z fallback) if it doesn't yet exist.
    /// Seeds the entry paragraph with the four
    /// core HJSON fields (`word`, `type`,
    /// `translation`, `example`) — author edits
    /// to add optional fields (`pronunciation`,
    /// `etymology`, `related`, `inflection`,
    /// `notes`).  Rejects duplicate words under
    /// the same language.
    AddWord {
        /// Target language name (case-insensitive
        /// match against existing Language sub-book
        /// titles).
        language: String,
        /// The word being defined.  Title-case as
        /// the author prefers; the slug is
        /// auto-derived.  Required UNLESS --import
        /// is set, in which case this positional is
        /// ignored.
        word: Option<String>,
        /// Part of speech.  Free-form string; the
        /// proposal §3 suggests `noun | verb |
        /// adjective | adverb | pronoun |
        /// preposition | conjunction |
        /// interjection | particle` but the field
        /// is open so the author can use language-
        /// specific categories.  Required unless
        /// --import is set.
        #[arg(long, short = 't')]
        r#type: Option<String>,
        /// Translation into the project's working
        /// language.  Required unless --import is
        /// set.
        #[arg(long)]
        translation: Option<String>,
        /// Optional canonical sample sentence the
        /// author wants frozen into the entry.
        #[arg(long)]
        example: Option<String>,
        /// bulk-import a CSV
        /// dictionary.  When set, the positional
        /// <word> + the --type / --translation /
        /// --example flags are ignored; every row
        /// of the CSV becomes an entry.
        ///
        /// CSV format: header row drives column
        /// mapping (any subset / order accepted).
        /// Required columns: `word`, `type`,
        /// `translation`.  Optional: `example`,
        /// `pronunciation`, `etymology`, `related`
        /// (`;`-separated), `inflection`
        /// (`;`-separated `key=value` pairs),
        /// `examples` (`|`-separated additional
        /// sentences), `register`, `era`, `notes`.
        /// Comment rows: `word` starting with `#`.
        /// Empty `word` rows: skipped silently.
        /// Duplicate words: skipped with warning.
        /// Tally printed at end.
        #[arg(long, value_name = "PATH")]
        import: Option<PathBuf>,
        /// when used with --import,
        /// WIPE the language's existing Dictionary
        /// chapter (every bucket subchapter + every
        /// entry paragraph) before importing the CSV.
        /// The Dictionary chapter itself is preserved
        /// — only its contents are cleared.  Without
        /// --new, existing entries are kept and the
        /// import is "update / add" semantics (duplicate
        /// words skipped, new rows added).
        #[arg(long, requires = "import")]
        new: bool,
        /// skip the pre-flight
        /// alphabet + phonology validation that
        /// normally aborts an import when any word
        /// uses characters outside the language's
        /// declared alphabet OR uses phonemes
        /// outside the declared phoneme inventories.
        /// Use when intentionally importing words
        /// that exceed the current Meta/overview
        /// declaration (e.g. you're seeding the
        /// alphabet from the CSV itself).
        #[arg(long, requires = "import")]
        force: bool,
    },
    /// health report for a language
    /// sub-book.  Counts dictionary entries, entries
    /// with examples, entries with inflection
    /// paradigms, grammar / phonology rule counts,
    /// sample-text count, and (when the project has
    /// authored prose) the manuscript words that
    /// appear as translations in the dictionary versus
    /// the working-language words in the manuscript
    /// that have no dictionary coverage.  Exit code
    /// 0 always — the report is informational, not a
    /// pass/fail gate.  See the proposal §13.
    Doctor {
        /// Language to inspect (case-insensitive
        /// match against existing Language sub-book
        /// titles).
        language: String,
        /// Emit the report as structured JSON instead
        /// of the human-readable text format.  Useful
        /// for CI gates and shell pipelines that want
        /// to grep for `coverage.with_example_pct <
        /// 80` etc.
        #[arg(long)]
        json: bool,
    },
    /// list every defined
    /// language with summary counts (dictionary
    /// entries, grammar / phonology rules, sample
    /// texts).  Companion to `inkhaven language
    /// doctor` for a quick at-a-glance overview of
    /// every language in the project.
    List,
    /// remove a dictionary entry
    /// from a language.  Mirror of `add-word`:
    /// resolves the language sub-book by case-
    /// insensitive title; finds the Dictionary
    /// chapter + bucket subchapter (derived from the
    /// word's first character); deletes the entry
    /// paragraph.  Errors when the entry doesn't
    /// exist rather than silently no-op-ing.
    RemoveWord {
        /// Target language name.
        language: String,
        /// The word to remove (case-insensitive
        /// title match).
        word: String,
    },
    /// 1.2.16+ Phase P.5 — define-or-edit a
    /// grammar or phonology rule in `$EDITOR`.
    /// Opens the rule's HJSON template in the
    /// user's `$EDITOR` (or `vi` if unset), then
    /// — on save — writes the resulting body
    /// back into a new or existing rule paragraph
    /// under the chosen category.  Pairs with the
    /// `--format grammar` exporter.
    DefineRule {
        /// Target language name (case-insensitive).
        language: String,
        /// Unique rule identifier (kebab-case
        /// recommended) — used as the paragraph
        /// slug and the `rule_id` field in the
        /// HJSON body.
        rule_id: String,
        /// Which chapter the rule lives under.
        /// `grammar` or `phonology`.
        #[arg(long, default_value = "grammar")]
        category: String,
    },
    /// export a language's content
    /// to a portable artefact.  See the proposal §12.
    /// Three formats land in Phase D; the remaining
    /// two (grammar reference + phrasebook) are
    /// Phase D.2.
    Export {
        /// Language to export (case-insensitive
        /// match against existing Language sub-book
        /// titles).
        language: String,
        /// Output format.  `json` is structured data
        /// for downstream tooling; `anki` is a CSV
        /// flash-card deck; `dictionary-twocol` is a
        /// printable two-column Typst dictionary.
        #[arg(long, short = 'f', default_value = "json")]
        format: LanguageExportFormat,
        /// Output path.  Defaults to stdout when
        /// omitted (json + anki only — typst always
        /// needs a path because the renderer doesn't
        /// stream).
        #[arg(long, short = 'o')]
        output: Option<PathBuf>,
    },
}

/// output format selector for
/// `inkhaven language export`.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum LanguageExportFormat {
    /// Full structured dump — overview, dictionary,
    /// grammar, phonology, sample-text content.
    Json,
    /// CSV deck importable by Anki / SuperMemo /
    /// Mochi.  Columns: `word`, `translation`,
    /// `type`, `example`, `inflection`.
    Anki,
    /// Two-column printable Typst dictionary.
    /// Alphabet headers between sections; entries
    /// formatted as: bold headword + POS italic +
    /// translation + examples indented.
    DictionaryTwocol,
    /// 1.2.16+ Phase P.5 — round-trip-compatible
    /// CSV that the `--import` path can re-ingest.
    /// 12-column format matching the dictionary
    /// importer; closes the import/export loop.
    Csv,
    /// 1.2.16+ Phase P.5 — typst-rendered grammar
    /// reference.  TOC + chapter per rule
    /// category (case marking, verb conjugation,
    /// etc.) + examples table + cross-references.
    /// Always needs `--output <path.typ>`.
    Grammar,
    /// 1.2.16+ Phase P.5 — typst-rendered
    /// phrasebook from the Sample-texts chapter.
    /// Two-column layout: working-language gloss
    /// on the left, invented-language sample on
    /// the right.  Always needs `--output
    /// <path.typ>`.
    Phrasebook,
}

/// output format selector for
/// `inkhaven thread export`.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ThreadExportFormat {
    /// Full structured dump.
    Json,
    /// Flat CSV with paradigm fields collapsed
    /// (characters / places / artefacts joined by
    /// `;`).
    Csv,
    /// Printable markdown summary — one section
    /// per thread with arc-shape + connections +
    /// notes.
    Markdown,
}

/// 1.2.14+ — sub-subcommands under
/// `inkhaven thread …`.  Manages plot-thread
/// paragraphs under the `Threads` system book.
/// See `Documentation/PROPOSALS/1.2.14_PLAN.md`.
#[derive(Debug, Subcommand)]
pub enum ThreadCommand {
    /// print a health report
    /// for every thread under the `Threads` system
    /// book.  Same shape as
    /// `inkhaven language doctor`: status
    /// distribution, weight distribution, link
    /// coverage statistics, blind-spot detector
    /// passes (dormant threads, payoff-marked-but-
    /// unfired, status-vs-evidence mismatches).
    /// Exit code 0 always — informational, not a
    /// pass/fail gate.  Add `--json` for CI-
    /// friendly structured output.
    Doctor {
        /// Emit the report as structured JSON
        /// instead of the human-readable text.
        #[arg(long)]
        json: bool,
    },
    /// export every thread's
    /// data to a portable artefact.  See
    /// `Documentation/PROPOSALS/1.2.14_PLAN.md`
    /// §3 for the field shape.
    Export {
        /// Output format.  `json` is structured
        /// data for downstream tooling; `csv` is
        /// a flat table (paradigm fields
        /// flattened to `key=value` pairs);
        /// `markdown` is a printable summary
        /// document.
        #[arg(long, short = 'f', default_value = "json")]
        format: ThreadExportFormat,
        /// Output path.  Defaults to stdout when
        /// omitted.
        #[arg(long, short = 'o')]
        output: Option<PathBuf>,
    },
    /// Add a new thread paragraph under the
    /// `Threads` system book.  Seeds the body
    /// with the full commented HJSON template;
    /// the author opens the paragraph to fill in
    /// arc shape, character / place links,
    /// tension, etc.
    Add {
        /// Thread title — becomes the paragraph
        /// slug + lemma.  Free-form; the
        /// underlying slug is auto-derived.
        name: String,
        /// Optional display title for the card
        /// renderer.  Falls back to `name` when
        /// not set.
        #[arg(long)]
        title: Option<String>,
        /// Arc status — `setup` | `develop` |
        /// `payoff` | `resolved` | `abandoned`.
        /// Default `setup`.
        #[arg(long, default_value = "setup")]
        status: String,
        /// Weight — `major` | `subplot` |
        /// `runner` | `bridge`.  Default `major`.
        #[arg(long, default_value = "major")]
        weight: String,
    },
    /// List every thread paragraph under the
    /// `Threads` system book with summary
    /// columns (status / weight / tension /
    /// character + place link counts).
    List {
        /// Filter to threads with this status
        /// (case-insensitive).  Omit to show all.
        #[arg(long)]
        status: Option<String>,
        /// Filter to threads with this weight
        /// (case-insensitive).  Omit to show all.
        #[arg(long)]
        weight: Option<String>,
    },
}

/// 1.2.11+ — sub-subcommands under
/// `inkhaven show-dont-tell …`.
#[derive(Debug, Subcommand)]
pub enum ShowDontTellCommand {
    /// Generate per-language word lists for the
    /// show-don't-tell overlay using the configured
    /// LLM.  Emits an HJSON snippet on stdout — never
    /// touches your `inkhaven.hjson`; review and paste
    /// what you like (same shape as
    /// `doctor --filter-words-snippet`).  The four
    /// fields produced match the
    /// `editor.style_warnings.show_dont_tell.<lang>_*`
    /// stanza: `linking_verbs`, `emotion_adjectives`,
    /// `manner_adverbs`, `cognition_verbs`.  Optional
    /// `--genre` hint biases the vocabulary toward a
    /// register (e.g. "literary fiction", "thriller",
    /// "YA fantasy") — useful when the built-in defaults
    /// sit at the wrong reading level for your corpus.
    Bootstrap {
        /// Target language.  One of: english, russian,
        /// french, german, spanish.  Other values are
        /// passed through verbatim — the LLM will try,
        /// but per-language stop-word + stemmer plumbing
        /// only ships for the five above.
        language: String,
        /// Optional genre / register hint.  Folded into
        /// the prompt so the model picks vocabulary at
        /// the right reading level.
        #[arg(long)]
        genre: Option<String>,
        /// Override the default LLM provider for this
        /// invocation.  Same semantics as `inkhaven ai
        /// --provider` (no short alias here because
        /// `-p` is reserved by the global
        /// `--project`).
        #[arg(long)]
        provider: Option<String>,
        /// 1.2.11+ — apply the LLM-discovered lists
        /// **in place** to `inkhaven.hjson`, merging
        /// with any existing per-language entries
        /// (union, case-insensitive dedup, existing
        /// entries first then new arrivals).  A
        /// versioned backup of the pre-patch file
        /// lands under `<project>/.config-backups/`
        /// before the rewrite, so rolling back is a
        /// single `cp`.  Default (without `--update`)
        /// stays as today: print the HJSON snippet to
        /// stdout and touch nothing.  The two modes
        /// are mutually compatible — `--update` also
        /// prints the merged snippet to stdout so the
        /// user can see what landed.
        #[arg(long)]
        update: bool,
    },
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum CliNodeKind {
    Book,
    Chapter,
    Subchapter,
    Paragraph,
    /// Bund script — a `.bund` file `bund.eval`'d into Adam at
    /// project open. Default home is the `Scripts` system book,
    /// but Scripts can also live inside any user Book.
    Script,
}

impl From<CliNodeKind> for NodeKind {
    fn from(k: CliNodeKind) -> Self {
        match k {
            CliNodeKind::Book => NodeKind::Book,
            CliNodeKind::Chapter => NodeKind::Chapter,
            CliNodeKind::Subchapter => NodeKind::Subchapter,
            CliNodeKind::Paragraph => NodeKind::Paragraph,
            CliNodeKind::Script => NodeKind::Script,
        }
    }
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ExportFormat {
    /// Concatenated `.typ` source.
    Typst,
    /// PDF via the `typst` CLI (must be on PATH).
    Pdf,
    /// Markdown via the in-process typst→markdown converter
    /// (`src/export/markdown.rs`).
    Markdown,
    /// LaTeX via the `tylax` crate. No external `pdflatex` needed
    /// for emit — but the user wants `pdflatex` / `xelatex` if they
    /// later compile the result.
    Tex,
    /// EPUB3 zip — markdown intermediate, written via the bundled
    /// `zip` crate.
    Epub,
}

/// 1.2.12+ — output formats for
/// `inkhaven export-concordance`.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ConcordanceExportFormat {
    /// CSV — one row per stem: headword, stem, count,
    /// variants (comma-separated), and the slug-path
    /// of each sample (semicolon-separated).  Drops
    /// the KWIC text since spreadsheet tools handle
    /// quotes poorly.  Easiest for pivoting.
    Csv,
    /// JSON — full structured form including KWIC
    /// snippets, line numbers, variants list.
    /// Use for downstream tooling.
    Json,
}

/// 1.2.8+ — output formats for `inkhaven export-timeline`.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum TimelineExportFormat {
    /// Typst-source listing — chronological events per track,
    /// calendar-formatted, ready to `#include` in a longer
    /// document. Compile through `typst compile <file>` to
    /// get PDF / SVG / PNG via typst's own pipeline.
    Typst,
    /// Vector swim-lane render — one row per track, events
    /// positioned by start tick (instant = circle, duration
    /// = bar), date axis at the top. Self-contained SVG;
    /// drop directly into an HTML page or open in any
    /// browser.
    Svg,
    /// Same swim-lane render as SVG, then rasterised through
    /// `resvg` + `tiny-skia` to a PNG. Pixel-density follows
    /// the SVG's intrinsic size (no extra DPI flag in 1.2.8 —
    /// add `--width` to taste in a follow-up).
    Png,
}

impl Cli {
    pub fn run(self) -> Result<()> {
        let project = self
            .project
            .clone()
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));

        match self.command.unwrap_or(Command::Tui) {
            Command::Init { path, force, template } => {
                init::run(&path, force, &template).map_err(Into::into)
            }
            Command::Add {
                kind,
                title,
                parent,
                slug,
                after,
            } => add::run(
                &project,
                kind.into(),
                &title,
                parent.as_deref(),
                slug.as_deref(),
                after.as_deref(),
            )
            .map_err(Into::into),
            Command::List => list::run(&project).map_err(Into::into),
            Command::Delete { path, yes } => delete::run(&project, &path, yes).map_err(Into::into),
            Command::Mv { path, direction } => {
                mv::run(&project, &path, direction).map_err(Into::into)
            }
            Command::Search { query, limit } => {
                search::run(&project, &query, limit).map_err(Into::into)
            }
            Command::Reindex { prune, adopt } => {
                reindex::run(&project, prune, adopt).map_err(Into::into)
            }
            Command::Export {
                format,
                output,
                book_name,
                status,
                tag,
            } => export::run(
                &project,
                format,
                output.as_deref(),
                book_name.as_deref(),
                status.as_deref(),
                tag.as_deref(),
            )
            .map_err(Into::into),
            Command::Ai { prompt, provider } => {
                ai::run(&project, &prompt, provider.as_deref()).map_err(Into::into)
            }
            Command::ImportHelp {
                documents_directory,
            } => import_help::run(&project, &documents_directory).map_err(Into::into),
            Command::ImportTypstHelp => {
                import_typst_help::run(&project).map_err(Into::into)
            }
            Command::ImportScrivener {
                scriv_path,
                draft_as_book,
                skip_research,
                dry_run,
            } => import_scrivener::run(
                &project,
                &scriv_path,
                draft_as_book.as_deref(),
                skip_research,
                dry_run,
            )
            .map_err(Into::into),
            Command::Backup { out } => backup::run(&project, out.as_deref()).map_err(Into::into),
            Command::Restore { archive, to } => {
                restore::run(&archive, &to).map_err(Into::into)
            }
            Command::Bund { code } => bund::run(&code, &project),
            Command::ExportConcordance { format, output, min_count } => {
                export_concordance::run(&project, format, &output, min_count)
                    .map_err(Into::into)
            }
            Command::Stats { book_name } => {
                stats::run(&project, book_name.as_deref()).map_err(Into::into)
            }
            Command::Doctor { voices, tts_test, filter_words_snippet, scan, json, class, autofix, yes } => {
                if filter_words_snippet {
                    doctor::run_filter_words_snippet().map_err(Into::into)
                } else if let Some(text) = tts_test {
                    doctor::run_tts_test(&project, &text).map_err(Into::into)
                } else if voices {
                    doctor::run_voices().map_err(Into::into)
                } else if scan || json || class.is_some() || autofix {
                    // 1.2.15+ Phase D.1 + D.2 —
                    // project scan path.  `--json`,
                    // `--class`, `--autofix` all
                    // imply `--scan`.
                    if yes && !autofix {
                        return Err(crate::error::Error::Config(
                            "doctor: --yes requires --autofix".into()
                        ).into());
                    }
                    let selected = match class.as_deref() {
                        None => None,
                        Some(s) => match doctor_scan::ScanClass::from_slug(s) {
                            Some(c) => Some(c),
                            None => {
                                return Err(crate::error::Error::Config(format!(
                                    "doctor: unknown scan class `{s}` — try one of: {}",
                                    doctor_scan::ScanClass::ALL
                                        .iter()
                                        .map(|c| c.slug())
                                        .collect::<Vec<_>>()
                                        .join(", "),
                                ))
                                .into());
                            }
                        },
                    };
                    let report = doctor_scan::scan_project(&project, selected)?;
                    if json {
                        let rendered = serde_json::to_string_pretty(&report)
                            .map_err(|e| crate::error::Error::Store(format!("doctor JSON: {e}")))?;
                        println!("{rendered}");
                    } else {
                        doctor_scan::print_human(&report);
                    }
                    if autofix && !report.findings.is_empty() {
                        run_autofix(&project, &report, yes)?;
                    }
                    // Exit code 2 when any finding
                    // at Warning or above shipped —
                    // matches conventional doctor /
                    // linter behaviour.  Autofix
                    // doesn't suppress this: the
                    // user may have skipped fixes,
                    // and re-running shows whether
                    // the project is now clean.
                    if report.count_at_or_above(doctor_scan::ScanSeverity::Warning) > 0 {
                        std::process::exit(2);
                    }
                    Ok(())
                } else {
                    doctor::run(&project).map_err(Into::into)
                }
            }
            Command::Build { book_name, compile } => {
                build::run(&project, book_name.as_deref(), compile).map_err(Into::into)
            }
            Command::Epub {
                book_name,
                output,
                title,
                author,
            } => epub::run(
                &project,
                book_name.as_deref(),
                output.as_deref(),
                title.as_deref(),
                author.as_deref(),
            )
            .map_err(Into::into),
            Command::Audiobook {
                book_name,
                output,
                title,
                author,
            } => audiobook::run(
                &project,
                book_name.as_deref(),
                output.as_deref(),
                title.as_deref(),
                author.as_deref(),
            )
            .map_err(Into::into),
            Command::Event(cmd) => event::run(&project, cmd).map_err(Into::into),
            Command::ExportTimeline {
                book_name,
                format,
                output,
                track,
            } => export_timeline::run(
                &project,
                book_name.as_deref(),
                format,
                &output,
                track.as_deref(),
            ).map_err(Into::into),
            Command::Tui => crate::tui::run(Some(&project)).map_err(Into::into),
            Command::Config => crate::config_tui::run(&project).map_err(Into::into),
            Command::PromptsEditor => crate::prompts_tui::run(&project).map_err(Into::into),
            Command::ShowDontTell(cmd) => {
                show_dont_tell::run(&project, cmd).map_err(Into::into)
            }
            Command::Prompts(cmd) => {
                prompts::run(&project, cmd).map_err(Into::into)
            }
            Command::Language(cmd) => {
                language::run(&project, cmd).map_err(Into::into)
            }
            Command::Thread(cmd) => {
                thread::run(&project, cmd).map_err(Into::into)
            }
            Command::Template(TemplateCommand::List) => {
                templates::list_templates();
                Ok(())
            }
            Command::Comments(cmd) => {
                comments::run(&project, cmd).map_err(Into::into)
            }
            Command::Tts(cmd) => {
                tts::run(&project, cmd).map_err(Into::into)
            }
            Command::Continuity(cmd) => {
                continuity::run(&project, cmd).map_err(Into::into)
            }
            Command::Tension(cmd) => {
                tension::run(&project, cmd).map_err(Into::into)
            }
            Command::Facts(cmd) => {
                facts_scan::run(&project, cmd).map_err(Into::into)
            }
            Command::Pdf(cmd) => pdf::run(cmd, &project).map_err(Into::into),
            Command::Replace {
                pattern,
                replacement,
                regex,
                substring,
                ignore_case,
                book,
                include_system,
                dry_run,
                yes,
            } => replace::run(
                &project,
                &pattern,
                &replacement,
                regex,
                substring,
                ignore_case,
                book.as_deref(),
                include_system,
                dry_run,
                yes,
            )
            .map_err(Into::into),
            Command::Manuscript {
                book_name,
                output,
                title,
                author,
                contact,
            } => manuscript::run(
                &project,
                book_name.as_deref(),
                output.as_deref(),
                title.as_deref(),
                author.as_deref(),
                contact.as_deref(),
            )
            .map_err(Into::into),
            Command::Docx {
                book_name,
                output,
                title,
                author,
                contact,
                font,
            } => docx::run(
                &project,
                book_name.as_deref(),
                output.as_deref(),
                title.as_deref(),
                author.as_deref(),
                contact.as_deref(),
                font.as_deref(),
            )
            .map_err(Into::into),
            Command::Submissions(cmd) => {
                submissions::run(&project, cmd).map_err(Into::into)
            }
            Command::Submission(cmd) => {
                submission::run(&project, cmd).map_err(Into::into)
            }
            Command::Plan(cmd) => {
                plan::run(&project, cmd).map_err(Into::into)
            }
            Command::Edit { json, only, book_name, show_deferred, deep, provider } => {
                editorial::run(
                    &project,
                    json,
                    only,
                    book_name.as_deref(),
                    show_deferred,
                    deep,
                    provider.as_deref(),
                )
                .map_err(Into::into)
            }
            Command::BenchLoad { query, iterations } => {
                bench_load::run(&project, &query, iterations)
                    .map_err(Into::into)
            }
            Command::BenchReport {
                baseline,
                current,
                threshold,
                markdown,
            } => {
                let current = current
                    .unwrap_or_else(bench_report::default_criterion_dir);
                bench_report::run(
                    baseline.as_deref(),
                    &current,
                    threshold,
                    markdown,
                )
            }
            Command::GenFixture {
                path,
                books,
                chapters,
                paragraphs,
                target_words,
                seed,
                force,
            } => {
                let spec = gen_fixture::FixtureSpec {
                    books,
                    chapters_per_book: chapters,
                    paragraphs_per_chapter: paragraphs,
                    target_words_per_paragraph: target_words,
                    seed,
                    force,
                    ..gen_fixture::FixtureSpec::default()
                };
                let stats = gen_fixture::run(&path, spec)?;
                eprintln!(
                    "gen-fixture: {} books · {} chapters · {} paragraphs at {}",
                    stats.books_created,
                    stats.chapters_created,
                    stats.paragraphs_created,
                    path.display(),
                );
                Ok(())
            }
            Command::Recover { report, yes, keep } => {
                recover::run(&report, yes, keep)
            }
        }
    }
}

/// 1.2.15+ Phase D.2 — interactive autofix walk.
/// Iterates the scan report, prompts the user per
/// finding (or auto-accepts when `yes`), calls
/// `doctor_scan::apply_fix` for each accepted
/// repair, logs the outcome.  Halts on the first
/// fatal error (e.g. Store open failure) but
/// continues past per-finding apply errors.
fn run_autofix(project: &std::path::Path, report: &doctor_scan::ScanReport, yes: bool) -> Result<()> {
    use std::io::{BufRead, Write};
    println!();
    println!("Autofix — applying repairs.");
    let stdin = std::io::stdin();
    let mut applied = 0usize;
    let mut skipped = 0usize;
    let mut errors = 0usize;

    for (i, f) in report.findings.iter().enumerate() {
        println!(
            "\n  [{n}/{total}] {sev} · {class}",
            n = i + 1,
            total = report.findings.len(),
            sev = f.severity.slug(),
            class = f.class.slug(),
        );
        if let Some(p) = &f.path {
            println!("        path: {p}");
        }
        println!("        {}", f.detail);
        let accept = if yes {
            true
        } else {
            print!("        apply repair? [y/N]: ");
            std::io::stdout().flush().ok();
            let mut line = String::new();
            stdin
                .lock()
                .read_line(&mut line)
                .map_err(crate::error::Error::Io)?;
            matches!(line.trim(), "y" | "Y")
        };
        if !accept {
            println!("        skipped.");
            skipped += 1;
            continue;
        }
        let outcome = doctor_scan::apply_fix(project, f);
        doctor_scan::log_fix(project, f, &outcome);
        match outcome {
            Ok(note) => {
                println!("        applied: {note}");
                applied += 1;
            }
            Err(e) => {
                eprintln!("        ERROR: {e:#}");
                errors += 1;
            }
        }
    }
    println!(
        "\nAutofix done: {applied} applied, {skipped} skipped, {errors} error(s).",
    );
    Ok(())
}

#[cfg(test)]
mod prompt_resolve_tests {
    use super::strip_typst_heading;

    #[test]
    fn strips_a_single_leading_heading() {
        assert_eq!(
            strip_typst_heading("= Plan Analyze\n\nYou are an editor.\nBe terse."),
            "You are an editor.\nBe terse."
        );
        // no heading → unchanged (trimmed)
        assert_eq!(strip_typst_heading("Just a prompt.\n"), "Just a prompt.");
        // only the FIRST heading is dropped
        assert_eq!(strip_typst_heading("= Title\nbody = x"), "body = x");
    }
}