nusy-kanban 0.15.2

Arrow-native kanban engine — SHACL shapes, graph-native PRs, dual boards, NATS multi-agent collaboration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
//! Export — render Arrow items to various formats.
//!
//! Supports:
//! - `item_to_markdown` — single item with YAML frontmatter
//! - `export_board_index` — full board index (KANBAN-BOARD.md / RESEARCH-BOARD.md)
//! - `export_json` — JSON array of items
//! - `export_markdown_table` — simple markdown table
//! - `export_board_html` — standalone HTML board with inline CSS
//! - `export_research_index_html` — paper→hypothesis→experiment→measure tree
//! - `burndown_svg` — inline SVG burndown chart

use crate::hdd::RegistryChain;
use crate::schema::items_col;
use crate::stats::BurndownPoint;
use arrow::array::{Array, ListArray, RecordBatch, StringArray};

/// Status emoji mapping for board index.
fn status_icon(status: &str) -> &'static str {
    match status {
        "done" | "complete" | "arrived" => "\u{2705}", //        "in_progress" | "underway" => "\u{1f504}",     // 🔄
        "review" | "approaching" => "\u{1f4cb}",       // 📋
        "backlog" | "harbor" | "draft" => "\u{1f4cb}", // 📋
        "blocked" | "stranded" => "\u{274c}",          //        _ => "\u{2796}",                               //    }
}

/// Priority abbreviation for board index.
fn priority_abbrev(priority: &str) -> &'static str {
    match priority {
        "critical" => "CRIT",
        "high" => "HIGH",
        "medium" => "MEDI",
        "low" => "LOW",
        _ => "-",
    }
}

/// Extract the numeric ID part from an item ID (e.g., "EXP-1264" → 1264).
fn extract_id_number(id: &str) -> u32 {
    id.split('-')
        .next_back()
        .and_then(|s| s.split('.').next())
        .and_then(|s| s.parse().ok())
        .unwrap_or(0)
}

/// Format depends_on list as short references.
fn format_depends_short(depends: &[String]) -> String {
    if depends.is_empty() {
        return "-".to_string();
    }
    depends
        .iter()
        .map(|d| {
            // Shorten: "EXP-1264" → "1264", "VOY-145" → "145"
            let num = extract_id_number(d);
            if num > 0 { num.to_string() } else { d.clone() }
        })
        .collect::<Vec<_>>()
        .join(",")
}

/// Export a full board index — the KANBAN-BOARD.md format.
///
/// Generates a table of all items sorted by ID (descending), with status icons,
/// priority abbreviations, assignee, and dependency references.
pub fn export_board_index(
    batches: &[RecordBatch],
    board_name: &str,
    item_type_filter: Option<&str>,
) -> String {
    let mut lines = Vec::new();
    let now = chrono::Utc::now().format("%Y-%m-%d %H:%M");

    lines.push(format!(
        "# {} Board",
        if board_name == "development" {
            "Development"
        } else {
            "Research"
        }
    ));
    lines.push(String::new());
    lines.push(format!("*Generated: {now}*"));
    lines.push(String::new());

    // Collect all items into a sortable vec
    let mut items: Vec<ItemRow> = Vec::new();
    for batch in batches {
        let ids = col_str(batch, items_col::ID);
        let titles = col_str(batch, items_col::TITLE);
        let types = col_str(batch, items_col::ITEM_TYPE);
        let statuses = col_str(batch, items_col::STATUS);
        let priorities = col_str(batch, items_col::PRIORITY);
        let assignees = col_str(batch, items_col::ASSIGNEE);
        let depends_col = batch
            .column(items_col::DEPENDS_ON)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("depends_on column");
        let tags_col = batch
            .column(items_col::TAGS)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("tags column");

        for i in 0..batch.num_rows() {
            let item_type = types.value(i);
            if let Some(filter) = item_type_filter
                && item_type != filter
            {
                continue;
            }

            let depends = list_values(depends_col, i);
            let tags = list_values(tags_col, i);
            // Derive "For" column from first tag
            let for_col = tags.first().cloned().unwrap_or_else(|| "-".to_string());

            items.push(ItemRow {
                _id: ids.value(i).to_string(),
                id_num: extract_id_number(ids.value(i)),
                title: titles.value(i).to_string(),
                _item_type: item_type.to_string(),
                status: statuses.value(i).to_string(),
                priority: if priorities.is_null(i) {
                    "-".to_string()
                } else {
                    priorities.value(i).to_string()
                },
                assignee: if assignees.is_null(i) {
                    "-".to_string()
                } else {
                    assignees.value(i).to_string()
                },
                depends,
                for_tag: for_col,
            });
        }
    }

    // Sort by ID number descending (newest first)
    items.sort_by(|a, b| b.id_num.cmp(&a.id_num));

    // Group by item type for the header
    let type_label = item_type_filter.unwrap_or("Items");
    let count = items.len();

    lines.push(format!("## {} ({})", capitalize(type_label), count));
    lines.push(String::new());
    lines.push("| # | Title | Status | Pri | Agent | Depends | For |".to_string());
    lines.push("|---|-------|--------|-----|-------|---------|-----|".to_string());

    for item in &items {
        let icon = status_icon(&item.status);
        let pri = priority_abbrev(&item.priority);
        let depends_str = format_depends_short(&item.depends);
        // Truncate title to 50 chars (UTF-8 safe)
        let title = if item.title.chars().count() > 50 {
            let truncated: String = item.title.chars().take(47).collect();
            format!("{truncated}...")
        } else {
            item.title.clone()
        };
        lines.push(format!(
            "| {} | {} | {} | {} | {} | {} | {} |",
            item.id_num, title, icon, pri, item.assignee, depends_str, item.for_tag
        ));
    }

    lines.push(String::new());
    lines.push(
        "**Legend:** \u{1f504} Active | \u{1f4cb} Backlog/Review | \u{2705} Done | \u{274c} Blocked"
            .to_string(),
    );
    lines.push(String::new());

    // Status summary
    let mut status_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for item in &items {
        *status_counts.entry(item.status.clone()).or_insert(0) += 1;
    }
    lines.push("## Status Summary".to_string());
    lines.push(String::new());
    lines.push("| Status | Count |".to_string());
    lines.push("|--------|-------|".to_string());
    let mut sorted_statuses: Vec<_> = status_counts.iter().collect();
    sorted_statuses.sort_by_key(|(_, count)| std::cmp::Reverse(**count));
    for (status, count) in &sorted_statuses {
        lines.push(format!(
            "| {} {} | {} |",
            status_icon(status),
            status,
            count
        ));
    }
    lines.push(format!("| **Total** | **{}** |", count));
    lines.push(String::new());

    lines.join("\n")
}

