gen-models 0.4.0

Models for the gen sequence graph and version control system.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
//! Models and persistence helpers for Gen operations.
//!
//! An operation is a user-visible change committed to the Dolt-backed graph database. The Dolt
//! commit is the authoritative history entry and records every changed graph row. Gen also writes
//! a `gen_operation_log` row into that database to describe the semantic operation: its kind, the
//! command or summary that produced it, and when it was created. Because this row is committed
//! with the graph changes, it follows branches and can be queried at historical refs.
//!
//! Files used by an operation are tracked as metadata rather than stored in Dolt. A
//! `gen_asset_refs` row identifies each asset by its URI, content checksum, file type, logical
//! path, display name, and role. A `gen_operation_assets` row links an operation-log ID to an
//! asset-reference ID and records the asset's role in that operation, allowing one operation to
//! use multiple assets and one content-addressed asset reference to be reused by multiple
//! operations. These rows are included in the same Dolt commit as the operation, while the file
//! contents live in the workspace asset store or remote object storage addressed by the URI.

use std::{
    io::{self, BufReader},
    path::Path,
};

use gen_core::{DoltHashId, HashId, Sha256Hash, Workspace, calculate_hash};
use itertools::Itertools;
use rusqlite::{
    OptionalExtension, Result as SQLResult, ToSql, params,
    types::{FromSql, FromSqlResult, ToSqlOutput, ValueRef},
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use uuid::Uuid;

use crate::{
    Direction, ModelSelect, ModelSelectError,
    assets::{
        AssetRef, AssetRole, AssetUri, CompressionType, LocalAssetUri, OperationAsset,
        OperationKind, OperationLog, stage_bgzf_asset_copy,
    },
    db::{ConfigConnection, DbContext},
    errors::{
        AddFilesOperationError, FileAdditionError, FileStoreError, OperationError, RemoteError,
    },
    file_types::FileTypes,
    history::{
        HistoryStore,
        dolt::{DoltHistoryStore, is_current_branch_dirty},
    },
    select::ModelSelectRow,
};

pub const GEN_DEFAULT_COMMITTER_NAME: &str = "gen";
pub const DEFAULT_COMMITTER_EMAIL: &str = "gen@genhub.bio";

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OperationFile {
    pub filename: String,
    pub file_path: String,
    pub file_type: FileTypes,
    pub checksum_override: Option<Sha256Hash>,
    pub role: AssetRole,
    pub upstream_asset_ref_id: Option<HashId>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct OperationFileInfo {
    pub id: HashId,
    pub filename: String,
    pub file_path: String,
    pub asset_uri: String,
    pub file_type: FileTypes,
    pub checksum: Option<Sha256Hash>,
    #[serde(default)]
    pub materialized_checksum: Option<Sha256Hash>,
}

impl OperationFile {
    pub fn new(file_path: impl Into<String>) -> Self {
        let file_path = file_path.into();
        let file_type = FileTypes::infer_from_path(&file_path);
        let filename = Path::new(&file_path)
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or(&file_path)
            .to_string();
        Self {
            filename,
            file_path,
            file_type,
            checksum_override: None,
            role: AssetRole::Input,
            upstream_asset_ref_id: None,
        }
    }

    pub fn set_file_type(mut self, file_type: FileTypes) -> Self {
        self.file_type = file_type;
        self
    }

    pub fn set_checksum_override(mut self, checksum: Sha256Hash) -> Self {
        self.checksum_override = Some(checksum);
        self
    }

    pub fn set_role(mut self, role: AssetRole) -> Self {
        self.role = role;
        self
    }

    pub fn set_upstream_asset_ref_id(mut self, upstream_asset_ref_id: &HashId) -> Self {
        self.upstream_asset_ref_id = Some(*upstream_asset_ref_id);
        self
    }

    /// Construct the AssetRef from an OperationFile
    pub fn prepare_asset_ref(
        &self,
        workspace: &Workspace,
        created_on: i64,
    ) -> Result<AssetRef, FileAdditionError> {
        let file_addition = FileAddition::prepare(
            workspace,
            &self.file_path,
            self.file_type,
            self.checksum_override,
        )?;
        let logical_path =
            Self::storage_file_path(workspace, &self.file_path, file_addition.checksum.as_ref())?;
        let file_type = file_addition.file_type.as_str();
        Ok(AssetRef {
            id: AssetRef::id_hash(
                &file_addition,
                &self.role,
                Some(&logical_path),
                Some(&self.filename),
                self.upstream_asset_ref_id.as_ref(),
            ),
            uri: file_addition.asset_uri,
            file_type: file_type.to_string(),
            checksum: file_addition.checksum,
            materialized_checksum: file_addition.materialized_checksum,
            size: None,
            role: self.role.clone(),
            logical_path: Some(logical_path),
            name: Some(self.filename.clone()),
            created_on,
            upstream_asset_ref_id: self.upstream_asset_ref_id,
        })
    }

    /// Resolves the path stored in operation metadata without materializing remote assets.
    ///
    /// Local inputs keep their original logical path, and remote inputs keep their URI for lazy
    /// access.
    pub fn storage_file_path(
        workspace: &Workspace,
        path_or_uri: &str,
        checksum: Option<&Sha256Hash>,
    ) -> Result<String, FileAdditionError> {
        if LocalAssetUri::is_local_path_or_file_uri(path_or_uri) {
            if !LocalAssetUri::is_index_path(path_or_uri) {
                let source_path = LocalAssetUri::resolve_input_source_path(workspace, path_or_uri)?;
                return LocalAssetUri::logical_file_path(workspace, &source_path);
            }
            let checksum = checksum.ok_or_else(|| {
                FileAdditionError::ChecksumError(format!(
                    "local operation file has no checksum: {path_or_uri}"
                ))
            })?;
            LocalAssetUri::operation_file_path(workspace, path_or_uri, checksum)
        } else {
            Ok(path_or_uri.to_string())
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OperationInfo {
    pub files: Vec<OperationFile>,
    pub description: String,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OperationSummary {
    pub operation_info: OperationInfo,
    pub summary: String,
    /// Exact asset references prepared while an operation consumed its source streams.
    ///
    /// When present, commit tracks these references directly instead of preparing the original
    /// descriptors again. This is used by imports that transform a source while streaming it.
    pub prepared_asset_refs: Option<Vec<AssetRef>>,
}

impl OperationSummary {
    pub fn new(operation_info: OperationInfo, summary: impl Into<String>) -> Self {
        Self {
            operation_info,
            summary: summary.into(),
            prepared_asset_refs: None,
        }
    }

    /// Uses the already-prepared asset references when this operation is committed.
    pub fn with_prepared_asset_refs(mut self, asset_refs: Vec<AssetRef>) -> Self {
        self.prepared_asset_refs = Some(asset_refs);
        self
    }
}

#[cfg_attr(
    feature = "profiling",
    tracing::instrument(skip(context, operation_summary))
)]
pub fn commit_operation_summary(
    context: &DbContext,
    operation_summary: &OperationSummary,
) -> Result<DoltHashId, OperationError> {
    let workspace = context.workspace();
    let graph_conn = context.graph().conn();
    let history_store = DoltHistoryStore::new_with_config(graph_conn, context.config().conn());
    let operation_info = &operation_summary.operation_info;

    if !is_current_branch_dirty(graph_conn)? {
        return Err(OperationError::NoChanges);
    }

    let created_on = chrono::Utc::now()
        .timestamp_nanos_opt()
        .expect("should create operation asset timestamp");
    let prepared_assets = match &operation_summary.prepared_asset_refs {
        Some(asset_refs) => asset_refs.clone(),
        None => operation_info
            .files
            .iter()
            .map(|operation_file| operation_file.prepare_asset_ref(workspace, created_on))
            .collect::<Result<Vec<_>, _>>()
            .map_err(|err| match err {
                FileAdditionError::ConfigError(config_error) => {
                    OperationError::ConfigError(config_error)
                }
                other => OperationError::SQLError(other.to_string()),
            })?,
    };
    let operation_kind = OperationKind::Other(operation_info.description.clone());
    track_asset_refs(
        graph_conn,
        None,
        &operation_kind,
        &operation_summary.summary,
        &prepared_assets,
    )?;

    let commit_result = history_store.commit_all(&operation_summary.summary);
    commit_result.map_err(OperationError::from)
}

#[cfg_attr(
    feature = "profiling",
    tracing::instrument(skip(graph_conn, log_id, assets))
)]
pub(crate) fn track_asset_refs(
    graph_conn: &crate::db::GraphConnection,
    log_id: Option<&HashId>,
    operation_kind: &OperationKind,
    command: &str,
    assets: &[AssetRef],
) -> Result<(), rusqlite::Error> {
    let created_on = chrono::Utc::now()
        .timestamp_nanos_opt()
        .expect("should create operation asset timestamp");
    let log_id = log_id
        .copied()
        .unwrap_or_else(|| OperationLog::id_hash(operation_kind, command, created_on));
    OperationLog::create(
        graph_conn,
        &OperationLog {
            id: log_id,
            operation_kind: operation_kind.clone(),
            command: command.to_string(),
            created_on,
        },
    )?;

    for asset_ref in assets {
        AssetRef::create(graph_conn, asset_ref)?;
        OperationAsset::create(
            graph_conn,
            &OperationAsset {
                log_id,
                asset_ref_id: asset_ref.id,
                role: asset_ref.role.clone(),
            },
        )?;
    }

    Ok(())
}

#[cfg_attr(
    all(debug_assertions, feature = "profiling"),
    tracing::instrument(skip(context, files, message))
)]
/// Records files used by an operation, retaining local content and preserving remote URIs.
///
/// Checksum overrides are propagated from callers that already streamed remote content, avoiding
/// a credentials-dependent read whose only purpose would be hashing.
pub fn add_files_operation(
    context: &DbContext,
    files: &[OperationFile],
    message: Option<&str>,
) -> Result<DoltHashId, AddFilesOperationError> {
    let workspace = context.workspace();
    let graph_conn = context.graph().conn();

    let file_additions = files
        .iter()
        .map(|operation_file| {
            let file_addition = FileAddition::prepare(
                workspace,
                &operation_file.file_path,
                operation_file.file_type,
                operation_file.checksum_override,
            )?;
            let operation_file_path = OperationFile::storage_file_path(
                workspace,
                &operation_file.file_path,
                file_addition.checksum.as_ref(),
            )?;
            Ok::<(FileAddition, String, String), FileAdditionError>((
                file_addition,
                operation_file.filename.clone(),
                operation_file_path,
            ))
        })
        .collect::<Result<Vec<_>, _>>()?;

    let unique_file_additions = file_additions
        .into_iter()
        .unique_by(|(file_addition, filename, file_path)| {
            (file_addition.id, filename.clone(), file_path.clone())
        })
        .collect::<Vec<_>>();

    let log_id = HashId(calculate_hash(
        &unique_file_additions
            .iter()
            .map(|(file_addition, filename, file_path)| {
                format!("{}:{filename}:{file_path}", file_addition.id)
            })
            .sorted()
            .join(":"),
    ));

    let summary = message.map(str::to_string).unwrap_or_else(|| {
        if files.len() == 1 {
            format!("Add file {}", files[0].file_path)
        } else {
            format!("Add {} files", files.len())
        }
    });
    let created_on = chrono::Utc::now()
        .timestamp_nanos_opt()
        .expect("should create operation asset timestamp");
    let asset_refs = unique_file_additions
        .iter()
        .map(|(file_addition, filename, file_path)| {
            AssetRef::from_file_addition(
                file_addition,
                AssetRole::Input,
                Some(file_path),
                Some(filename),
                None,
                created_on,
            )
        })
        .collect::<Vec<_>>();
    track_asset_refs(
        graph_conn,
        Some(&log_id),
        &OperationKind::AddFile,
        &summary,
        &asset_refs,
    )?;
    let history_store = DoltHistoryStore::new_with_config(graph_conn, context.config().conn());
    if history_store.status()?.is_empty() {
        return Err(AddFilesOperationError::OperationError(
            OperationError::NoChanges,
        ));
    }

    history_store
        .commit_all(&summary)
        .map_err(AddFilesOperationError::from)
}

pub fn calculate_file_checksum<P: AsRef<Path>>(file_path: P) -> Result<Sha256Hash, std::io::Error> {
    let file = std::fs::File::open(file_path)?;
    let reader = BufReader::new(file);
    calculate_reader_checksum(reader)
}

pub fn calculate_reader_checksum<R: std::io::Read>(
    reader: R,
) -> Result<Sha256Hash, std::io::Error> {
    let hash_bytes = calculate_stream_hash(reader)?;
    Ok(Sha256Hash(hash_bytes))
}

fn calculate_stream_hash<R: std::io::Read>(mut reader: R) -> Result<[u8; 32], std::io::Error> {
    let mut hasher = Sha256::new();
    io::copy(&mut reader, &mut hasher)?;
    let result = hasher.finalize();
    let mut hash_array = [0u8; 32];
    hash_array.copy_from_slice(&result);
    Ok(hash_array)
}

#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize, ModelSelect)]
#[model_select(table = "file_additions")]
pub struct FileAddition {
    pub id: HashId,
    pub asset_uri: String,
    pub file_type: FileTypes,
    pub checksum: Option<Sha256Hash>,
    /// SHA-256 of the workspace bytes when they differ from the retained archive bytes.
    #[serde(default)]
    pub materialized_checksum: Option<Sha256Hash>,
}

impl FileAddition {
    pub fn file_path(&self) -> &str {
        self.asset_uri
            .strip_prefix(LocalAssetUri::SCHEME)
            .unwrap_or(&self.asset_uri)
    }

    #[cfg_attr(
        feature = "profiling",
        tracing::instrument(skip(workspace, checksum_override))
    )]
    /// Retains local source content and validates any supplied checksum against it.
    ///
    /// Local assets are retained as BGZF compressed assets; plain inputs record their source checksum separately,
    /// and ordinary gzip inputs are recompressed as bgzf. Native BGZF is stored unchanged. Index sidecars remain
    /// unchanged for direct access by index readers. Remote content remains a lazy URI and can carry an
    /// optional checksum supplied by a caller that already streamed it for useful work; preparation
    /// does not download or verify remote bytes.
    pub fn prepare(
        workspace: &Workspace,
        file_path: &str,
        file_type: FileTypes,
        checksum_override: Option<Sha256Hash>,
    ) -> Result<FileAddition, FileAdditionError> {
        let asset_uri = <dyn AssetUri>::new(workspace, file_path);
        let is_local = LocalAssetUri::is_local_path_or_file_uri(file_path);
        if is_local && !LocalAssetUri::is_index_path(file_path) {
            let source_reader = asset_uri.reader(workspace)?;
            let (compression_type, replayed_reader) =
                CompressionType::sniff(source_reader).map_err(FileAdditionError::FileReadError)?;
            return Self::prepare_from_reader(
                workspace,
                file_path,
                file_type,
                replayed_reader,
                compression_type,
                checksum_override,
            );
        }

        let checksum = asset_uri.prepare_asset(workspace, checksum_override)?;
        let stored_asset_uri = match checksum.as_ref() {
            Some(checksum) => asset_uri.stored_asset_uri(workspace, checksum)?,
            None => asset_uri.uri().to_string(),
        };

        Ok(FileAddition {
            id: LocalAssetUri::generate_file_addition_id(checksum.as_ref(), &stored_asset_uri),
            asset_uri: stored_asset_uri,
            file_type,
            checksum,
            materialized_checksum: None,
        })
    }

    /// Stores an asset from a source stream that has already been classified.
    ///
    /// Streaming importers can inspect a bounded prefix once, then send the replayed reader through
    /// the same content-addressed archive path used by ordinary local preparation.
    pub fn prepare_from_reader(
        workspace: &Workspace,
        source_uri: &str,
        file_type: FileTypes,
        reader: impl io::Read + 'static,
        compression_type: CompressionType,
        source_checksum_override: Option<Sha256Hash>,
    ) -> Result<FileAddition, FileAdditionError> {
        if LocalAssetUri::is_index_path(source_uri) {
            return Err(FileAdditionError::FileReadError(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("index sources cannot be retained as BGZF assets: {source_uri}"),
            )));
        }

        let (archive_checksum, source_checksum) = stage_bgzf_asset_copy(
            workspace,
            file_type,
            reader,
            compression_type,
            source_checksum_override,
        )
        .map_err(|error| match error {
            FileAdditionError::ChecksumError(message) => {
                FileAdditionError::ChecksumError(format!("{message}: {source_uri}"))
            }
            error => error,
        })?;
        let repo_root = workspace.repo_root()?;
        let asset_path = workspace.asset_dir()?.join(format!(
            "{archive_checksum}.{}.bgz",
            FileTypes::suffix(file_type)
        ));
        let relative_path = asset_path
            .strip_prefix(&repo_root)
            .map_err(|_| FileAdditionError::PathOutsideRepo {
                path: asset_path.clone(),
                repo_root,
            })?
            .to_string_lossy();
        let stored_asset_uri = LocalAssetUri::asset_uri(&relative_path);
        let checksum = Some(archive_checksum);
        let materialized_checksum =
            (compression_type == CompressionType::Plain).then_some(source_checksum);

        Ok(FileAddition {
            id: LocalAssetUri::generate_file_addition_id(checksum.as_ref(), &stored_asset_uri),
            asset_uri: stored_asset_uri,
            file_type,
            checksum,
            materialized_checksum,
        })
    }

    #[cfg_attr(
        all(debug_assertions, feature = "profiling"),
        tracing::instrument(skip(self, workspace))
    )]
    pub fn store_file(&self, workspace: &Workspace) -> Result<(), FileStoreError> {
        let asset_uri = <dyn AssetUri>::new(workspace, &self.asset_uri);
        asset_uri.store_file(self, workspace)
    }

    /// Returns the content-addressed filename when this asset has a verified checksum.
    ///
    /// Checksumless remote references do not live under `.gen/assets`, so they have no hashed
    /// storage filename.
    pub fn hashed_filename(&self) -> Option<String> {
        self.checksum
            .as_ref()
            .map(|checksum| <dyn AssetUri>::from_uri(&self.asset_uri).hashed_filename(checksum))
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, ModelSelect)]
#[model_select(table = "remotes", history = false)]
pub struct Remote {
    #[model_select(primary_key)]
    pub name: String,
    pub url: String,
}

impl Remote {
    /// Validate remote name - no spaces or special characters except hyphens and underscores
    pub fn validate_name(name: &str) -> Result<(), RemoteError> {
        if name.is_empty() {
            return Err(RemoteError::EmptyName);
        }

        if name
            .chars()
            .any(|c| !c.is_alphanumeric() && c != '-' && c != '_')
        {
            return Err(RemoteError::InvalidNameCharacters);
        }

        Ok(())
    }

    /// Validate URL format
    pub fn validate_url(url: &str) -> Result<(), RemoteError> {
        if url.is_empty() {
            return Err(RemoteError::EmptyUrl);
        }

        // Check if it looks like a URL with a scheme
        if url.contains("://") {
            match url::Url::parse(url) {
                Ok(parsed_url) => {
                    // Only allow http, https, and ssh schemes
                    match parsed_url.scheme() {
                        "http" | "https" | "ssh" | "file" => Ok(()),
                        _ => Err(RemoteError::UnsupportedUrlScheme),
                    }
                }
                Err(_) => Err(RemoteError::InvalidUrl("Invalid URL format".to_string())),
            }
        } else if url.starts_with('/') || url.contains(':') {
            // Assume it's a file path or SSH-style path (like user@host:path)
            Ok(())
        } else {
            Err(RemoteError::UnsupportedUrlScheme)
        }
    }