/// Export items as a JSON array (includes all fields needed for dependency analysis).
pub fn export_json(batches: &[RecordBatch]) -> String {
    let mut items = Vec::new();

    for batch in batches {
        let ids = col_str(batch, items_col::ID);
        let titles = col_str(batch, items_col::TITLE);
        let types = col_str(batch, items_col::ITEM_TYPE);
        let statuses = col_str(batch, items_col::STATUS);
        let priorities = col_str(batch, items_col::PRIORITY);
        let assignees = col_str(batch, items_col::ASSIGNEE);
        let bodies = col_str(batch, items_col::BODY);
        let deleted = batch
            .column(items_col::DELETED)
            .as_any()
            .downcast_ref::<arrow::array::BooleanArray>()
            .expect("deleted column");
        let tags_col = batch
            .column(items_col::TAGS)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("tags");
        let related_col = batch
            .column(items_col::RELATED)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("related");
        let depends_col = batch
            .column(items_col::DEPENDS_ON)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("depends_on");

        for i in 0..batch.num_rows() {
            if deleted.value(i) {
                continue;
            }

            let tags = list_values(tags_col, i);
            let related = list_values(related_col, i);
            let depends_on = list_values(depends_col, i);

            let fmt_list = |vals: &[String]| -> String {
                vals.iter()
                    .map(|v| format!("\"{}\"", escape_json(v)))
                    .collect::<Vec<_>>()
                    .join(",")
            };

            let body_json = if bodies.is_null(i) {
                "null".to_string()
            } else {
                format!("\"{}\"", escape_json(bodies.value(i)))
            };

            items.push(format!(
                r#"  {{"id":"{}","title":"{}","type":"{}","status":"{}","priority":{},"assignee":{},"tags":[{}],"related":[{}],"depends_on":[{}],"body":{}}}"#,
                escape_json(ids.value(i)),
                escape_json(titles.value(i)),
                escape_json(types.value(i)),
                escape_json(statuses.value(i)),
                if priorities.is_null(i) { "null".to_string() } else { format!("\"{}\"", escape_json(priorities.value(i))) },
                if assignees.is_null(i) { "null".to_string() } else { format!("\"{}\"", escape_json(assignees.value(i))) },
                fmt_list(&tags),
                fmt_list(&related),
                fmt_list(&depends_on),
                body_json,
            ));
        }
    }

    format!("[\n{}\n]", items.join(",\n"))
}

/// Export items as a simple markdown table.
pub fn export_markdown_table(batches: &[RecordBatch]) -> String {
    let mut lines = Vec::new();
    lines.push("| ID | Title | Type | Status | Priority | Assignee |".to_string());
    lines.push("|---|---|---|---|---|---|".to_string());

    for batch in batches {
        let ids = col_str(batch, items_col::ID);
        let titles = col_str(batch, items_col::TITLE);
        let types = col_str(batch, items_col::ITEM_TYPE);
        let statuses = col_str(batch, items_col::STATUS);
        let priorities = col_str(batch, items_col::PRIORITY);
        let assignees = col_str(batch, items_col::ASSIGNEE);

        for i in 0..batch.num_rows() {
            lines.push(format!(
                "| {} | {} | {} | {} | {} | {} |",
                ids.value(i),
                titles.value(i),
                types.value(i),
                statuses.value(i),
                if priorities.is_null(i) {
                    "-"
                } else {
                    priorities.value(i)
                },
                if assignees.is_null(i) {
                    "-"
                } else {
                    assignees.value(i)
                },
            ));
        }
    }

    lines.join("\n")
}

/// Export a full board as standalone HTML with inline CSS.
///
/// Generates a responsive HTML page with:
/// - Status badges with colored backgrounds
/// - Sortable responsive table layout
/// - Status summary section
/// - Optional burndown SVG chart
pub fn export_board_html(
    batches: &[RecordBatch],
    board_name: &str,
    item_type_filter: Option<&str>,
    burndown_points: Option<&[BurndownPoint]>,
) -> String {
    let now = chrono::Utc::now().format("%Y-%m-%d %H:%M UTC");
    let board_label = if board_name == "development" {
        "Development"
    } else {
        "Research"
    };

    // Collect items
    let mut items: Vec<ItemRow> = Vec::new();
    for batch in batches {
        let ids = col_str(batch, items_col::ID);
        let titles = col_str(batch, items_col::TITLE);
        let types = col_str(batch, items_col::ITEM_TYPE);
        let statuses = col_str(batch, items_col::STATUS);
        let priorities = col_str(batch, items_col::PRIORITY);
        let assignees = col_str(batch, items_col::ASSIGNEE);
        let depends_col = batch
            .column(items_col::DEPENDS_ON)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("depends_on column");
        let tags_col = batch
            .column(items_col::TAGS)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("tags column");

        for i in 0..batch.num_rows() {
            let item_type = types.value(i);
            if let Some(filter) = item_type_filter
                && item_type != filter
            {
                continue;
            }

            let depends = list_values(depends_col, i);
            let tags = list_values(tags_col, i);
            let for_col = tags.first().cloned().unwrap_or_else(|| "-".to_string());

            items.push(ItemRow {
                _id: ids.value(i).to_string(),
                id_num: extract_id_number(ids.value(i)),
                title: titles.value(i).to_string(),
                _item_type: item_type.to_string(),
                status: statuses.value(i).to_string(),
                priority: if priorities.is_null(i) {
                    "-".to_string()
                } else {
                    priorities.value(i).to_string()
                },
                assignee: if assignees.is_null(i) {
                    "-".to_string()
                } else {
                    assignees.value(i).to_string()
                },
                depends,
                for_tag: for_col,
            });
        }
    }

    items.sort_by(|a, b| b.id_num.cmp(&a.id_num));

    // Status summary
    let mut status_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for item in &items {
        *status_counts.entry(item.status.clone()).or_insert(0) += 1;
    }

    let type_label = item_type_filter.unwrap_or("Items");

    // Build table rows
    let mut rows_html = String::new();
    for item in &items {
        let status_class = status_css_class(&item.status);
        let pri_class = priority_css_class(&item.priority);
        let title_escaped = escape_html(&item.title);
        let depends_str = format_depends_short(&item.depends);

        rows_html.push_str(&format!(
            "      <tr>\n\
             \x20       <td class=\"id\">{}</td>\n\
             \x20       <td class=\"title\">{}</td>\n\
             \x20       <td><span class=\"badge {}\">{}</span></td>\n\
             \x20       <td><span class=\"badge {}\">{}</span></td>\n\
             \x20       <td>{}</td>\n\
             \x20       <td class=\"depends\">{}</td>\n\
             \x20       <td class=\"tag\">{}</td>\n\
             \x20     </tr>\n",
            item.id_num,
            title_escaped,
            status_class,
            escape_html(&item.status),
            pri_class,
            escape_html(priority_abbrev(&item.priority)),
            escape_html(&item.assignee),
            escape_html(&depends_str),
            escape_html(&item.for_tag),
        ));
    }

    // Status summary rows
    let mut summary_html = String::new();
    let mut sorted_statuses: Vec<_> = status_counts.iter().collect();
    sorted_statuses.sort_by_key(|(_, count)| std::cmp::Reverse(**count));
    for (status, count) in &sorted_statuses {
        let cls = status_css_class(status);
        summary_html.push_str(&format!(
            "      <tr><td><span class=\"badge {cls}\">{status}</span></td><td>{count}</td></tr>\n"
        ));
    }
    summary_html.push_str(&format!(
        "      <tr class=\"total\"><td><strong>Total</strong></td><td><strong>{}</strong></td></tr>\n",
        items.len()
    ));

    // Burndown SVG
    let burndown_section = if let Some(points) = burndown_points {
        format!("  <h2>Burndown</h2>\n  {}\n", burndown_svg(points))
    } else {
        String::new()
    };

    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{board_label} Board — NuSy Kanban</title>
  <style>
{CSS}
  </style>
</head>
<body>
  <h1>{board_label} Board</h1>
  <p class="generated">Generated: {now}</p>

  <h2>{type_label_cap} ({count})</h2>
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>#</th><th>Title</th><th>Status</th><th>Pri</th>
          <th>Agent</th><th>Depends</th><th>For</th>
        </tr>
      </thead>
      <tbody>
{rows_html}      </tbody>
    </table>
  </div>

  <h2>Status Summary</h2>
  <table class="summary">
    <thead><tr><th>Status</th><th>Count</th></tr></thead>
    <tbody>
{summary_html}    </tbody>
  </table>

{burndown_section}</body>
</html>"#,
        type_label_cap = capitalize(type_label),
        count = items.len(),
    )
}