    /// Create a new remote with the given name and URL
    /// Validates input and handles constraint violations gracefully
    pub fn create(conn: &ConfigConnection, name: &str, url: &str) -> Result<Remote, RemoteError> {
        // Validate input
        Self::validate_name(name)?;
        Self::validate_url(url)?;

        let query = "INSERT INTO remotes (name, url) VALUES (?1, ?2)";
        let mut stmt = conn.prepare(query)?;

        match stmt.execute(params![name, url]) {
            Ok(_) => Ok(Remote {
                name: name.to_string(),
                url: url.to_string(),
            }),
            Err(rusqlite::Error::SqliteFailure(err, _))
                if err.code == rusqlite::ErrorCode::ConstraintViolation =>
            {
                Err(RemoteError::RemoteAlreadyExists(name.to_string()))
            }
            Err(e) => Err(RemoteError::DatabaseError(e)),
        }
    }

    /// Get a remote by name
    pub fn get_by_name(conn: &ConfigConnection, name: &str) -> Result<Remote, RemoteError> {
        Remote::select(conn)
            .name(name)
            .load()?
            .into_iter()
            .next()
            .ok_or_else(|| RemoteError::RemoteNotFound(name.to_string()))
    }

    /// Get a remote by name, returning None if not found (for backward compatibility)
    pub fn get_by_name_optional(conn: &ConfigConnection, name: &str) -> Option<Remote> {
        Self::get_by_name(conn, name).ok()
    }

    /// List all remotes
    pub fn list_all(conn: &ConfigConnection) -> Vec<Remote> {
        Remote::select(conn)
            .order_by(RemoteSelect::Name, Direction::Asc)
            .load()
            .expect("should load remotes")
    }

    /// Delete a remote by name
    pub fn delete(conn: &ConfigConnection, name: &str) -> Result<(), RemoteError> {
        // Check if remote exists first
        Self::get_by_name(conn, name)?;
        RemoteBranch::clear_by_remote(conn, name)?;

        let query = "DELETE FROM remotes WHERE name = ?1";
        let mut stmt = conn.prepare(query)?;
        stmt.execute(params![name])?;
        Ok(())
    }

    /// Check if a remote exists
    pub fn exists(conn: &ConfigConnection, name: &str) -> bool {
        Self::get_by_name_optional(conn, name).is_some()
    }
}

#[derive(Clone, Debug, Eq, PartialEq, ModelSelect)]
#[model_select(table = "remote_branch", history = false)]
pub struct RemoteBranch {
    pub remote_name: Option<String>,
    #[model_select(primary_key)]
    pub name: String,
}

impl RemoteBranch {
    pub fn set_remote_validated(
        conn: &ConfigConnection,
        branch_name: &str,
        remote_name: Option<&str>,
    ) -> Result<(), RemoteError> {
        if let Some(name) = remote_name {
            Remote::get_by_name(conn, name)?;
            conn.execute(
                "DELETE FROM remote_branch WHERE name = ?1",
                params![branch_name],
            )?;
            conn.execute(
                "INSERT INTO remote_branch (name, remote_name) VALUES (?1, ?2)",
                params![branch_name, name],
            )?;
        } else {
            conn.execute(
                "DELETE FROM remote_branch WHERE name = ?1",
                params![branch_name],
            )?;
        }
        Ok(())
    }

    pub fn get_remote(conn: &ConfigConnection, branch_name: &str) -> Option<String> {
        RemoteBranch::select(conn)
            .name(branch_name)
            .only(RemoteBranchSelect::RemoteName)
            .load()
            .ok()?
            .into_iter()
            .next()
            .flatten()
    }

    pub fn clear_by_remote(conn: &ConfigConnection, remote_name: &str) -> Result<(), RemoteError> {
        conn.execute(
            "DELETE FROM remote_branch WHERE remote_name = ?1",
            params![remote_name],
        )?;
        Ok(())
    }
}

/// A remote operation whose graph and asset phases must complete together.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RemoteOperationKind {
    /// Initializes a workspace from a remote repository.
    Clone,
    /// Advances an existing local branch from a remote repository.
    Pull,
    /// Advances a remote branch from the local repository.
    Push,
}

impl RemoteOperationKind {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Clone => "clone",
            Self::Pull => "pull",
            Self::Push => "push",
        }
    }
}

impl FromSql for RemoteOperationKind {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        value.as_str().map(|operation| match operation {
            "clone" => Self::Clone,
            "pull" => Self::Pull,
            "push" => Self::Push,
            _ => unreachable!("remote operation should satisfy its database constraint"),
        })
    }
}

impl ToSql for RemoteOperationKind {
    fn to_sql(&self) -> SQLResult<ToSqlOutput<'_>> {
        Ok(self.as_str().into())
    }
}

/// Tracks a remote operation until its graph and asset phases are complete.
#[derive(Clone, Debug, Eq, PartialEq, ModelSelect)]
#[model_select(table = "remote_operations", history = false)]
pub struct RemoteOperationRecord {
    /// Config database row identifier.
    pub id: i64,
    /// Configured remote participating in the operation.
    pub remote_name: String,
    /// Branch transferred by the operation.
    pub branch_name: String,
    /// Direction of the remote graph transfer.
    pub operation: RemoteOperationKind,
    /// Local branch commit from before the graph transfer.
    pub from_commit: Option<DoltHashId>,
    /// Last commit whose complete asset batch was verified locally.
    pub assets_transfer_checkpoint: Option<DoltHashId>,
    /// Destination graph commit whose assets must be transferred.
    pub to_commit: Option<DoltHashId>,
    /// GenHub push lease retained by a pending operation.
    pub transfer_id: Option<Uuid>,
    /// Unix timestamp after which GenHub will reject the retained push lease.
    pub transfer_expires_at: Option<i64>,
    /// Time at which the operation began.
    pub started_at: String,
    /// Time at which both graph and asset transfer completed.
    pub completed_at: Option<String>,
    /// Time at which the operation became unrecoverable.
    pub failed_at: Option<String>,
}

impl RemoteOperationRecord {
    /// Resumes an incomplete operation or starts one from the supplied local commit.
    pub fn begin_or_resume(
        conn: &ConfigConnection,
        remote_name: &str,
        branch_name: &str,
        operation: RemoteOperationKind,
        from_commit: Option<&DoltHashId>,
    ) -> SQLResult<Self> {
        let pending = conn
            .query_row(
                "SELECT * FROM remote_operations \
                 WHERE remote_name = ?1 AND branch_name = ?2 \
                   AND completed_at IS NULL AND failed_at IS NULL \
                   -- This is confusing, but this checks whether a clone operation is followed by a pull.
                   -- If a clone fails to download assets, a pull can finish the operation even though the
                   -- persisted operation is clone and the requested operation is pull.
                   AND (operation = ?3 OR operation = 'clone' AND ?3 = 'pull') \
                 ORDER BY id LIMIT 1",
                params![remote_name, branch_name, operation.as_str()],
                Self::process_row,
            )
            .optional()?;
        if let Some(pending) = pending {
            return Ok(pending);
        }

        let assets_transfer_checkpoint = conn
            .query_row(
                "SELECT assets_transfer_checkpoint FROM remote_operations \
                 WHERE remote_name = ?1 AND branch_name = ?2 AND completed_at IS NOT NULL \
                 ORDER BY id DESC LIMIT 1",
                params![remote_name, branch_name],
                |row| row.get::<_, DoltHashId>(0),
            )
            .optional()?;
        conn.execute(
            "INSERT INTO remote_operations \
             (remote_name, branch_name, operation, from_commit, assets_transfer_checkpoint) \
             VALUES (?1, ?2, ?3, ?4, ?5)",
            params![
                remote_name,
                branch_name,
                operation.as_str(),
                from_commit,
                assets_transfer_checkpoint
            ],
        )?;
        Self::select(conn)
            .get_by_id(conn.last_insert_rowid())
            .map_err(|error| match error {
                ModelSelectError::DatabaseError(error) => error,
                ModelSelectError::MultipleResults => rusqlite::Error::QueryReturnedMoreThanOneRow,
                ModelSelectError::InvalidSelector(_)
                | ModelSelectError::HistoryNotSupported { .. }
                | ModelSelectError::ProjectionSourceNotSelected { .. } => {
                    rusqlite::Error::InvalidQuery
                }
            })?
            .ok_or(rusqlite::Error::QueryReturnedNoRows)
    }

    /// Records the desired end commit an operation is tracking.
    pub fn set_destination(
        &mut self,
        conn: &ConfigConnection,
        to_commit: &DoltHashId,
    ) -> SQLResult<()> {
        conn.execute(
            "UPDATE remote_operations SET to_commit = ?1 WHERE id = ?2",
            params![to_commit, self.id],
        )?;
        self.to_commit = Some(*to_commit);
        Ok(())
    }

    /// After transferring assets for a commit, mark it in the database so subsequent transfers for
    /// resumes can restart from there.
    pub fn advance_assets_transfer_checkpoint(
        &mut self,
        conn: &ConfigConnection,
        commit: &DoltHashId,
    ) -> SQLResult<()> {
        conn.execute(
            "UPDATE remote_operations SET assets_transfer_checkpoint = ?1 WHERE id = ?2",
            params![commit, self.id],
        )?;
        self.assets_transfer_checkpoint = Some(*commit);
        Ok(())
    }

    /// Records the successful push graph transfer and its capability-scoped lease.
    pub fn set_push_destination(
        &mut self,
        conn: &ConfigConnection,
        to_commit: &DoltHashId,
        transfer_id: Uuid,
        transfer_expires_at: i64,
    ) -> SQLResult<()> {
        conn.execute(
            "UPDATE remote_operations \
             SET to_commit = ?1, transfer_id = ?2, transfer_expires_at = ?3 WHERE id = ?4",
            params![to_commit, transfer_id, transfer_expires_at, self.id],
        )?;
        self.to_commit = Some(*to_commit);
        self.transfer_id = Some(transfer_id);
        self.transfer_expires_at = Some(transfer_expires_at);
        Ok(())
    }

    /// Marks the operation complete only after its graph and asset phases succeed.
    pub fn complete(&self, conn: &ConfigConnection) -> SQLResult<()> {
        if self.to_commit.is_none() || self.to_commit != self.assets_transfer_checkpoint {
            self.fail(conn)?;
            return Err(rusqlite::Error::InvalidQuery);
        }
        conn.execute(
            "UPDATE remote_operations SET completed_at = CURRENT_TIMESTAMP WHERE id = ?1",
            [self.id],
        )?;
        Ok(())
    }

    pub fn fail(&self, conn: &ConfigConnection) -> SQLResult<()> {
        conn.execute(
            "UPDATE remote_operations SET failed_at = CURRENT_TIMESTAMP WHERE id = ?1",
            [self.id],
        )?;
        Ok(())
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, ModelSelect)]
#[model_select(table = "defaults", history = false)]
pub struct Defaults {
    pub id: i64,
    pub collection_name: Option<String>,
    pub remote_name: Option<String>,
    pub current_branch_name: Option<String>,
    pub default_committer_name: String,
    pub default_committer_email: String,
}

impl Defaults {
    /// Set the default remote by name
    pub fn set_default_remote(
        conn: &ConfigConnection,
        remote_name: Option<&str>,
    ) -> Result<(), RemoteError> {
        // If setting a remote name, validate that it exists
        if let Some(name) = remote_name {
            Remote::get_by_name(conn, name)?;
        }

        let query = "UPDATE defaults SET remote_name = ?1 WHERE id = 1";
        let mut stmt = conn.prepare(query)?;
        stmt.execute(params![remote_name])?;
        Ok(())
    }

    pub fn set_default_remote_compat(
        conn: &ConfigConnection,
        remote_name: Option<&str>,
    ) -> SQLResult<()> {
        let query = "UPDATE defaults SET remote_name = ?1 WHERE id = 1";
        let mut stmt = conn.prepare(query)?;
        stmt.execute(params![remote_name])?;
        Ok(())
    }

    /// Get the default remote name
    pub fn get_default_remote(conn: &ConfigConnection) -> Option<String> {
        Defaults::select(conn)
            .id(1)
            .only(DefaultsSelect::RemoteName)
            .load()
            .ok()?
            .into_iter()
            .next()
            .flatten()
    }

    /// Helper method to get the default remote URL by resolving the remote name
    pub fn get_default_remote_url(conn: &ConfigConnection) -> Option<String> {
        if let Some(remote_name) = Self::get_default_remote(conn) {
            if let Some(remote) = Remote::get_by_name_optional(conn, &remote_name) {
                Some(remote.url)
            } else {
                None
            }
        } else {
            None
        }
    }

    pub fn set_current_branch(conn: &ConfigConnection, branch_name: Option<&str>) -> SQLResult<()> {
        let query = "UPDATE defaults SET current_branch_name = ?1 WHERE id = 1";
        let mut stmt = conn.prepare(query)?;
        stmt.execute(params![branch_name])?;
        Ok(())
    }

    pub fn get_current_branch(conn: &ConfigConnection) -> Option<String> {
        Defaults::select(conn)
            .id(1)
            .only(DefaultsSelect::CurrentBranchName)
            .load()
            .ok()?
            .into_iter()
            .next()
            .flatten()
    }

    pub fn set_default_committer_name(conn: &ConfigConnection, name: &str) -> SQLResult<()> {
        let query = "UPDATE defaults SET default_committer_name = ?1 WHERE id = 1";
        let mut stmt = conn.prepare(query)?;
        stmt.execute(params![name])?;
        Ok(())
    }

    pub fn get_default_committer_name(conn: &ConfigConnection) -> String {
        Defaults::select(conn)
            .id(1)
            .only(DefaultsSelect::DefaultCommitterName)
            .load()
            .ok()
            .and_then(|names| names.into_iter().next())
            .unwrap_or_else(|| GEN_DEFAULT_COMMITTER_NAME.to_string())
    }

    pub fn set_default_committer_email(conn: &ConfigConnection, email: &str) -> SQLResult<()> {
        let query = "UPDATE defaults SET default_committer_email = ?1 WHERE id = 1";
        let mut stmt = conn.prepare(query)?;
        stmt.execute(params![email])?;
        Ok(())
    }

    pub fn get_default_committer_email(conn: &ConfigConnection) -> String {
        Defaults::select(conn)
            .id(1)
            .only(DefaultsSelect::DefaultCommitterEmail)
            .load()
            .ok()
            .and_then(|emails| emails.into_iter().next())
            .unwrap_or_else(|| DEFAULT_COMMITTER_EMAIL.to_string())
    }

    /// Get the defaults record
    pub fn get(conn: &ConfigConnection) -> Option<Defaults> {
        Self::select(conn).id(1).load().ok()?.into_iter().next()
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        io::{Cursor, Write},
        path::PathBuf,
        slice::from_ref,
    };

    use tempfile::NamedTempFile;

    use super::*;
    use crate::{
        assets::{AssetRef, AssetRole, OperationAsset, OperationLog},
        file_types::FileTypes,
        history::{HistoryStore, dolt::DoltHistoryStore},
        test_helpers::setup_gen,
    };

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

        #[test]
        fn test_default_remote_functionality() {
            let context = setup_gen();
            let config_conn = context.config().conn();

            // Create test remotes
            Remote::create(config_conn, "origin", "https://example.com/repo.gen").unwrap();
            Remote::create(config_conn, "upstream", "https://upstream.com/repo.gen").unwrap();

            // Test getting default remote when none is set
            assert_eq!(Defaults::get_default_remote(config_conn), None);
            assert_eq!(Defaults::get_default_remote_url(config_conn), None);

            // Test setting default remote
            Defaults::set_default_remote(config_conn, Some("origin")).unwrap();
            assert_eq!(
                Defaults::get_default_remote(config_conn),
                Some("origin".to_string())
            );
            assert_eq!(
                Defaults::get_default_remote_url(config_conn),
                Some("https://example.com/repo.gen".to_string())
            );

            // Test changing default remote
            Defaults::set_default_remote(config_conn, Some("upstream")).unwrap();
            assert_eq!(
                Defaults::get_default_remote(config_conn),
                Some("upstream".to_string())
            );
            assert_eq!(
                Defaults::get_default_remote_url(config_conn),
                Some("https://upstream.com/repo.gen".to_string())
            );

            // Test clearing default remote
            Defaults::set_default_remote(config_conn, None).unwrap();
            assert_eq!(Defaults::get_default_remote(config_conn), None);
            assert_eq!(Defaults::get_default_remote_url(config_conn), None);

            // Test getting URL for non-existent remote (using the compat method to bypass validation)
            Defaults::set_default_remote_compat(config_conn, Some("nonexistent")).unwrap();
            assert_eq!(
                Defaults::get_default_remote(config_conn),
                Some("nonexistent".to_string())
            );
            assert_eq!(Defaults::get_default_remote_url(config_conn), None);
        }

        #[test]
        fn test_defaults_get() {
            let context = setup_gen();
            let config_conn = context.config().conn();

            // Test getting defaults record
            let defaults = Defaults::get(config_conn).unwrap();
            assert_eq!(defaults.id, 1);
            assert_eq!(defaults.collection_name, None);
            assert_eq!(defaults.remote_name, None);
            assert_eq!(defaults.current_branch_name, None);
            assert_eq!(defaults.default_committer_name, GEN_DEFAULT_COMMITTER_NAME);
            assert_eq!(defaults.default_committer_email, DEFAULT_COMMITTER_EMAIL);

            // Set a default remote and test again (using compat method to bypass validation)
            Defaults::set_default_remote_compat(config_conn, Some("test-remote")).unwrap();
            let defaults = Defaults::get(config_conn).unwrap();
            assert_eq!(defaults.remote_name, Some("test-remote".to_string()));
        }

        #[test]
        fn test_current_branch_round_trip() {
            let context = setup_gen();
            let config_conn = context.config().conn();

            assert_eq!(Defaults::get_current_branch(config_conn), None);

            Defaults::set_current_branch(config_conn, Some("feature")).unwrap();
            assert_eq!(
                Defaults::get_current_branch(config_conn),
                Some("feature".to_string())
            );

            Defaults::set_current_branch(config_conn, None).unwrap();
            assert_eq!(Defaults::get_current_branch(config_conn), None);
        }