/// Generate an inline SVG burndown chart from burndown data points.
pub fn burndown_svg(points: &[BurndownPoint]) -> String {
    if points.is_empty() {
        return "<p>No burndown data.</p>".to_string();
    }

    let width = 600u32;
    let height = 300u32;
    let pad_left = 50u32;
    let pad_right = 20u32;
    let pad_top = 20u32;
    let pad_bottom = 40u32;
    let chart_w = width - pad_left - pad_right;
    let chart_h = height - pad_top - pad_bottom;

    let max_remaining = points.iter().map(|p| p.remaining).max().unwrap_or(1).max(1);
    let n = points.len();

    // Build polyline points
    let mut polyline = String::new();
    let mut circles = String::new();
    let mut labels = String::new();

    for (i, p) in points.iter().enumerate() {
        let x = pad_left as f64 + (i as f64 / (n - 1).max(1) as f64) * chart_w as f64;
        let y = pad_top as f64 + (1.0 - p.remaining as f64 / max_remaining as f64) * chart_h as f64;

        polyline.push_str(&format!("{:.1},{:.1} ", x, y));
        circles.push_str(&format!(
            "    <circle cx=\"{x:.1}\" cy=\"{y:.1}\" r=\"3\" fill=\"#2563eb\"/>\n"
        ));

        // X-axis labels (show every other label if many points)
        let show = n <= 8 || i % 2 == 0 || i == n - 1;
        if show {
            labels.push_str(&format!(
                "    <text x=\"{x:.1}\" y=\"{}\" text-anchor=\"middle\" \
                 class=\"axis-label\">{}</text>\n",
                height - 8,
                escape_html(&p.label)
            ));
        }
    }

    // Y-axis labels (5 ticks)
    let mut y_labels = String::new();
    for tick in 0..=4 {
        let val = max_remaining as f64 * tick as f64 / 4.0;
        let y = pad_top as f64 + (1.0 - tick as f64 / 4.0) * chart_h as f64;
        y_labels.push_str(&format!(
            "    <text x=\"{}\" y=\"{:.1}\" text-anchor=\"end\" \
             class=\"axis-label\">{}</text>\n\
             \x20   <line x1=\"{pad_left}\" y1=\"{y:.1}\" x2=\"{}\" y2=\"{y:.1}\" \
             stroke=\"#e5e7eb\" stroke-width=\"1\"/>\n",
            pad_left - 6,
            y + 4.0,
            val.round() as u32,
            width - pad_right,
        ));
    }

    format!(
        r##"<svg viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg"
   style="max-width:{width}px;width:100%;font-family:system-ui,sans-serif;">
    <style>
      .axis-label {{ font-size: 11px; fill: #6b7280; }}
    </style>
{y_labels}{circles}    <polyline points="{polyline}" fill="none" stroke="#2563eb" stroke-width="2"/>
{labels}  </svg>"##
    )
}

/// Export a research index as standalone HTML: paper → hypothesis → experiment → measure tree.
pub fn export_research_index_html(chains: &[RegistryChain]) -> String {
    let now = chrono::Utc::now().format("%Y-%m-%d %H:%M UTC");

    let mut tree_html = String::new();
    if chains.is_empty() {
        tree_html.push_str("  <p>No papers found on the research board.</p>\n");
    } else {
        tree_html.push_str("  <ul class=\"tree\">\n");
        for chain in chains {
            tree_html.push_str(&format!(
                "    <li class=\"paper\"><span class=\"badge badge-paper\">{}</span> {}\n",
                escape_html(&chain.paper_id),
                escape_html(&chain.paper_title),
            ));
            if !chain.hypotheses.is_empty() {
                tree_html.push_str("      <ul>\n");
                for hyp in &chain.hypotheses {
                    tree_html.push_str(&format!(
                        "        <li class=\"hypothesis\"><span class=\"badge badge-hyp\">{}</span> {}\n",
                        escape_html(&hyp.id),
                        escape_html(&hyp.title),
                    ));
                    if !hyp.experiments.is_empty() {
                        tree_html.push_str("          <ul>\n");
                        for expr in &hyp.experiments {
                            tree_html.push_str(&format!(
                                "            <li class=\"experiment\"><span class=\"badge badge-expr\">{}</span> {}\n",
                                escape_html(&expr.id),
                                escape_html(&expr.title),
                            ));
                            if !expr.measures.is_empty() {
                                tree_html.push_str("              <ul>\n");
                                for m in &expr.measures {
                                    tree_html.push_str(&format!(
                                        "                <li class=\"measure\"><span class=\"badge badge-measure\">{}</span> {}</li>\n",
                                        escape_html(&m.id),
                                        escape_html(&m.title),
                                    ));
                                }
                                tree_html.push_str("              </ul>\n");
                            }
                            tree_html.push_str("            </li>\n");
                        }
                        tree_html.push_str("          </ul>\n");
                    }
                    tree_html.push_str("        </li>\n");
                }
                tree_html.push_str("      </ul>\n");
            }
            tree_html.push_str("    </li>\n");
        }
        tree_html.push_str("  </ul>\n");
    }

    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Research Index — NuSy Kanban</title>
  <style>
{CSS}
{TREE_CSS}
  </style>
</head>
<body>
  <h1>Research Index</h1>
  <p class="generated">Generated: {now}</p>
  <p>Paper &rarr; Hypothesis &rarr; Experiment &rarr; Measure</p>

{tree_html}</body>
</html>"#,
    )
}

// ─── HTML helpers ──────────────────────────────────────────────────────────

/// Inline CSS for HTML exports (no external dependencies).
const CSS: &str = r#"    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
      max-width: 960px; margin: 0 auto; padding: 1rem;
      color: #1f2937; background: #f9fafb;
    }
    h1 { margin-bottom: 0.25rem; }
    h2 { margin: 1.5rem 0 0.5rem; }
    p.generated { color: #6b7280; font-size: 0.85rem; margin-bottom: 1rem; }
    .table-wrap { overflow-x: auto; }
    table { border-collapse: collapse; width: 100%; font-size: 0.9rem; }
    th, td { padding: 0.4rem 0.6rem; text-align: left; border-bottom: 1px solid #e5e7eb; }
    th { background: #f3f4f6; font-weight: 600; position: sticky; top: 0; }
    tr:hover { background: #f0f4ff; }
    .id { font-family: monospace; white-space: nowrap; }
    .title { max-width: 320px; }
    .depends, .tag { font-family: monospace; font-size: 0.85rem; color: #6b7280; }
    .badge {
      display: inline-block; padding: 0.15rem 0.5rem; border-radius: 9999px;
      font-size: 0.78rem; font-weight: 500; white-space: nowrap;
    }
    .status-done       { background: #d1fae5; color: #065f46; }
    .status-in_progress { background: #dbeafe; color: #1e40af; }
    .status-review     { background: #fef3c7; color: #92400e; }
    .status-backlog    { background: #f3f4f6; color: #374151; }
    .status-blocked    { background: #fee2e2; color: #991b1b; }
    .status-default    { background: #f3f4f6; color: #374151; }
    .pri-critical      { background: #fee2e2; color: #991b1b; }
    .pri-high          { background: #fef3c7; color: #92400e; }
    .pri-medium        { background: #e0e7ff; color: #3730a3; }
    .pri-low           { background: #f3f4f6; color: #374151; }
    .pri-default       { background: #f3f4f6; color: #6b7280; }
    table.summary { max-width: 280px; }
    tr.total td { border-top: 2px solid #9ca3af; }
    @media (max-width: 640px) {
      body { padding: 0.5rem; }
      th, td { padding: 0.3rem 0.4rem; font-size: 0.8rem; }
    }"#;

/// Additional CSS for the research index tree view.
const TREE_CSS: &str = r#"    .tree, .tree ul { list-style: none; padding-left: 1.5rem; }
    .tree > li { padding-left: 0; }
    .tree li { padding: 0.3rem 0; position: relative; }
    .tree li::before {
      content: ''; position: absolute; left: -1rem; top: 0;
      border-left: 1px solid #d1d5db; height: 100%;
    }
    .tree li::after {
      content: ''; position: absolute; left: -1rem; top: 0.9rem;
      border-top: 1px solid #d1d5db; width: 0.8rem;
    }
    .tree > li::before, .tree > li::after { display: none; }
    .tree li:last-child::before { height: 0.9rem; }
    .badge-paper   { background: #dbeafe; color: #1e40af; }
    .badge-hyp     { background: #fef3c7; color: #92400e; }
    .badge-expr    { background: #d1fae5; color: #065f46; }
    .badge-measure { background: #e0e7ff; color: #3730a3; }"#;

fn status_css_class(status: &str) -> &'static str {
    match status {
        "done" | "complete" | "arrived" => "status-done",
        "in_progress" | "underway" => "status-in_progress",
        "review" | "approaching" => "status-review",
        "backlog" | "harbor" | "draft" => "status-backlog",
        "blocked" | "stranded" => "status-blocked",
        _ => "status-default",
    }
}

fn priority_css_class(priority: &str) -> &'static str {
    match priority {
        "critical" => "pri-critical",
        "high" => "pri-high",
        "medium" => "pri-medium",
        "low" => "pri-low",
        _ => "pri-default",
    }
}

fn escape_html(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}

/// Export a single item batch row to a markdown string with YAML frontmatter.
pub fn item_to_markdown(batch: &RecordBatch, row: usize) -> String {
    let ids = col_str(batch, items_col::ID);
    let titles = col_str(batch, items_col::TITLE);
    let types = col_str(batch, items_col::ITEM_TYPE);
    let statuses = col_str(batch, items_col::STATUS);
    let priorities = col_str(batch, items_col::PRIORITY);
    let assignees = col_str(batch, items_col::ASSIGNEE);
    let tags_col = batch
        .column(items_col::TAGS)
        .as_any()
        .downcast_ref::<ListArray>()
        .expect("tags column");
    let related_col = batch
        .column(items_col::RELATED)
        .as_any()
        .downcast_ref::<ListArray>()
        .expect("related column");
    let depends_col = batch
        .column(items_col::DEPENDS_ON)
        .as_any()
        .downcast_ref::<ListArray>()
        .expect("depends_on column");

    let id = ids.value(row);
    let title = titles.value(row);
    let item_type = types.value(row);
    let status = statuses.value(row);

    let mut lines = Vec::new();
    lines.push("---".to_string());
    lines.push(format!("id: {id}"));
    lines.push(format!("title: \"{title}\""));
    lines.push(format!("type: {item_type}"));
    lines.push(format!("status: {status}"));

    if !priorities.is_null(row) {
        lines.push(format!("priority: {}", priorities.value(row)));
    }

    if !assignees.is_null(row) {
        lines.push(format!("assignee: {}", assignees.value(row)));
    }

    let tags = list_values(tags_col, row);
    if !tags.is_empty() {
        lines.push(format!("tags: [{}]", tags.join(", ")));
    }

    let related = list_values(related_col, row);
    if !related.is_empty() {
        lines.push(format!("related: [{}]", related.join(", ")));
    }

    let depends = list_values(depends_col, row);
    if !depends.is_empty() {
        lines.push(format!("depends_on: [{}]", depends.join(", ")));
    }

    lines.push("---".to_string());
    lines.push(String::new());

    // Append body content if present; otherwise emit a heading
    let bodies = col_str(batch, items_col::BODY);
    if !bodies.is_null(row) {
        let body = bodies.value(row).trim();
        if !body.is_empty() {
            lines.push(body.to_string());
            lines.push(String::new());
        } else {
            lines.push(format!("# {id}: {title}"));
            lines.push(String::new());
        }
    } else {
        lines.push(format!("# {id}: {title}"));
        lines.push(String::new());
    }

    lines.join("\n")
}

/// Get the next available ID for a given type prefix, as JSON.
pub fn next_id_json(prefix: &str, next_num: u32) -> String {
    format!(
        r#"{{"prefix":"{}","number":{},"id":"{}-{}"}}"#,
        prefix, next_num, prefix, next_num
    )
}

// ─── Internal types ─────────────────────────────────────────────────────────

struct ItemRow {
    _id: String,
    id_num: u32,
    title: String,
    _item_type: String,
    status: String,
    priority: String,
    assignee: String,
    depends: Vec<String>,
    for_tag: String,
}

fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(c) => c.to_uppercase().to_string() + chars.as_str(),
    }
}

// ─── Helpers ────────────────────────────────────────────────────────────────

/// Escape a string for safe JSON interpolation.
fn escape_json(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
}

fn col_str(batch: &RecordBatch, col: usize) -> &StringArray {
    batch
        .column(col)
        .as_any()
        .downcast_ref::<StringArray>()
        .expect("string column")
}

pub fn list_values(arr: &ListArray, row: usize) -> Vec<String> {
    if arr.is_null(row) {
        return Vec::new();
    }
    let values = arr.value(row);
    let str_arr = values
        .as_any()
        .downcast_ref::<StringArray>()
        .expect("list string values");
    (0..str_arr.len())
        .map(|i| str_arr.value(i).to_string())
        .collect()
}

/// Folder name for each item type in the materialize layout.
fn materialize_folder(item_type: &str, _board: &str) -> &'static str {
    match item_type {
        // Development board
        "expedition" => "expeditions",
        "chore" => "chores",
        "voyage" => "voyages",
        "hazard" => "hazards",
        "signal" => "signals",
        "feature" => "features",
        // Research board
        "paper" => "papers",
        "hypothesis" => "hypotheses",
        "experiment" => "experiments",
        "measure" => "measures",
        "literature" => "literature",
        "idea" => "ideas",
        // Fallback: use type as folder name
        _ => {
            eprintln!("Warning: unknown item type '{}', using 'misc'", item_type);
            "misc"
        }
    }
}

/// Materialize Arrow items to a folder-per-type layout.
///
/// Writes each item as `nusy-kanban/{work,research}/{type}/{id}.md`
/// where {work,research} is derived from the board name and {type} maps
/// to the folder names above.
///
/// Returns the number of files written.
pub fn kanban_materialize(
    batches: &[RecordBatch],
    board: &str,
    out_dir: &std::path::Path,
) -> std::io::Result<usize> {
    use arrow::array::{Array, ListArray};
    use std::io::Write;

    let ids_col = col_str_idx(batches, "id");
    let titles_col = col_str_idx(batches, "title");
    let types_col = col_str_idx(batches, "item_type");
    let statuses_col = col_str_idx(batches, "status");
    let priorities_col = col_str_idx(batches, "priority");
    let assignees_col = col_str_idx(batches, "assignee");
    let tags_col_idx = batch_col_idx(batches, "tags");
    let related_col_idx = batch_col_idx(batches, "related");
    let depends_col_idx = batch_col_idx(batches, "depends_on");
    let body_col_idx = batch_col_idx(batches, "body");

    let board_folder = if board == "development" { "work" } else { "research" };
    let mut files_written = 0usize;
    let mut errors = 0usize;

    for batch in batches {
        let ids = arrow::array::as_string_array(batch.column(ids_col));
        let titles = arrow::array::as_string_array(batch.column(titles_col));
        let types = arrow::array::as_string_array(batch.column(types_col));
        let statuses = arrow::array::as_string_array(batch.column(statuses_col));
        let priorities = arrow::array::as_string_array(batch.column(priorities_col));
        let assignees = arrow::array::as_string_array(batch.column(assignees_col));

        let tags_col = batch
            .column(tags_col_idx)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("tags column");
        let related_col = batch
            .column(related_col_idx)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("related column");
        let depends_col = batch
            .column(depends_col_idx)
            .as_any()
            .downcast_ref::<ListArray>()
            .expect("depends_on column");

        let bodies = arrow::array::as_string_array(batch.column(body_col_idx));

        for i in 0..batch.num_rows() {
            let id = ids.value(i);
            let title = titles.value(i);
            let item_type = types.value(i);
            let status = statuses.value(i);

            let folder = materialize_folder(item_type, board);
            let type_folder = out_dir.join(board_folder).join(folder);

            // Create parent directories
            if let Err(e) = std::fs::create_dir_all(&type_folder) {
                eprintln!("  ERROR creating {}: {}", type_folder.display(), e);
                errors += 1;
                continue;
            }

            // Sanitize id for filesystem: some IDs contain embedded type prefixes like "expedition/EXP-P008-001"
            let safe_id = id.replace('/', "-");
            let file_path = type_folder.join(format!("{}.md", safe_id));
            let mut file = match std::fs::File::create(&file_path) {
                Ok(f) => f,
                Err(e) => {
                    eprintln!("  ERROR creating {}: {}", file_path.display(), e);
                    errors += 1;
                    continue;
                }
            };

            // Write YAML frontmatter
            writeln!(file, "---").unwrap();
            writeln!(file, "id: {}", id).unwrap();
            writeln!(file, "title: \"{}\"", escape_frontmatter(title)).unwrap();
            writeln!(file, "type: {}", item_type).unwrap();
            writeln!(file, "status: {}", status).unwrap();

            if !priorities.is_null(i) {
                writeln!(file, "priority: {}", priorities.value(i)).unwrap();
            }
            if !assignees.is_null(i) {
                writeln!(file, "assignee: {}", assignees.value(i)).unwrap();
            }

            let tags = list_values(tags_col, i);
            if !tags.is_empty() {
                writeln!(file, "tags: [{}]", tags.join(", ")).unwrap();
            }
            let related = list_values(related_col, i);
            if !related.is_empty() {
                writeln!(file, "related: [{}]", related.join(", ")).unwrap();
            }
            let depends = list_values(depends_col, i);
            if !depends.is_empty() {
                writeln!(file, "depends_on: [{}]", depends.join(", ")).unwrap();
            }

            writeln!(file, "---").unwrap();
            writeln!(file).unwrap();

            // Write body or default heading
            if !bodies.is_null(i) {
                let body = bodies.value(i).trim();
                if !body.is_empty() {
                    writeln!(file, "{}", body).unwrap();
                } else {
                    writeln!(file, "# {}: {}", id, title).unwrap();
                }
            } else {
                writeln!(file, "# {}: {}", id, title).unwrap();
            }

            files_written += 1;
        }
    }

    if errors > 0 {
        eprintln!("  {} errors during materialization", errors);
    }

    Ok(files_written)
}

/// Materialize a single Arrow item to its folder-per-type layout.
///
/// Writes the item as `nusy-kanban/{work,research}/{type}/{id}/{id}.md`.
/// Returns the path that was written, or an error.
///
/// The batch is assumed to be a single-row batch (e.g., from `store.get_item(id)`
/// which returns `batch.slice(i, 1)`).
pub fn kanban_materialize_single(
    batch: &RecordBatch,
    out_dir: &std::path::Path,
) -> std::io::Result<std::path::PathBuf> {
    use arrow::array::{Array, ListArray};
    use std::io::Write;

    debug_assert_eq!(batch.num_rows(), 1, "kanban_materialize_single requires exactly 1 row");

    let schema = batch.schema();
    let idx = |name| schema.index_of(name).unwrap();

    let ids = arrow::array::as_string_array(batch.column(idx("id")));
    let titles = arrow::array::as_string_array(batch.column(idx("title")));
    let types = arrow::array::as_string_array(batch.column(idx("item_type")));
    let statuses = arrow::array::as_string_array(batch.column(idx("status")));
    let priorities = arrow::array::as_string_array(batch.column(idx("priority")));
    let assignees = arrow::array::as_string_array(batch.column(idx("assignee")));
    let bodies = arrow::array::as_string_array(batch.column(idx("body")));

    let tags_idx = idx("tags");
    let related_idx = idx("related");
    let depends_idx = idx("depends_on");

    let tags_col = batch
        .column(tags_idx)
        .as_any()
        .downcast_ref::<ListArray>()
        .expect("tags column");
    let related_col = batch
        .column(related_idx)
        .as_any()
        .downcast_ref::<ListArray>()
        .expect("related column");
    let depends_col = batch
        .column(depends_idx)
        .as_any()
        .downcast_ref::<ListArray>()
        .expect("depends_on column");

    let i = 0; // Single row
    let id = ids.value(i);
    let title = titles.value(i);
    let item_type = types.value(i);
    let status = statuses.value(i);

    let folder = materialize_folder(item_type, "");
    let id_upper = id.to_uppercase();
    let board_folder = if id_upper.starts_with("EX") || id_upper.starts_with("CH")
        || id_upper.starts_with("VY") || id_upper.starts_with("HZ")
        || id_upper.starts_with("SG") || id_upper.starts_with("FT")
    {
        "work"
    } else {
        "research"
    };
    let safe_id = id.replace('/', "-");
    let item_folder = out_dir.join(board_folder).join(folder).join(safe_id.clone());

    // Create parent directories
    std::fs::create_dir_all(&item_folder)?;

    // Sanitize id for filesystem: some IDs contain embedded slashes
    let file_path = item_folder.join(format!("{}.md", safe_id));
    let mut file = std::fs::File::create(&file_path)?;

    // Write YAML frontmatter
    writeln!(file, "---")?;
    writeln!(file, "id: {}", id)?;
    writeln!(file, "title: \"{}\"", escape_frontmatter(title))?;
    writeln!(file, "type: {}", item_type)?;
    writeln!(file, "status: {}", status)?;

    if !priorities.is_null(i) {
        writeln!(file, "priority: {}", priorities.value(i))?;
    }
    if !assignees.is_null(i) {
        writeln!(file, "assignee: {}", assignees.value(i))?;
    }

    let tags = list_values(tags_col, i);
    if !tags.is_empty() {
        writeln!(file, "tags: [{}]", tags.join(", "))?;
    }
    let related = list_values(related_col, i);
    if !related.is_empty() {
        writeln!(file, "related: [{}]", related.join(", "))?;
    }
    let depends = list_values(depends_col, i);
    if !depends.is_empty() {
        writeln!(file, "depends_on: [{}]", depends.join(", "))?;
    }

    writeln!(file, "---")?;
    writeln!(file)?;

    // Write body or default heading
    if !bodies.is_null(i) {
        let body = bodies.value(i).trim();
        if !body.is_empty() {
            writeln!(file, "{}", body)?;
        } else {
            writeln!(file, "# {}: {}", id, title)?;
        }
    } else {
        writeln!(file, "# {}: {}", id, title)?;
    }

    Ok(file_path)
}

/// Escape a string for safe YAML frontmatter quoting.
fn escape_frontmatter(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', " ")
}

/// Get column index by name from first batch.
fn col_str_idx(batches: &[RecordBatch], name: &str) -> usize {
    batches
        .first()
        .map(|b| b.schema().index_of(name).expect(format!("column '{}' not found", name).as_str()))
        .unwrap_or(0)
}

/// Get column index for a ListArray column.
fn batch_col_idx(batches: &[RecordBatch], name: &str) -> usize {
    col_str_idx(batches, name)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crud::{CreateItemInput, KanbanStore};
    use crate::item_type::ItemType;

    fn create_test_store() -> KanbanStore {
        let mut store = KanbanStore::new();
        store
            .create_item(&CreateItemInput {
                title: "Arrow Engine".to_string(),
                item_type: ItemType::Expedition,
                priority: Some("critical".to_string()),
                assignee: Some("M5".to_string()),
                tags: vec!["v14".to_string()],
                related: vec!["VOY-145".to_string()],
                depends_on: vec!["EXP-100".to_string()],
                body: None,
            })
            .expect("create");
        store
            .create_item(&CreateItemInput {
                title: "CLI Parity".to_string(),
                item_type: ItemType::Expedition,
                priority: Some("high".to_string()),
                assignee: Some("Mini".to_string()),
                tags: vec!["v14".to_string(), "cli".to_string()],
                related: vec![],
                depends_on: vec![],
                body: None,
            })
            .expect("create");
        store
            .create_item(&CreateItemInput {
                title: "Research Paper".to_string(),
                item_type: ItemType::Paper,
                priority: Some("medium".to_string()),
                assignee: None,
                tags: vec![],
                related: vec![],
                depends_on: vec![],
                body: None,
            })
            .expect("create");
        store
    }

    #[test]
    fn test_item_to_markdown() {
        let store = create_test_store();
        let item = store.get_item("EX-1300").expect("get");
        let md = item_to_markdown(&item, 0);

        assert!(md.contains("---"));
        assert!(md.contains("id: EX-1300"));
        assert!(md.contains("title: \"Arrow Engine\""));
        assert!(md.contains("type: expedition"));
        assert!(md.contains("priority: critical"));
        assert!(md.contains("assignee: M5"));
        assert!(md.contains("tags: [v14]"));
        assert!(md.contains("depends_on: [EXP-100]"));
    }

    #[test]
    fn test_next_id_json() {
        let json = next_id_json("EX", 1300);
        assert_eq!(json, r#"{"prefix":"EX","number":1300,"id":"EX-1300"}"#);
    }

    #[test]
    fn test_item_to_markdown_no_optional_fields() {
        let store = create_test_store();
        let item = store.get_item("PAPER-1302").expect("get");
        let md = item_to_markdown(&item, 0);

        assert!(md.contains("id: PAPER-1302"));
        assert!(!md.contains("assignee:"));
    }

    #[test]
    fn test_board_index_contains_all_items() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let output = export_board_index(&batches, "development", None);

        assert!(output.contains("# Development Board"));
        assert!(output.contains("Arrow Engine"));
        assert!(output.contains("CLI Parity"));
        assert!(output.contains("CRIT"));
        assert!(output.contains("HIGH"));
        assert!(output.contains("M5"));
        assert!(output.contains("Mini"));
    }

    #[test]
    fn test_board_index_has_status_summary() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let output = export_board_index(&batches, "development", None);

        assert!(output.contains("## Status Summary"));
        assert!(output.contains("backlog"));
        assert!(output.contains("**Total**"));
    }

    #[test]
    fn test_board_index_depends_formatting() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let output = export_board_index(&batches, "development", None);

        // EXP-1 depends on EXP-100 → should show "100"
        assert!(output.contains("100"));
    }

    #[test]
    fn test_board_index_with_type_filter() {
        let mut store = create_test_store();
        // Add a non-expedition item to dev board
        store
            .create_item(&CreateItemInput {
                title: "Cleanup Task".to_string(),
                item_type: ItemType::Chore,
                priority: Some("low".to_string()),
                assignee: None,
                tags: vec![],
                related: vec![],
                depends_on: vec![],
                body: None,
            })
            .expect("create chore");

        let batches = store.query_items(None, None, Some("development"), None);
        let output = export_board_index(&batches, "development", Some("expedition"));

        // Expeditions should appear
        assert!(output.contains("Arrow Engine"));
        assert!(output.contains("CLI Parity"));
        // Chore should NOT appear (filtered by type)
        assert!(
            !output.contains("Cleanup Task"),
            "Chore should be excluded by expedition type filter"
        );
    }

    #[test]
    fn test_export_json() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let json = export_json(&batches);

        assert!(json.starts_with('['));
        assert!(json.ends_with(']'));
        assert!(json.contains("\"id\":\"EX-1300\""));
        assert!(json.contains("\"title\":\"Arrow Engine\""));
        assert!(json.contains("\"priority\":\"critical\""));
    }

    #[test]
    fn test_export_markdown_table() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let md = export_markdown_table(&batches);

        assert!(md.contains("| ID | Title |"));
        assert!(md.contains("| EX-1300 | Arrow Engine |"));
        assert!(md.contains("| EX-1301 | CLI Parity |"));
    }

    #[test]
    fn test_research_board_index() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("research"), None);
        let output = export_board_index(&batches, "research", None);

        assert!(output.contains("# Research Board"));
        assert!(output.contains("Research Paper"));
    }

    #[test]
    fn test_empty_board_index() {
        let batches: Vec<RecordBatch> = vec![];
        let output = export_board_index(&batches, "development", None);

        assert!(output.contains("# Development Board"));
        assert!(output.contains("Items (0)"));
        assert!(output.contains("**Total** | **0**"));
    }

    #[test]
    fn test_export_json_empty() {
        let batches: Vec<RecordBatch> = vec![];
        let json = export_json(&batches);
        assert_eq!(json, "[\n\n]");
    }

    #[test]
    fn test_status_icons() {
        assert_eq!(status_icon("done"), "\u{2705}");
        assert_eq!(status_icon("in_progress"), "\u{1f504}");
        assert_eq!(status_icon("backlog"), "\u{1f4cb}");
        assert_eq!(status_icon("blocked"), "\u{274c}");
    }

    #[test]
    fn test_priority_abbrev() {
        assert_eq!(priority_abbrev("critical"), "CRIT");
        assert_eq!(priority_abbrev("high"), "HIGH");
        assert_eq!(priority_abbrev("medium"), "MEDI");
        assert_eq!(priority_abbrev("low"), "LOW");
    }

    #[test]
    fn test_item_to_markdown_with_body() {
        let mut store = KanbanStore::new();
        store
            .create_item(&CreateItemInput {
                title: "Rich Content".to_string(),
                item_type: ItemType::Expedition,
                priority: Some("high".to_string()),
                assignee: Some("DGX".to_string()),
                tags: vec!["v14".to_string()],
                related: vec![],
                depends_on: vec![],
                body: Some(
                    "# EX-1300: Rich Content\n\n## Why This Exists\n\nBecause reasons.\n\n## Phase 1\n\nDo it.".to_string(),
                ),
            })
            .expect("create");
        let item = store.get_item("EX-1300").expect("get");
        let md = item_to_markdown(&item, 0);

        // Should contain frontmatter
        assert!(md.contains("---"));
        assert!(md.contains("id: EX-1300"));
        // Body replaces the heading — should NOT have duplicate heading
        assert!(md.contains("# EX-1300: Rich Content"));
        // Should contain body content
        assert!(md.contains("## Why This Exists"));
        assert!(md.contains("Because reasons."));
        assert!(md.contains("## Phase 1"));
    }

    #[test]
    fn test_item_to_markdown_without_body() {
        let store = create_test_store();
        let item = store.get_item("EX-1300").expect("get");
        let md = item_to_markdown(&item, 0);

        assert!(md.contains("# EX-1300: Arrow Engine"));
        // No body content — just frontmatter + heading
        assert!(!md.contains("## Phase"));
    }

    #[test]
    fn test_export_json_with_body() {
        let mut store = KanbanStore::new();
        store
            .create_item(&CreateItemInput {
                title: "JSON Body".to_string(),
                item_type: ItemType::Expedition,
                priority: Some("high".to_string()),
                assignee: None,
                tags: vec![],
                related: vec![],
                depends_on: vec![],
                body: Some("Body content here".to_string()),
            })
            .expect("create");

        let batches = store.query_items(None, None, None, None);
        let json = export_json(&batches);
        assert!(json.contains("\"body\":\"Body content here\""));
    }

    #[test]
    fn test_export_json_null_body() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let json = export_json(&batches);
        assert!(json.contains("\"body\":null"));
    }

    #[test]
    fn test_round_trip_create_body_export() {
        // Create an item with body content (simulating --body-file)
        let body = "# EX-1300: Round Trip Test\n\n\
                     ## Phase 1: Setup\n\n\
                     - **What:** Do the thing\n\
                     - **Acceptance criteria:** Thing is done\n\n\
                     ## Phase 2: Verify\n\n\
                     Run tests.\n\n\
                     ## Constraints\n\n\
                     - Don't break anything";

        let mut store = KanbanStore::new();
        store
            .create_item(&CreateItemInput {
                title: "Round Trip Test".to_string(),
                item_type: ItemType::Expedition,
                priority: Some("high".to_string()),
                assignee: Some("DGX".to_string()),
                tags: vec!["v14".to_string(), "test".to_string()],
                related: vec!["VOY-152".to_string()],
                depends_on: vec!["EXP-1280".to_string()],
                body: Some(body.to_string()),
            })
            .expect("create");

        // Export to markdown
        let item = store.get_item("EX-1300").expect("get");
        let md = item_to_markdown(&item, 0);

        // Verify frontmatter is correct
        assert!(md.contains("id: EX-1300"));
        assert!(md.contains("title: \"Round Trip Test\""));
        assert!(md.contains("type: expedition"));
        assert!(md.contains("status: backlog"));
        assert!(md.contains("priority: high"));
        assert!(md.contains("assignee: DGX"));
        assert!(md.contains("tags: [v14, test]"));
        assert!(md.contains("related: [VOY-152]"));
        assert!(md.contains("depends_on: [EXP-1280]"));

        // Verify body content survives round-trip exactly
        assert!(md.contains("## Phase 1: Setup"));
        assert!(md.contains("- **What:** Do the thing"));
        assert!(md.contains("## Phase 2: Verify"));
        assert!(md.contains("Run tests."));
        assert!(md.contains("## Constraints"));
        assert!(md.contains("- Don't break anything"));

        // Verify NO duplicate heading (body already contains # EX-1300: ...)
        let heading_count = md.matches("# EX-1300: Round Trip Test").count();
        assert_eq!(heading_count, 1, "heading should appear exactly once");
    }

    // ─── Phase 1: HTML Export Tests ────────────────────────────────────────

    #[test]
    fn test_html_export_is_standalone() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let html = export_board_html(&batches, "development", None, None);

        assert!(html.starts_with("<!DOCTYPE html>"));
        assert!(html.contains("<html lang=\"en\">"));
        assert!(html.contains("<style>"));
        assert!(html.contains("</html>"));
        // No external CSS/JS references
        assert!(!html.contains("<link"));
        assert!(!html.contains("<script src"));
    }

    #[test]
    fn test_html_export_contains_items() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let html = export_board_html(&batches, "development", None, None);

        assert!(html.contains("Arrow Engine"));
        assert!(html.contains("CLI Parity"));
        assert!(html.contains("Development Board"));
    }

    #[test]
    fn test_html_export_status_badges() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let html = export_board_html(&batches, "development", None, None);

        // Status badges should have CSS classes
        assert!(html.contains("status-backlog"));
        assert!(html.contains("class=\"badge"));
    }

    #[test]
    fn test_html_export_priority_badges() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let html = export_board_html(&batches, "development", None, None);

        assert!(html.contains("CRIT"));
        assert!(html.contains("HIGH"));
        assert!(html.contains("pri-critical"));
        assert!(html.contains("pri-high"));
    }

    #[test]
    fn test_html_export_status_summary() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let html = export_board_html(&batches, "development", None, None);

        assert!(html.contains("Status Summary"));
        assert!(html.contains("<strong>Total</strong>"));
    }

    #[test]
    fn test_html_export_responsive() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let html = export_board_html(&batches, "development", None, None);

        assert!(html.contains("viewport"));
        assert!(html.contains("@media"));
        assert!(html.contains("table-wrap"));
    }

    #[test]
    fn test_html_export_escapes_html() {
        let mut store = KanbanStore::new();
        store
            .create_item(&CreateItemInput {
                title: "XSS <script>alert(1)</script>".to_string(),
                item_type: ItemType::Expedition,
                priority: Some("high".to_string()),
                assignee: None,
                tags: vec![],
                related: vec![],
                depends_on: vec![],
                body: None,
            })
            .expect("create");

        let batches = store.query_items(None, None, Some("development"), None);
        let html = export_board_html(&batches, "development", None, None);

        assert!(!html.contains("<script>alert(1)</script>"));
        assert!(html.contains("&lt;script&gt;"));
    }

    #[test]
    fn test_html_export_empty_board() {
        let batches: Vec<RecordBatch> = vec![];
        let html = export_board_html(&batches, "development", None, None);

        assert!(html.contains("Development Board"));
        assert!(html.contains("(0)"));
        assert!(html.contains("<strong>0</strong>"));
    }

    #[test]
    fn test_html_export_research_board() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("research"), None);
        let html = export_board_html(&batches, "research", None, None);

        assert!(html.contains("Research Board"));
        assert!(html.contains("Research Paper"));
    }

    #[test]
    fn test_html_export_with_burndown() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let points = vec![
            BurndownPoint {
                timestamp_ms: 0,
                label: "Mar 4".to_string(),
                remaining: 10,
            },
            BurndownPoint {
                timestamp_ms: 604800000,
                label: "Mar 11".to_string(),
                remaining: 7,
            },
            BurndownPoint {
                timestamp_ms: 1209600000,
                label: "Mar 18".to_string(),
                remaining: 3,
            },
        ];
        let html = export_board_html(&batches, "development", None, Some(&points));

        assert!(html.contains("<svg"));
        assert!(html.contains("Burndown"));
        assert!(html.contains("Mar 4"));
        assert!(html.contains("Mar 18"));
    }

    #[test]
    fn test_html_export_without_burndown() {
        let store = create_test_store();
        let batches = store.query_items(None, None, Some("development"), None);
        let html = export_board_html(&batches, "development", None, None);

        assert!(!html.contains("<svg"));
        assert!(!html.contains("Burndown"));
    }

    // ─── Phase 2: Research Index Tests ─────────────────────────────────────

    #[test]
    fn test_research_index_empty() {
        let chains: Vec<RegistryChain> = vec![];
        let html = export_research_index_html(&chains);

        assert!(html.starts_with("<!DOCTYPE html>"));
        assert!(html.contains("Research Index"));
        assert!(html.contains("No papers found"));
    }

    #[test]
    fn test_research_index_with_chains() {
        use crate::hdd::{RegistryExperiment, RegistryHypothesis, RegistryItem};

        let chains = vec![RegistryChain {
            paper_id: "PAPER-130".to_string(),
            paper_title: "Perception Study".to_string(),
            hypotheses: vec![RegistryHypothesis {
                id: "H130.1".to_string(),
                title: "Beings prefer visual cues".to_string(),
                experiments: vec![RegistryExperiment {
                    id: "EXPR-130.1".to_string(),
                    title: "A/B visual vs text".to_string(),
                    measures: vec![RegistryItem {
                        id: "M-42".to_string(),
                        title: "Response accuracy".to_string(),
                    }],
                }],
            }],
        }];

        let html = export_research_index_html(&chains);

        assert!(html.contains("Research Index"));
        assert!(html.contains("PAPER-130"));
        assert!(html.contains("Perception Study"));
        assert!(html.contains("H130.1"));
        assert!(html.contains("Beings prefer visual cues"));
        assert!(html.contains("EXPR-130.1"));
        assert!(html.contains("A/B visual vs text"));
        assert!(html.contains("M-42"));
        assert!(html.contains("Response accuracy"));
    }

    #[test]
    fn test_research_index_tree_badges() {
        use crate::hdd::{RegistryExperiment, RegistryHypothesis, RegistryItem};

        let chains = vec![RegistryChain {
            paper_id: "PAPER-5".to_string(),
            paper_title: "Test Paper".to_string(),
            hypotheses: vec![RegistryHypothesis {
                id: "H5.1".to_string(),
                title: "Test Hypothesis".to_string(),
                experiments: vec![RegistryExperiment {
                    id: "EXPR-5.1".to_string(),
                    title: "Test Experiment".to_string(),
                    measures: vec![RegistryItem {
                        id: "M-1".to_string(),
                        title: "Test Measure".to_string(),
                    }],
                }],
            }],
        }];

        let html = export_research_index_html(&chains);

        assert!(html.contains("badge-paper"));
        assert!(html.contains("badge-hyp"));
        assert!(html.contains("badge-expr"));
        assert!(html.contains("badge-measure"));
        assert!(html.contains("class=\"tree\""));
    }

    #[test]
    fn test_research_index_standalone() {
        let chains: Vec<RegistryChain> = vec![];
        let html = export_research_index_html(&chains);

        assert!(!html.contains("<link"));
        assert!(!html.contains("<script src"));
        assert!(html.contains("<style>"));
    }

    #[test]
    fn test_research_index_escapes_html() {
        use crate::hdd::RegistryHypothesis;

        let chains = vec![RegistryChain {
            paper_id: "PAPER-1".to_string(),
            paper_title: "Paper with <dangerous> chars & \"quotes\"".to_string(),
            hypotheses: vec![RegistryHypothesis {
                id: "H1.1".to_string(),
                title: "Hyp with <b>bold</b>".to_string(),
                experiments: vec![],
            }],
        }];

        let html = export_research_index_html(&chains);

        assert!(html.contains("&lt;dangerous&gt;"));
        assert!(html.contains("&amp; &quot;quotes&quot;"));
        assert!(html.contains("&lt;b&gt;bold&lt;/b&gt;"));
    }

    // ─── Phase 3: Burndown SVG Tests ───────────────────────────────────────

    #[test]
    fn test_burndown_svg_empty() {
        let points: Vec<BurndownPoint> = vec![];
        let svg = burndown_svg(&points);

        assert!(svg.contains("No burndown data"));
        assert!(!svg.contains("<svg"));
    }

    #[test]
    fn test_burndown_svg_generates_svg() {
        let points = vec![
            BurndownPoint {
                timestamp_ms: 0,
                label: "Mar 4".to_string(),
                remaining: 10,
            },
            BurndownPoint {
                timestamp_ms: 604800000,
                label: "Mar 11".to_string(),
                remaining: 5,
            },
        ];

        let svg = burndown_svg(&points);

        assert!(svg.contains("<svg"));
        assert!(svg.contains("</svg>"));
        assert!(svg.contains("<polyline"));
        assert!(svg.contains("<circle"));
        assert!(svg.contains("Mar 4"));
        assert!(svg.contains("Mar 11"));
    }

    #[test]
    fn test_burndown_svg_y_axis_labels() {
        let points = vec![
            BurndownPoint {
                timestamp_ms: 0,
                label: "W1".to_string(),
                remaining: 20,
            },
            BurndownPoint {
                timestamp_ms: 604800000,
                label: "W2".to_string(),
                remaining: 10,
            },
        ];

        let svg = burndown_svg(&points);

        // Y-axis should show values from 0 to max
        assert!(svg.contains(">0<"));
        assert!(svg.contains(">20<"));
    }

    #[test]
    fn test_burndown_svg_single_point() {
        let points = vec![BurndownPoint {
            timestamp_ms: 0,
            label: "Now".to_string(),
            remaining: 5,
        }];

        let svg = burndown_svg(&points);

        assert!(svg.contains("<svg"));
        assert!(svg.contains("<circle"));
        assert!(svg.contains("Now"));
    }

    // ─── HTML helper tests ─────────────────────────────────────────────────

    #[test]
    fn test_escape_html() {
        assert_eq!(escape_html("a < b"), "a &lt; b");
        assert_eq!(escape_html("a & b"), "a &amp; b");
        assert_eq!(escape_html("a > b"), "a &gt; b");
        assert_eq!(escape_html("a \"b\""), "a &quot;b&quot;");
        assert_eq!(escape_html("no special"), "no special");
    }

    #[test]
    fn test_status_css_class() {
        assert_eq!(status_css_class("done"), "status-done");
        assert_eq!(status_css_class("in_progress"), "status-in_progress");
        assert_eq!(status_css_class("review"), "status-review");
        assert_eq!(status_css_class("backlog"), "status-backlog");
        assert_eq!(status_css_class("blocked"), "status-blocked");
        assert_eq!(status_css_class("unknown"), "status-default");
    }

    #[test]
    fn test_priority_css_class() {
        assert_eq!(priority_css_class("critical"), "pri-critical");
        assert_eq!(priority_css_class("high"), "pri-high");
        assert_eq!(priority_css_class("medium"), "pri-medium");
        assert_eq!(priority_css_class("low"), "pri-low");
        assert_eq!(priority_css_class("-"), "pri-default");
    }
}