        #[test]
        fn test_default_committer_round_trip() {
            let context = setup_gen();
            let config_conn = context.config().conn();

            assert_eq!(
                Defaults::get_default_committer_name(config_conn),
                GEN_DEFAULT_COMMITTER_NAME
            );
            assert_eq!(
                Defaults::get_default_committer_email(config_conn),
                DEFAULT_COMMITTER_EMAIL
            );

            Defaults::set_default_committer_name(config_conn, "Test User").unwrap();
            Defaults::set_default_committer_email(config_conn, "test@example.com").unwrap();

            assert_eq!(
                Defaults::get_default_committer_name(config_conn),
                "Test User".to_string()
            );
            assert_eq!(
                Defaults::get_default_committer_email(config_conn),
                "test@example.com".to_string()
            );
            let defaults = Defaults::get(config_conn).expect("should load defaults");
            assert_eq!(defaults.default_committer_name, "Test User");
            assert_eq!(defaults.default_committer_email, "test@example.com");
        }
    }

    #[cfg(test)]
    mod remote_operations {
        use gen_core::DoltHashId;
        use uuid::Uuid;

        use crate::{
            operations::{Remote, RemoteOperationKind, RemoteOperationRecord},
            test_helpers::setup_gen,
        };

        #[test]
        fn test_remote_operation_resumes_until_completed() {
            let context = setup_gen();
            let config = context.config().conn();
            Remote::create(config, "origin", "https://example.com/repo")
                .expect("should create remote");
            let original_commit = DoltHashId([1_u8; 20]);
            let advanced_commit = DoltHashId([2_u8; 20]);

            let mut baseline = RemoteOperationRecord::begin_or_resume(
                config,
                "origin",
                "main",
                RemoteOperationKind::Clone,
                Some(&original_commit),
            )
            .expect("should begin clone operation");
            assert_eq!(baseline.from_commit, Some(original_commit));
            assert_eq!(baseline.assets_transfer_checkpoint, None);
            baseline
                .set_destination(config, &original_commit)
                .expect("should record clone destination");
            baseline
                .advance_assets_transfer_checkpoint(config, &original_commit)
                .expect("should record clone asset checkpoint");
            baseline
                .complete(config)
                .expect("should complete clone operation");

            let operation = RemoteOperationRecord::begin_or_resume(
                config,
                "origin",
                "main",
                RemoteOperationKind::Pull,
                Some(&original_commit),
            )
            .expect("should begin pull operation");
            let mut resumed = RemoteOperationRecord::begin_or_resume(
                config,
                "origin",
                "main",
                RemoteOperationKind::Pull,
                Some(&advanced_commit),
            )
            .expect("should resume pull operation");

            assert_eq!(resumed, operation);
            assert_eq!(resumed.from_commit, Some(original_commit));
            assert_eq!(resumed.assets_transfer_checkpoint, Some(original_commit));

            resumed
                .set_destination(config, &advanced_commit)
                .expect("should record pull destination");
            resumed
                .advance_assets_transfer_checkpoint(config, &advanced_commit)
                .expect("should record pull asset checkpoint");
            resumed
                .complete(config)
                .expect("should complete pull operation");
            let completed = RemoteOperationRecord::select(config)
                .get_by_id(resumed.id)
                .expect("should query completed pull operation")
                .expect("should refetch completed pull operation");
            assert!(
                completed.completed_at.is_some(),
                "completed_at should be set"
            );
            assert_eq!(completed.failed_at, None, "failed_at should remain unset");

            let next = RemoteOperationRecord::begin_or_resume(
                config,
                "origin",
                "main",
                RemoteOperationKind::Pull,
                Some(&advanced_commit),
            )
            .expect("should begin the next pull operation");
            assert_ne!(next.id, operation.id);
            assert_eq!(next.from_commit, Some(advanced_commit));
            assert_eq!(next.assets_transfer_checkpoint, Some(advanced_commit));
        }

        #[test]
        fn test_failed_graph_operation_does_not_resume() {
            let context = setup_gen();
            let config = context.config().conn();
            Remote::create(config, "origin", "https://example.com/repo")
                .expect("should create remote");
            let original_commit = DoltHashId([1_u8; 20]);

            let failed = RemoteOperationRecord::begin_or_resume(
                config,
                "origin",
                "main",
                RemoteOperationKind::Pull,
                Some(&original_commit),
            )
            .expect("should begin pull operation");
            failed.fail(config).expect("should fail pull operation");
            let next = RemoteOperationRecord::begin_or_resume(
                config,
                "origin",
                "main",
                RemoteOperationKind::Pull,
                Some(&original_commit),
            )
            .expect("should begin replacement pull operation");

            assert_ne!(next.id, failed.id);
        }

        #[test]
        fn test_remote_operation_cannot_complete_before_asset_checkpoint() {
            let context = setup_gen();
            let config = context.config().conn();
            Remote::create(config, "origin", "https://example.com/repo")
                .expect("should create remote");
            let destination_commit = DoltHashId([1_u8; 20]);
            let mut operation = RemoteOperationRecord::begin_or_resume(
                config,
                "origin",
                "main",
                RemoteOperationKind::Clone,
                None,
            )
            .expect("should begin clone operation");
            operation
                .set_destination(config, &destination_commit)
                .expect("should record graph destination");

            operation
                .complete(config)
                .expect_err("should require assets to reach graph destination");
            let failed = RemoteOperationRecord::select(config)
                .get_by_id(operation.id)
                .expect("should query failed clone operation")
                .expect("should refetch failed clone operation");
            assert!(failed.failed_at.is_some(), "failed_at should be set");
        }

        #[test]
        fn test_push_operation_resumes_transfer_lease() {
            let context = setup_gen();
            let config = context.config().conn();
            Remote::create(config, "origin", "https://example.com/repo")
                .expect("should create remote");
            let destination_commit = DoltHashId([3_u8; 20]);
            let transfer_id = Uuid::from_u128(7);
            let transfer_expires_at = 1_900_000_000;
            let mut operation = RemoteOperationRecord::begin_or_resume(
                config,
                "origin",
                "main",
                RemoteOperationKind::Push,
                None,
            )
            .expect("should begin push operation");
            operation
                .set_push_destination(
                    config,
                    &destination_commit,
                    transfer_id,
                    transfer_expires_at,
                )
                .expect("should record push destination and lease");

            let mut resumed = RemoteOperationRecord::begin_or_resume(
                config,
                "origin",
                "main",
                RemoteOperationKind::Push,
                None,
            )
            .expect("should resume push operation");

            assert_eq!(resumed.to_commit.as_ref(), Some(&destination_commit));
            assert_eq!(resumed.transfer_id, Some(transfer_id));
            assert_eq!(resumed.transfer_expires_at, Some(transfer_expires_at));
            resumed
                .advance_assets_transfer_checkpoint(config, &destination_commit)
                .expect("should record completed push assets");
            resumed
                .complete(config)
                .expect("should complete push operation");
        }
    }

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

        #[test]
        fn test_validate_remote_name() {
            // Valid names
            assert!(Remote::validate_name("origin").is_ok());
            assert!(Remote::validate_name("my-remote").is_ok());
            assert!(Remote::validate_name("remote_1").is_ok());
            assert!(Remote::validate_name("test123").is_ok());

            // Invalid names
            assert!(Remote::validate_name("").is_err());
            assert!(Remote::validate_name("remote with spaces").is_err());
            assert!(Remote::validate_name("remote@special").is_err());
            assert!(Remote::validate_name("remote.dot").is_err());
        }

        #[test]
        fn test_validate_url() {
            // Valid URLs
            assert!(Remote::validate_url("https://genhub.bio/user/repo.gen").is_ok());
            assert!(Remote::validate_url("http://example.com/repo").is_ok());
            assert!(Remote::validate_url("ssh://git@genhub.bio/user/repo.gen").is_ok());
            assert!(Remote::validate_url("/path/to/local/repo").is_ok());
            assert!(Remote::validate_url("user@host:path/to/repo").is_ok());

            // Invalid URLs
            assert!(Remote::validate_url("").is_err());
            assert!(Remote::validate_url("not-a-url").is_err());

            assert!(Remote::validate_url("ftp://invalid-protocol.com").is_err());
        }
    }

    mod remote_branch {
        use super::*;

        #[test]
        fn test_remote_branch_set_remote_valid() {
            let context = setup_gen();
            let config_conn = context.config().conn();

            Remote::create(config_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
            let result =
                RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("origin"));
            assert!(result.is_ok());
            assert_eq!(
                RemoteBranch::get_remote(config_conn, "test_branch"),
                Some("origin".to_string())
            );
        }

        #[test]
        fn test_remote_branch_set_remote_nonexistent() {
            let context = setup_gen();
            let config_conn = context.config().conn();

            let result =
                RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("nonexistent"));
            assert_eq!(
                result,
                Err(RemoteError::RemoteNotFound("nonexistent".to_string()))
            );
            assert_eq!(RemoteBranch::get_remote(config_conn, "test_branch"), None);
        }

        #[test]
        fn test_remote_branch_clear_remote() {
            let context = setup_gen();
            let config_conn = context.config().conn();

            Remote::create(config_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
            RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("origin")).unwrap();
            assert_eq!(
                RemoteBranch::get_remote(config_conn, "test_branch"),
                Some("origin".to_string())
            );
            RemoteBranch::set_remote_validated(config_conn, "test_branch", None).unwrap();
            assert_eq!(RemoteBranch::get_remote(config_conn, "test_branch"), None);
        }

        #[test]
        fn test_remote_branch_clears_on_remote_delete() {
            let context = setup_gen();
            let config_conn = context.config().conn();

            Remote::create(config_conn, "origin", "https://genhub.bio/user/repo.gen").unwrap();
            RemoteBranch::set_remote_validated(config_conn, "test_branch_cascade", Some("origin"))
                .unwrap();
            assert_eq!(
                RemoteBranch::get_remote(config_conn, "test_branch_cascade"),
                Some("origin".to_string())
            );

            Remote::delete(config_conn, "origin").unwrap();
            assert_eq!(
                RemoteBranch::get_remote(config_conn, "test_branch_cascade"),
                None
            );
        }
    }

    #[test]
    fn test_remote_create() {
        let context = setup_gen();
        let config_conn = context.config().conn();

        // Test successful remote creation
        let remote = Remote::create(config_conn, "origin", "https://example.com/repo.gen").unwrap();
        assert_eq!(remote.name, "origin");
        assert_eq!(remote.url, "https://example.com/repo.gen");

        // Test duplicate name constraint violation
        let result = Remote::create(config_conn, "origin", "https://different.com/repo.gen");
        assert!(result.is_err());
    }

    #[test]
    fn test_remote_get_by_name() {
        let context = setup_gen();
        let config_conn = context.config().conn();

        // Test getting non-existent remote
        let result = Remote::get_by_name_optional(config_conn, "nonexistent");
        assert!(result.is_none());

        // Create a remote and test retrieval
        Remote::create(config_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
        let result = Remote::get_by_name_optional(config_conn, "upstream");
        assert!(result.is_some());
        let remote = result.unwrap();
        assert_eq!(remote.name, "upstream");
        assert_eq!(remote.url, "https://upstream.com/repo.gen");
    }

    #[test]
    fn test_remote_list_all() {
        let context = setup_gen();
        let config_conn = context.config().conn();

        // Test empty list
        let remotes = Remote::list_all(config_conn);
        assert!(remotes.is_empty());

        // Create multiple remotes
        Remote::create(config_conn, "origin", "https://origin.com/repo.gen").unwrap();
        Remote::create(config_conn, "upstream", "https://upstream.com/repo.gen").unwrap();
        Remote::create(config_conn, "fork", "https://fork.com/repo.gen").unwrap();

        // Test list returns all remotes in alphabetical order
        let remotes = Remote::list_all(config_conn);
        assert_eq!(remotes.len(), 3);
        assert_eq!(remotes[0].name, "fork");
        assert_eq!(remotes[1].name, "origin");
        assert_eq!(remotes[2].name, "upstream");
    }

    #[test]
    fn test_remote_delete() {
        let context = setup_gen();
        let config_conn = context.config().conn();

        // Create a remote
        Remote::create(config_conn, "temp", "https://temp.com/repo.gen").unwrap();

        // Verify it exists
        let remote = Remote::get_by_name_optional(config_conn, "temp");
        assert!(remote.is_some());

        // Delete the remote
        let result = Remote::delete(config_conn, "temp");
        assert!(result.is_ok());

        // Verify it's gone
        let remote = Remote::get_by_name_optional(config_conn, "temp");
        assert!(remote.is_none());

        // Test deleting non-existent remote (should return error)
        let result = Remote::delete(config_conn, "nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_remote_delete_with_remote_branch_associations() {
        let context = setup_gen();
        let config_conn = context.config().conn();

        Remote::create(config_conn, "test_remote", "https://test.com/repo.gen").unwrap();
        RemoteBranch::set_remote_validated(config_conn, "test_branch", Some("test_remote"))
            .unwrap();
        assert_eq!(
            RemoteBranch::get_remote(config_conn, "test_branch"),
            Some("test_remote".to_string())
        );

        let result = Remote::delete(config_conn, "test_remote");
        assert!(result.is_ok());
        assert_eq!(RemoteBranch::get_remote(config_conn, "test_branch"), None);
        let remote = Remote::get_by_name_optional(config_conn, "test_remote");
        assert!(remote.is_none());
    }

    #[test]
    fn test_calculate_stream_hash() {
        let content = b"Hello, World!";
        let cursor = Cursor::new(content);
        let hash = calculate_stream_hash(cursor).unwrap();

        assert_eq!(hash.len(), 32);

        // Test consistency - same content should produce same hash
        let cursor2 = Cursor::new(content);
        let hash2 = calculate_stream_hash(cursor2).unwrap();
        assert_eq!(hash, hash2);

        // Test different content produces different hash
        let different_content = b"Hello, World!!";
        let cursor3 = Cursor::new(different_content);
        let hash3 = calculate_stream_hash(cursor3).unwrap();
        assert_ne!(hash, hash3);
    }

    #[test]
    fn test_calculate_file_checksum() {
        let mut temp_file = NamedTempFile::new().unwrap();
        let content = b"Test file content for checksum calculation";
        temp_file.write_all(content).unwrap();
        temp_file.flush().unwrap();

        let checksum = calculate_file_checksum(temp_file.path()).unwrap();

        assert_eq!(checksum.0.len(), 32);

        // Test consistency - same file should produce same checksum
        let checksum2 = calculate_file_checksum(temp_file.path()).unwrap();
        assert_eq!(checksum, checksum2);

        // Test with different file content
        let mut temp_file2 = NamedTempFile::new().unwrap();
        let different_content = b"Different test file content";
        temp_file2.write_all(different_content).unwrap();
        temp_file2.flush().unwrap();

        let checksum3 = calculate_file_checksum(temp_file2.path()).unwrap();
        assert_ne!(checksum, checksum3);
    }

    #[test]
    fn test_calculate_file_checksum_nonexistent_file() {
        let result = calculate_file_checksum("/nonexistent/file/path");
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err().kind(),
            std::io::ErrorKind::NotFound
        ));
    }

    #[test]
    fn test_operation_file_new_infers_file_type_from_path() {
        let operation_file = OperationFile::new("fixtures/sample.gb");

        assert_eq!(operation_file.filename, "sample.gb");
        assert_eq!(operation_file.file_path, "fixtures/sample.gb");
        assert_eq!(operation_file.file_type, FileTypes::GenBank);
        assert_eq!(operation_file.checksum_override, None);
    }

    #[test]
    fn test_operation_file_storage_path_normalizes_absolute_repo_path() {
        let context = setup_gen();
        let repo_root = context.workspace().repo_root().unwrap();
        let absolute_path = repo_root.join("nested").join("sample.fa");

        fs::create_dir_all(absolute_path.parent().unwrap()).unwrap();
        fs::write(&absolute_path, b"sample").unwrap();

        let checksum = calculate_file_checksum(&absolute_path).unwrap();
        let storage_path = OperationFile::storage_file_path(
            context.workspace(),
            &absolute_path.to_string_lossy(),
            Some(&checksum),
        )
        .unwrap();

        assert_eq!(storage_path, "nested/sample.fa");
    }

    #[test]
    fn test_native_bgzf_generic_asset_keeps_bytes_and_source_path() {
        let context = setup_gen();
        let fixture_path =
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/simple.fa.bgz");
        let outside_dir = tempfile::tempdir().unwrap();
        let outside_path = outside_dir.path().join("opaque.bin");
        fs::copy(&fixture_path, &outside_path).unwrap();
        let outside_path_string = outside_path.to_string_lossy().to_string();

        let file_addition = FileAddition::prepare(
            context.workspace(),
            &outside_path_string,
            FileTypes::None,
            None,
        )
        .unwrap();
        let storage_path = OperationFile::storage_file_path(
            context.workspace(),
            &outside_path_string,
            file_addition.checksum.as_ref(),
        )
        .unwrap();
        let checksum = file_addition
            .checksum
            .expect("local file addition should have a checksum");
        let archived_path = context
            .workspace()
            .asset_dir()
            .unwrap()
            .join(file_addition.hashed_filename().unwrap());

        assert_eq!(storage_path, ".gen/outside_root/opaque.bin");
        assert_eq!(
            fs::read(archived_path).unwrap(),
            fs::read(fixture_path).unwrap()
        );
        assert_eq!(
            file_addition.asset_uri,
            LocalAssetUri::asset_uri(&format!(".gen/assets/{checksum}.none.bgz")),
        );
    }

    #[test]
    fn test_file_addition_prepare() {
        let context = setup_gen();
        let repo_root = context.workspace().repo_root().unwrap();

        let file1_path = repo_root.join("test_file.bin");
        let file_contents = b"\x00\xffgeneric binary asset\x80";
        fs::write(&file1_path, file_contents).unwrap();
        let file1_path_str = file1_path.to_string_lossy().to_string();
        let fa1 =
            FileAddition::prepare(context.workspace(), &file1_path_str, FileTypes::None, None)
                .expect("should prepare file addition");

        let archive_checksum = fa1.checksum.expect("should checksum generic BGZF asset");
        let materialized_checksum = fa1
            .materialized_checksum
            .expect("should checksum original generic bytes");
        let expected_asset_path = format!(".gen/assets/{archive_checksum}.none.bgz");
        assert_eq!(
            fa1.asset_uri,
            LocalAssetUri::asset_uri(&expected_asset_path)
        );
        assert_eq!(fa1.file_path(), expected_asset_path);
        assert_eq!(
            calculate_file_checksum(&file1_path).unwrap(),
            materialized_checksum
        );
        let archive_path = context.workspace().asset_dir().unwrap().join(
            fa1.hashed_filename()
                .expect("should derive generic BGZF filename"),
        );
        let mut decoded = noodles::bgzf::io::Reader::new(
            fs::File::open(archive_path).expect("should open generic BGZF asset"),
        );
        let mut decoded_contents = Vec::new();
        std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
            .expect("should decode generic BGZF asset");
        assert_eq!(decoded_contents, file_contents);

        for (file_type, filename) in [
            (FileTypes::Changeset, "generic_changeset.dat"),
            (FileTypes::Tabix, "generic_tabix.dat"),
        ] {
            let source_path = repo_root.join(filename);
            fs::write(&source_path, file_contents).expect("should write generic binary asset");
            let addition = FileAddition::prepare(
                context.workspace(),
                source_path
                    .to_str()
                    .expect("should encode generic asset path"),
                file_type,
                None,
            )
            .expect("should archive formerly excluded file type as BGZF");
            let archive_path = context.workspace().asset_dir().unwrap().join(
                addition
                    .hashed_filename()
                    .expect("should derive generic archive filename"),
            );
            let mut decoded = noodles::bgzf::io::Reader::new(
                fs::File::open(archive_path).expect("should open generic BGZF asset"),
            );
            let mut decoded_contents = Vec::new();
            std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
                .expect("should decode generic BGZF asset");

            assert!(
                addition
                    .asset_uri
                    .ends_with(&format!(".{}.bgz", FileTypes::suffix(file_type))),
                "{file_type:?} should use its BGZF archive suffix"
            );
            assert_eq!(decoded_contents, file_contents);
        }

        let relative1_id =
            LocalAssetUri::generate_file_addition_id(Some(&archive_checksum), &fa1.asset_uri);

        assert_eq!(fa1.id, relative1_id);
        assert!(
            context
                .workspace()
                .asset_dir()
                .unwrap()
                .join(
                    fa1.hashed_filename()
                        .expect("local file addition should have a checksum"),
                )
                .exists()
        );

        // Second call with same file should return the same FileAddition
        let fa2 =
            FileAddition::prepare(context.workspace(), &file1_path_str, FileTypes::None, None)
                .expect("should prepare same file addition");

        assert_eq!(fa1, fa2);

        let file2_path = repo_root.join("nested").join("file2.txt");
        fs::create_dir_all(file2_path.parent().unwrap()).unwrap();
        fs::write(&file2_path, file_contents).unwrap();
        let file2_path_str = file2_path.to_string_lossy().to_string();

        let fa3 =
            FileAddition::prepare(context.workspace(), &file2_path_str, FileTypes::None, None)
                .expect("should prepare matching file addition");

        assert_eq!(fa1.id, fa3.id);

        fs::write(&file1_path, b"new content").unwrap();
        let fa1_new =
            FileAddition::prepare(context.workspace(), &file1_path_str, FileTypes::None, None)
                .expect("should prepare updated file addition");

        assert_ne!(fa1.id, fa1_new.id);

        let outside_dir = tempfile::tempdir().unwrap();
        let outside_file = outside_dir.path().join("opaque.bin");
        fs::write(&outside_file, file_contents).unwrap();
        let outside_path = outside_file.to_string_lossy().to_string();

        let outside =
            FileAddition::prepare(context.workspace(), &outside_path, FileTypes::None, None)
                .expect("should prepare external file addition");

        assert!(outside.asset_uri.ends_with(".none.bgz"));
        assert!(
            context
                .workspace()
                .asset_dir()
                .unwrap()
                .join(
                    outside
                        .hashed_filename()
                        .expect("local file addition should have a checksum"),
                )
                .exists()
        );
    }

    #[test]
    fn test_plain_local_file_is_archived_as_bgzf_with_both_checksums() {
        let context = setup_gen();
        let repo_root = context.workspace().repo_root().unwrap();
        let source_path = repo_root.join("input.vcf");
        let source_contents = b"##fileformat=VCFv4.3\n#CHROM\tPOS\tID\nchr1\t1\t.\n";
        fs::write(&source_path, source_contents).expect("should write plain VCF source");

        let file_addition = FileAddition::prepare(
            context.workspace(),
            source_path.to_str().expect("should encode VCF source path"),
            FileTypes::VCF,
            None,
        )
        .expect("should archive plain VCF as BGZF");
        let archive_checksum = file_addition
            .checksum
            .expect("should calculate archive checksum");
        let materialized_checksum = file_addition
            .materialized_checksum
            .expect("should calculate source checksum");
        let asset_dir = context.workspace().asset_dir().unwrap();
        let archive_path = asset_dir.join(
            file_addition
                .hashed_filename()
                .expect("should derive content-addressed archive filename"),
        );

        assert_eq!(
            file_addition.asset_uri,
            LocalAssetUri::asset_uri(&format!(".gen/assets/{archive_checksum}.vcf.bgz"))
        );
        assert_eq!(
            calculate_file_checksum(&source_path).unwrap(),
            materialized_checksum
        );
        assert_eq!(
            calculate_file_checksum(&archive_path).unwrap(),
            archive_checksum
        );
        assert_ne!(archive_checksum, materialized_checksum);
        assert_eq!(fs::read(&source_path).unwrap(), source_contents);
        let verified_addition = FileAddition::prepare(
            context.workspace(),
            source_path.to_str().expect("should encode VCF source path"),
            FileTypes::VCF,
            Some(materialized_checksum),
        )
        .expect("should verify the supplied checksum against the plain source bytes");
        assert_eq!(verified_addition.checksum, Some(archive_checksum));

        let mut decoded = noodles::bgzf::io::Reader::new(
            fs::File::open(&archive_path).expect("should open retained BGZF archive"),
        );
        let mut decoded_contents = Vec::new();
        std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
            .expect("should decode retained BGZF archive");
        assert_eq!(decoded_contents, source_contents);
    }

    #[test]
    fn test_index_suffixes_remain_raw_for_direct_index_readers() {
        let context = setup_gen();
        let repo_root = context.workspace().repo_root().unwrap();
        let asset_dir = context.workspace().asset_dir().unwrap();
        let index_contents = b"index bytes\n";

        for (index, extension) in ["fai", "gzi", "tbi", "csi", "bai", "BAI"]
            .iter()
            .enumerate()
        {
            // Distinct stems keep case variants separate on case-insensitive filesystems.
            let filename = format!("reference_{index}.fa.{extension}");
            let source_path = repo_root.join(&filename);
            fs::write(&source_path, index_contents).expect("should write raw index file");

            let addition = FileAddition::prepare(
                context.workspace(),
                source_path.to_str().expect("should encode index path"),
                FileTypes::Fasta,
                None,
            )
            .expect("should retain index bytes without BGZF encoding");
            let archived_path = asset_dir.join(
                addition
                    .hashed_filename()
                    .expect("should derive retained index filename"),
            );
            let source_checksum = calculate_file_checksum(&source_path).unwrap();
            let archived_checksum = calculate_file_checksum(&archived_path).unwrap();
            let storage_path = OperationFile::storage_file_path(
                context.workspace(),
                source_path.to_str().expect("should encode index path"),
                addition.checksum.as_ref(),
            )
            .expect("should preserve the index sidecar path");

            assert_eq!(addition.materialized_checksum, None);
            assert_eq!(addition.checksum.as_ref(), Some(&source_checksum));
            assert_eq!(archived_checksum, source_checksum);
            assert_eq!(fs::read(archived_path).unwrap(), index_contents);
            assert!(addition.asset_uri.ends_with(&format!(".fa.{extension}")));
            assert_eq!(storage_path, filename);
        }
    }

    #[test]
    fn test_bam_bgzf_asset_is_retained_byte_identically() {
        let context = setup_gen();
        let repo_root = context.workspace().repo_root().unwrap();
        let source_path = repo_root.join("minimal.bam");

        let mut bam_contents = b"BAM\x01".to_vec();
        bam_contents.extend_from_slice(&0_i32.to_le_bytes());
        bam_contents.extend_from_slice(&0_i32.to_le_bytes());

        let mut bgzf_writer = noodles::bgzf::io::writer::Builder::default()
            .set_compression_level(noodles::bgzf::io::writer::CompressionLevel::NONE)
            .build_from_writer(Vec::new());
        bgzf_writer
            .write_all(&bam_contents)
            .expect("should write minimal BAM bytes");
        let bam_bgzf_contents = bgzf_writer
            .finish()
            .expect("should finish BGZF-compressed BAM bytes");
        fs::write(&source_path, &bam_bgzf_contents).expect("should write BGZF BAM asset");

        let addition = FileAddition::prepare(
            context.workspace(),
            source_path.to_str().expect("should encode BAM path"),
            FileTypes::None,
            None,
        )
        .expect("should retain BGZF-compressed BAM bytes");
        let checksum = addition
            .checksum
            .as_ref()
            .expect("should checksum the retained BAM asset");
        let archived_path = context
            .workspace()
            .asset_dir()
            .unwrap()
            .join(addition.hashed_filename().unwrap());
        let storage_path = OperationFile::storage_file_path(
            context.workspace(),
            source_path.to_str().expect("should encode BAM path"),
            Some(checksum),
        )
        .expect("should preserve the BAM logical path");

        assert_eq!(addition.materialized_checksum, None);
        assert_eq!(calculate_file_checksum(&source_path).unwrap(), *checksum);
        assert_eq!(calculate_file_checksum(&archived_path).unwrap(), *checksum);
        assert_eq!(fs::read(archived_path).unwrap(), bam_bgzf_contents);
        assert_eq!(storage_path, "minimal.bam");

        let mut decoded = noodles::bgzf::io::Reader::new(Cursor::new(bam_bgzf_contents));
        let mut decoded_contents = Vec::new();
        std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
            .expect("should decode the retained BAM bytes");
        assert_eq!(decoded_contents, bam_contents);
    }

    #[test]
    fn test_existing_gzip_generic_file_is_normalized_as_bgzf() {
        let context = setup_gen();
        let repo_root = context.workspace().repo_root().unwrap();
        let asset_dir = context.workspace().asset_dir().unwrap();
        let source_path = repo_root.join("opaque.bin.gz");
        let decoded_source_contents = b"\x00\xffgeneric gzip asset\x80";
        let mut gzip_encoder =
            flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        gzip_encoder
            .write_all(decoded_source_contents)
            .expect("should write gzip asset content");
        let gzip_contents = gzip_encoder
            .finish()
            .expect("should finish gzip asset content");
        fs::write(&source_path, &gzip_contents).expect("should write compressed generic bytes");

        let source_checksum = calculate_file_checksum(&source_path).unwrap();
        let addition = FileAddition::prepare(
            context.workspace(),
            source_path
                .to_str()
                .expect("should encode compressed generic path"),
            FileTypes::None,
            Some(source_checksum),
        )
        .expect("should normalize ordinary gzip generic asset as BGZF");
        let archive_checksum = addition.checksum.expect("should checksum BGZF archive");
        let archived_path = asset_dir.join(
            addition
                .hashed_filename()
                .expect("should derive compressed generic filename"),
        );
        let mut decoded = noodles::bgzf::io::Reader::new(
            fs::File::open(&archived_path).expect("should open normalized generic archive"),
        );
        let mut decoded_contents = Vec::new();
        std::io::Read::read_to_end(&mut decoded, &mut decoded_contents)
            .expect("should decode normalized generic archive");

        assert_eq!(addition.materialized_checksum, None);
        assert_eq!(
            calculate_file_checksum(archived_path).unwrap(),
            archive_checksum
        );
        assert_eq!(decoded_contents, decoded_source_contents);
        assert_eq!(fs::read(source_path).unwrap(), gzip_contents);
        assert!(addition.asset_uri.ends_with(".none.bgz"));
    }

    #[test]
    fn test_file_addition_prepare_http_uri() {
        let context = setup_gen();
        let asset_uri = "https://example.com/assets/reference.fa";

        let addition =
            FileAddition::prepare(context.workspace(), asset_uri, FileTypes::Fasta, None)
                .expect("should prepare HTTP file addition");

        assert_eq!(addition.asset_uri, asset_uri);
        assert_eq!(addition.file_path(), asset_uri);
        assert_eq!(addition.checksum, None);
        assert!(
            fs::read_dir(context.workspace().asset_dir().unwrap())
                .unwrap()
                .next()
                .is_none()
        );
    }

    #[test]
    fn test_file_addition_prepare_remote_uri() {
        let context = setup_gen();
        let asset_uri = "s3://bucket/reference.fa";
        let checksum = Sha256Hash::convert_str("remote S3 contents");

        let addition = FileAddition::prepare(
            context.workspace(),
            asset_uri,
            FileTypes::Fasta,
            Some(checksum),
        )
        .expect("should prepare remote file addition");

        assert_eq!(addition.asset_uri, asset_uri);
        assert_eq!(addition.file_path(), asset_uri);
        assert_eq!(addition.checksum, Some(checksum));
    }

    #[test]
    fn test_file_addition_rejects_incorrect_local_checksum_override() {
        let context = setup_gen();
        let path = context.workspace().repo_root().unwrap().join("asset.fa");
        fs::write(&path, "actual contents").expect("should write local asset");
        let file_path = path.to_str().expect("should encode local asset path");

        let error = FileAddition::prepare(
            context.workspace(),
            file_path,
            FileTypes::Fasta,
            Some(Sha256Hash::convert_str("different contents")),
        )
        .expect_err("should reject incorrect checksum override");

        assert!(
            matches!(error, FileAdditionError::ChecksumError(_)),
            "should report a checksum error: {error}"
        );
        assert!(
            error.to_string().contains(file_path),
            "checksum error should include the source path: {error}"
        );
        assert_eq!(
            fs::read_dir(context.workspace().asset_dir().unwrap())
                .expect("should read asset directory")
                .count(),
            0
        );
    }

    #[test]
    fn test_add_files_operation_does_not_read_remote_asset() {
        let context = setup_gen();
        let asset_uri = "http://127.0.0.1:1/asset.fa".to_string();
        let operation_file = OperationFile::new(&asset_uri);

        add_files_operation(
            &context,
            from_ref(&operation_file),
            Some("track remote reference"),
        )
        .expect("should track remote asset");

        let asset_refs =
            AssetRef::all(context.graph().conn()).expect("should load asset references");
        assert_eq!(asset_refs.len(), 1);
        assert_eq!(asset_refs[0].uri, asset_uri);
        assert_eq!(asset_refs[0].checksum, None);
    }

    #[test]
    fn test_add_files_operation_passes_remote_checksum_override() {
        let context = setup_gen();
        let asset_uri = "http://127.0.0.1:1/asset.fa";
        let checksum = Sha256Hash::convert_str("known remote contents");
        let operation_file = OperationFile::new(asset_uri).set_checksum_override(checksum);

        add_files_operation(
            &context,
            from_ref(&operation_file),
            Some("track checksummed remote reference"),
        )
        .expect("should track remote asset without reading it");

        let asset_refs =
            AssetRef::all(context.graph().conn()).expect("should load asset references");
        assert_eq!(asset_refs.len(), 1);
        assert_eq!(asset_refs[0].uri, asset_uri);
        assert_eq!(asset_refs[0].checksum, Some(checksum));
    }

    #[test]
    fn test_add_files_operation_stores_shared_unmodified_asset_once_across_operations() {
        let context = setup_gen();
        let graph_conn = context.graph().conn();
        let workspace = context.workspace();

        let repo_root = workspace.repo_root().unwrap();
        fs::write(repo_root.join("shared.txt"), "shared contents").unwrap();
        fs::write(repo_root.join("unique.txt"), "unique contents").unwrap();

        let _operation_1_hash =
            add_files_operation(&context, &[OperationFile::new("shared.txt")], Some("first"))
                .unwrap();
        let _operation_2_hash = add_files_operation(
            &context,
            &[
                OperationFile::new("shared.txt"),
                OperationFile::new("unique.txt"),
            ],
            Some("second"),
        )
        .unwrap();

        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
        operation_logs.sort_by_key(|operation_log| operation_log.created_on);
        let mut first_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[0].id);
        first_assets.sort_by_key(|asset| asset.asset_ref_id);
        let mut second_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[1].id);
        second_assets.sort_by_key(|asset| asset.asset_ref_id);

        assert_eq!(operation_logs[0].command, "first");
        assert_eq!(operation_logs[1].command, "second");
        assert_eq!(first_assets.len(), 1);
        assert_eq!(second_assets.len(), 2);
        assert!(
            second_assets
                .iter()
                .any(|asset| asset.asset_ref_id == first_assets[0].asset_ref_id)
        );

        let shared_asset = AssetRef::select(graph_conn)
            .get_by_id(first_assets[0].asset_ref_id)
            .expect("should query shared asset ref")
            .expect("should load shared asset ref");
        let unique_asset = second_assets
            .iter()
            .find(|asset| asset.asset_ref_id != first_assets[0].asset_ref_id)
            .and_then(|asset| {
                AssetRef::select(graph_conn)
                    .get_by_id(asset.asset_ref_id)
                    .expect("should query unique asset ref")
            })
            .expect("should load unique asset ref");

        let assets_dir = workspace.asset_dir().unwrap();
        let asset_names = fs::read_dir(&assets_dir)
            .unwrap()
            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
            .collect::<Vec<_>>();

        assert_eq!(asset_names.len(), 2);
        let shared_asset_name = <dyn AssetUri>::from_uri(&shared_asset.uri)
            .hashed_filename(&shared_asset.checksum.unwrap());
        let unique_asset_name = <dyn AssetUri>::from_uri(&unique_asset.uri)
            .hashed_filename(&unique_asset.checksum.unwrap());
        assert!(asset_names.contains(&shared_asset_name));
        assert!(asset_names.contains(&unique_asset_name));
    }

    #[test]
    fn test_add_files_operation_tracks_distinct_filenames_for_same_asset()
    -> Result<(), Box<dyn std::error::Error>> {
        let context = setup_gen();
        let graph_conn = context.graph().conn();

        let outside_dir = tempfile::tempdir()?;
        let alpha_path = outside_dir.path().join("alpha.fa");
        let beta_path = outside_dir.path().join("beta.fa");
        fs::write(&alpha_path, "shared contents")?;
        fs::write(&beta_path, "shared contents")?;

        add_files_operation(
            &context,
            &[
                OperationFile::new(alpha_path.to_string_lossy()),
                OperationFile::new(beta_path.to_string_lossy()),
            ],
            Some("same asset, different filenames"),
        )?;

        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
        asset_refs.sort_by(|left, right| left.name.cmp(&right.name));

        assert_eq!(
            asset_refs
                .iter()
                .map(|asset| asset.name.clone().unwrap_or_default())
                .collect::<Vec<_>>(),
            vec!["alpha.fa".to_string(), "beta.fa".to_string()],
        );
        assert_ne!(asset_refs[0].id, asset_refs[1].id);
        assert_eq!(asset_refs[0].checksum, asset_refs[1].checksum);
        Ok(())
    }

    #[test]
    fn test_add_files_operation_tracks_graph_asset_refs() {
        let context = setup_gen();
        let graph_conn = context.graph().conn();

        let repo_root = context.workspace().repo_root().unwrap();
        fs::write(repo_root.join("alpha.fa"), "AAAA").unwrap();
        fs::write(repo_root.join("beta.fa"), "BBBB").unwrap();

        let _operation_hash = add_files_operation(
            &context,
            &[
                OperationFile::new("alpha.fa"),
                OperationFile::new("beta.fa"),
            ],
            Some("import references"),
        )
        .unwrap();

        let mut asset_refs = AssetRef::all(graph_conn).expect("should load asset references");
        asset_refs.sort_by(|left, right| left.logical_path.cmp(&right.logical_path));
        let mut operation_logs = OperationLog::all(graph_conn).expect("should load operation logs");
        operation_logs.sort_by_key(|operation_log| operation_log.created_on);

        assert_eq!(asset_refs.len(), 2);
        assert_eq!(asset_refs[0].logical_path.as_deref(), Some("alpha.fa"));
        assert_eq!(asset_refs[0].name.as_deref(), Some("alpha.fa"));
        assert_eq!(asset_refs[0].role, AssetRole::Input);
        assert_eq!(asset_refs[1].logical_path.as_deref(), Some("beta.fa"));
        assert_eq!(asset_refs[1].name.as_deref(), Some("beta.fa"));
        assert_eq!(asset_refs[1].role, AssetRole::Input);
        assert_eq!(operation_logs.len(), 1);
        assert_eq!(operation_logs[0].operation_kind, OperationKind::AddFile);
        assert_eq!(operation_logs[0].command, "import references");
        let mut operation_assets = OperationAsset::by_log_id(graph_conn, &operation_logs[0].id);
        operation_assets.sort_by(|left, right| {
            left.role
                .as_str()
                .cmp(right.role.as_str())
                .then_with(|| left.asset_ref_id.cmp(&right.asset_ref_id))
        });
        assert_eq!(operation_assets.len(), 2);
        assert!(
            operation_assets
                .iter()
                .all(|asset| asset.role == AssetRole::Input)
        );
    }

    #[test]
    fn test_add_files_operation_records_history_without_config_db_rows() {
        let context = setup_gen();
        let graph_conn = context.graph().conn();
        let config_conn = context.config().conn();

        let repo_root = context.workspace().repo_root().unwrap();
        fs::write(repo_root.join("alpha.fa"), "AAAA").unwrap();

        let operation_hash = add_files_operation(
            &context,
            &[OperationFile::new("alpha.fa")],
            Some("import reference"),
        )
        .unwrap();

        let history_store = DoltHistoryStore::new(graph_conn);
        assert_eq!(
            history_store.current_head().unwrap(),
            Some(operation_hash),
            "add-file should commit through Dolt history"
        );
        let operation_count: i64 = config_conn
            .query_row(
                "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'operations'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(operation_count, 0);
    }
}