ai-model-vault 4.6.1

DEPRECATED - renamed to `ironvault`. This crate is no longer maintained; 4.6.1 is identical to 4.6.0 apart from this notice.
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
//! REST API route handlers.

use axum::extract::{ConnectInfo, Multipart, Path, Query, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{Html, IntoResponse, Response};
use axum::Json;
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::sync::Arc;

use crate::conversion::{ConversionOptions, ConversionPipeline};
use crate::formats::{ModelFormat, ModelMetadata};
use crate::traits::VaultState;

use super::auth;
use super::dashboard;
use super::error::ApiError;
use super::openapi;
use super::server::AppState;

// ── Health ───────────────────────────────────────────────────────────────────

#[derive(Serialize)]
pub struct HealthResponse {
    pub status: String,
    pub version: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vault_state: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_count: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uptime_seconds: Option<u64>,
}

/// GET /api/v1/health
///
/// Returns server health. Includes vault state when AppState is available.
pub async fn health(state: Option<State<Arc<AppState>>>) -> Json<HealthResponse> {
    let (vault_state_str, model_count) = if let Some(State(st)) = state {
        let vault = st.vault.read().await;
        let vs = vault.state();
        let mc = match &vs {
            VaultState::Locked { model_count, .. } => Some(*model_count),
            VaultState::Unlocked { model_count, .. } => Some(*model_count),
            _ => None,
        };
        (Some(vs.to_string()), mc)
    } else {
        (None, None)
    };

    Json(HealthResponse {
        status: "ok".into(),
        version: env!("CARGO_PKG_VERSION").into(),
        vault_state: vault_state_str,
        model_count,
        uptime_seconds: None,
    })
}

// ── Auth ─────────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct AuthRequest {
    passphrase: String,
}

#[derive(Serialize)]
pub struct AuthResponse {
    pub token: String,
    pub expires_in: u64,
}

/// POST /api/v1/auth/token
///
/// Unlocks the vault with the given passphrase and returns a JWT.
pub async fn auth_token(
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    State(state): State<Arc<AppState>>,
    Json(body): Json<AuthRequest>,
) -> Result<Json<AuthResponse>, ApiError> {
    // Rate-limit auth attempts per IP
    if !state.auth_rate_limiter.check(addr.ip()) {
        return Err(ApiError::rate_limited("Too many authentication attempts"));
    }

    // Attempt unlock
    {
        let mut vault = state.vault.write().await;
        vault
            .unlock(body.passphrase.into_bytes())
            .map_err(|_| ApiError::unauthorized("Invalid passphrase"))?;
    }

    let token = auth::create_token(&state.config.jwt_secret, state.config.token_expiry_secs)
        .map_err(|e| ApiError::internal(format!("Token creation failed: {e}")))?;

    Ok(Json(AuthResponse {
        token,
        expires_in: state.config.token_expiry_secs,
    }))
}

/// POST /api/v1/auth/logout
///
/// Revokes the presented token so it cannot be used again before it expires.
///
/// `auth::revoke_claims` existed but nothing ever called it: there was no way
/// to invalidate a leaked or finished token short of rotating `jwt_secret`,
/// which invalidates every other token at the same time.
pub async fn auth_logout(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let claims = require_auth(&headers, &state)?;

    auth::revoke_claims(&claims)
        .map_err(|e| ApiError::internal(format!("Could not persist revocation: {e}")))?;

    Ok(Json(serde_json::json!({
        "revoked": true,
        "jti": claims.jti,
    })))
}

// ── Models ───────────────────────────────────────────────────────────────────

#[derive(Serialize)]
pub struct ModelInfo {
    pub name: String,
    pub version_count: usize,
}

/// GET /api/v1/models
pub async fn list_models(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<Vec<ModelInfo>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let models: Vec<ModelInfo> = vault
        .list_models()
        .into_iter()
        .map(|name| {
            let version_count = vault.list_versions(&name).len();
            ModelInfo {
                name,
                version_count,
            }
        })
        .collect();
    Ok(Json(models))
}

/// GET /api/v1/models/:name
pub async fn get_model(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
) -> Result<Response, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;
    let data = vault.get_model(&name, None).map_err(ApiError::from)?;
    Ok((
        StatusCode::OK,
        [(header::CONTENT_TYPE, "application/octet-stream")],
        data,
    )
        .into_response())
}

/// POST /api/v1/models/:name  (multipart: file + format + description?)
pub async fn store_model(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
    mut multipart: Multipart,
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;

    let mut file_data: Option<Vec<u8>> = None;
    let mut format_str: Option<String> = None;
    let mut description: Option<String> = None;

    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|e| ApiError::bad_request(format!("Multipart error: {e}")))?
    {
        let field_name = field.name().unwrap_or("").to_string();
        match field_name.as_str() {
            "file" => {
                file_data = Some(
                    field
                        .bytes()
                        .await
                        .map_err(|e| ApiError::bad_request(format!("Read error: {e}")))?
                        .to_vec(),
                );
            }
            "format" => {
                format_str = Some(
                    field
                        .text()
                        .await
                        .map_err(|e| ApiError::bad_request(e.to_string()))?,
                );
            }
            "description" => {
                description = Some(
                    field
                        .text()
                        .await
                        .map_err(|e| ApiError::bad_request(e.to_string()))?,
                );
            }
            _ => {} // ignore unknown fields
        }
    }

    let data = file_data.ok_or_else(|| ApiError::bad_request("Missing 'file' field"))?;
    let fmt = format_str.ok_or_else(|| ApiError::bad_request("Missing 'format' field"))?;
    // Accept both a format name ("PyTorch") and an extension ("pt"): storing a
    // Custom variant here would break conversion and diffing later.
    let format = ModelFormat::from_stored(&fmt);

    let mut metadata = ModelMetadata::new(name.clone(), format);
    if let Some(desc) = description {
        metadata = metadata.with_description(desc);
    }

    let mut vault = state.vault.write().await;
    let version = vault
        .store_model(&name, data, metadata, None)
        .map_err(ApiError::from)?;

    Ok((
        StatusCode::CREATED,
        Json(serde_json::json!({
            "model": name,
            "version": version.version,
            "checkpoint_id": version.checkpoint_id,
            "size_bytes": version.size_bytes,
            "checksum": version.checksum_sha256,
        })),
    ))
}

// ── Versions ─────────────────────────────────────────────────────────────────

/// GET /api/v1/models/:name/versions
pub async fn list_versions(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;
    let versions = vault.list_versions(&name);
    if versions.is_empty() {
        return Err(ApiError::not_found(format!("Model '{}' not found", name)));
    }
    let vs: Vec<serde_json::Value> = versions
        .iter()
        .map(|v| {
            serde_json::json!({
                "version": v.version,
                "checkpoint_id": v.checkpoint_id,
                "timestamp": v.timestamp.to_rfc3339(),
                "format": v.format,
                "size_bytes": v.size_bytes,
                "compressed_size_bytes": v.compressed_size_bytes,
                "checksum_sha256": v.checksum_sha256,
                "parent_version": v.parent_version,
            })
        })
        .collect();
    Ok(Json(vs))
}

/// GET /api/v1/models/:name/versions/:version
pub async fn get_version(
    State(state): State<Arc<AppState>>,
    Path((name, version)): Path<(String, u32)>,
    headers: HeaderMap,
) -> Result<Response, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;
    let data = vault
        .get_model(&name, Some(version))
        .map_err(ApiError::from)?;
    Ok((
        StatusCode::OK,
        [(header::CONTENT_TYPE, "application/octet-stream")],
        data,
    )
        .into_response())
}

/// DELETE /api/v1/models/:name/versions/:version
pub async fn delete_version(
    State(state): State<Arc<AppState>>,
    Path((name, version)): Path<(String, u32)>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let mut vault = state.vault.write().await;
    let deleted = vault
        .delete_version(&name, version)
        .map_err(ApiError::from)?;
    if deleted {
        Ok(Json(
            serde_json::json!({ "deleted": true, "model": name, "version": version }),
        ))
    } else {
        Err(ApiError::not_found(format!(
            "Version {} not found for model '{}'",
            version, name
        )))
    }
}

/// GET /api/v1/models/:name/lineage/:version
pub async fn get_lineage(
    State(state): State<Arc<AppState>>,
    Path((name, version)): Path<(String, u32)>,
    headers: HeaderMap,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;
    let lineage = vault.get_lineage(&name, version);
    let vs: Vec<serde_json::Value> = lineage
        .iter()
        .map(|v| {
            serde_json::json!({
                "version": v.version,
                "checkpoint_id": v.checkpoint_id,
                "timestamp": v.timestamp.to_rfc3339(),
                "format": v.format,
                "size_bytes": v.size_bytes,
            })
        })
        .collect();
    Ok(Json(vs))
}

// ── Conversions ──────────────────────────────────────────────────────────────

#[derive(Serialize)]
pub struct ConversionInfo {
    pub name: String,
    pub source: String,
    pub target: String,
}

/// GET /api/v1/conversions
pub async fn list_conversions() -> Json<Vec<ConversionInfo>> {
    let pipeline = ConversionPipeline::with_builtins();
    let conversions: Vec<ConversionInfo> = pipeline
        .supported_conversions()
        .into_iter()
        .map(|(src, tgt, converter_name)| ConversionInfo {
            name: converter_name.to_string(),
            source: src.to_string(),
            target: tgt.to_string(),
        })
        .collect();
    Json(conversions)
}

#[derive(Deserialize)]
pub struct ConvertRequest {
    data_base64: String,
    source_format: String,
    target_format: String,
    quantization: Option<String>,
    opset_version: Option<u32>,
    #[serde(default)]
    validate: bool,
}

#[derive(Serialize)]
pub struct ConvertResponse {
    /// True when `data_base64` holds real target-format bytes.
    ///
    /// False when the conversion needs external tooling: `data_base64` is then
    /// `null` and `plan` describes the steps to run. Clients must check this
    /// before writing the payload to a file — otherwise they produce a file
    /// with the target extension and the wrong contents.
    pub converted: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_base64: Option<String>,
    /// Instructions for performing this conversion with external tooling.
    /// Present only when `converted` is false.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan: Option<serde_json::Value>,
    pub source_format: String,
    pub target_format: String,
    pub conversion_path: Vec<String>,
    pub input_size: u64,
    pub output_size: u64,
    pub validation: Option<serde_json::Value>,
}

/// POST /api/v1/convert
pub async fn convert(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<ConvertRequest>,
) -> Result<Json<ConvertResponse>, ApiError> {
    let _claims = require_auth(&headers, &state)?;

    let data = B64
        .decode(&body.data_base64)
        .map_err(|e| ApiError::bad_request(format!("Invalid base64: {e}")))?;

    let src = parse_format(&body.source_format)?;
    let tgt = parse_format(&body.target_format)?;

    let opts = ConversionOptions {
        quantization: body.quantization,
        opset_version: body.opset_version,
        validate: body.validate,
        ..ConversionOptions::default()
    };

    let pipeline = ConversionPipeline::with_builtins();
    let result = pipeline
        .convert(&data, &src, &tgt, &opts, None)
        .map_err(ApiError::from)?;

    let validation = result.validation.as_ref().map(|r| {
        serde_json::json!({
            "passed": r.passed,
            "checks": r.checks.iter().map(|c| serde_json::json!({
                "name": c.name,
                "passed": c.passed,
                "message": c.message,
            })).collect::<Vec<_>>()
        })
    });

    let converted = !result.is_plan();

    Ok(Json(ConvertResponse {
        converted,
        data_base64: converted.then(|| B64.encode(&result.data)),
        plan: result.plan.clone(),
        source_format: result.source_format.to_string(),
        target_format: result.target_format.to_string(),
        conversion_path: result
            .conversion_path
            .iter()
            .map(|f| f.to_string())
            .collect(),
        input_size: result.input_size,
        output_size: result.output_size,
        validation,
    }))
}

// ── Stats ────────────────────────────────────────────────────────────────────

#[derive(Serialize)]
pub struct StatsResponse {
    pub model_count: usize,
    pub total_versions: usize,
    pub total_size_bytes: u64,
    pub file_count: usize,
}

/// GET /api/v1/stats
pub async fn stats(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<StatsResponse>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let s = vault.get_stats().map_err(ApiError::from)?;
    Ok(Json(StatsResponse {
        model_count: s.model_count,
        total_versions: s.total_versions,
        total_size_bytes: s.total_size_bytes,
        file_count: s.file_count,
    }))
}

// ── Audit ────────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct AuditQuery {
    limit: Option<usize>,
}

/// GET /api/v1/audit
///
/// Returns audit log entries. Admins see all events; Operators and Viewers
/// cannot see `SecurityViolation`, `IntegrityFailure`, or `AuthFailure` events.
pub async fn audit_log(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Query(q): Query<AuditQuery>,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let claims = require_auth(&headers, &state)?;

    // Read the audit log file from the vault config path
    let vault = state.vault.read().await;
    let audit_path = vault.get_config().get_audit_log_path();

    if !audit_path.exists() {
        return Ok(Json(vec![]));
    }

    let contents =
        std::fs::read_to_string(&audit_path).map_err(|e| ApiError::internal(e.to_string()))?;

    let mut entries: Vec<serde_json::Value> = contents
        .lines()
        .filter_map(|line| serde_json::from_str(line).ok())
        .collect();

    // Role-based filtering: non-admin roles cannot see security-sensitive events
    if claims.role != super::auth::Role::Admin {
        entries.retain(|entry| !is_security_event(entry));
    }

    let limited = if let Some(n) = q.limit {
        entries.into_iter().take(n).collect()
    } else {
        entries
    };

    Ok(Json(limited))
}

// ── Observability ─────────────────────────────────────────────────────────────

/// GET /api/v1/metrics
///
/// Returns vault metrics: state, model counts, operation counters,
/// storage statistics, and compliance status.
pub async fn metrics(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vs = vault.state();
    let stats = vault.get_stats().map_err(ApiError::from)?;

    Ok(Json(serde_json::json!({
        "vault_state": vs.to_string(),
        "models_count": stats.model_count,
        "versions_count": stats.total_versions,
        "storage_bytes": stats.total_size_bytes,
        "file_count": stats.file_count,
        "version": env!("CARGO_PKG_VERSION"),
        "healthy": true,
    })))
}

#[derive(Deserialize)]
pub struct EventsQuery {
    /// Maximum number of events to return.
    limit: Option<usize>,
    /// Filter by event type (e.g. "ModelStored", "VaultUnlocked").
    #[serde(rename = "type")]
    event_type: Option<String>,
}

/// GET /api/v1/events
///
/// Returns audit events from the vault's audit log, with optional
/// filtering by type and limit. Events are returned newest-first.
/// Non-admin roles cannot see security-sensitive events.
pub async fn events(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Query(q): Query<EventsQuery>,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let claims = require_auth(&headers, &state)?;

    let vault = state.vault.read().await;
    let audit_path = vault.get_config().get_audit_log_path();

    if !audit_path.exists() {
        return Ok(Json(vec![]));
    }

    let contents =
        std::fs::read_to_string(&audit_path).map_err(|e| ApiError::internal(e.to_string()))?;

    let mut entries: Vec<serde_json::Value> = contents
        .lines()
        .filter_map(|line| serde_json::from_str(line).ok())
        .collect();

    // Role-based filtering: non-admin roles cannot see security-sensitive events
    if claims.role != super::auth::Role::Admin {
        entries.retain(|entry| !is_security_event(entry));
    }

    // Filter by event type if specified
    if let Some(ref et) = q.event_type {
        let et_lower = et.to_lowercase();
        entries.retain(|entry| {
            entry
                .get("action")
                .and_then(|a| a.as_str())
                .map(|a| a.to_lowercase().contains(&et_lower))
                .unwrap_or(false)
                || entry
                    .get("type")
                    .and_then(|t| t.as_str())
                    .map(|t| t.to_lowercase().contains(&et_lower))
                    .unwrap_or(false)
        });
    }

    // Return newest first
    entries.reverse();

    // Apply limit
    if let Some(n) = q.limit {
        entries.truncate(n);
    }

    Ok(Json(entries))
}

// ── OpenAPI & Dashboard ──────────────────────────────────────────────────────

/// GET /api/v1/openapi.json
pub async fn openapi_json() -> Json<serde_json::Value> {
    Json(openapi::openapi_spec())
}

/// GET /  — serves the embedded web dashboard
pub async fn dashboard_index() -> Html<&'static str> {
    Html(dashboard::dashboard_html())
}

// ── Model Cards ──────────────────────────────────────────────────────────────

/// GET /api/v1/models/:name/card
///
/// Generate a model card for the given model using vault metadata.
pub async fn get_model_card(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;

    // Verify model exists
    let versions = vault.list_versions(&name);
    if versions.is_empty() {
        return Err(ApiError::not_found(format!("Model '{}' not found", name)));
    }

    let latest = &versions[versions.len() - 1];
    let details = crate::model_card::ModelDetails {
        name: name.clone(),
        version: format!("v{}", latest.version),
        description: latest
            .metadata
            .get("description")
            .cloned()
            .unwrap_or_default(),
        model_type: String::new(),
        architecture: String::new(),
        size: format!("{} bytes", latest.size_bytes),
        framework: latest
            .metadata
            .get("framework")
            .cloned()
            .unwrap_or_default(),
        format: latest.format.clone(),
        license: None,
        citation: None,
        developers: vec![],
        contact: None,
        repository: None,
        paper: None,
    };
    let intended_use = crate::model_card::IntendedUse {
        primary_uses: vec!["General-purpose AI model".to_string()],
        primary_users: vec![],
        out_of_scope_uses: vec![],
        use_case_examples: None,
    };

    let card = crate::model_card::ModelCard::new(details, intended_use);

    let json_str = card
        .to_json()
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let value: serde_json::Value =
        serde_json::from_str(&json_str).map_err(|e| ApiError::internal(e.to_string()))?;

    Ok(Json(value))
}

/// POST /api/v1/models/:name/card
///
/// Create (or overwrite) a custom model card from JSON.
/// Returns the rendered card re-serialized from the parsed input.
pub async fn create_model_card(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
    Json(body): Json<serde_json::Value>,
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;

    // Verify model exists
    let vault = state.vault.read().await;
    let versions = vault.list_versions(&name);
    if versions.is_empty() {
        return Err(ApiError::not_found(format!("Model '{}' not found", name)));
    }

    let json_str = serde_json::to_string(&body)
        .map_err(|e| ApiError::bad_request(format!("Invalid JSON: {e}")))?;
    let card = crate::model_card::ModelCard::from_json(&json_str)
        .map_err(|e| ApiError::bad_request(format!("Invalid model card: {e}")))?;

    let roundtrip = card
        .to_json()
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let value: serde_json::Value =
        serde_json::from_str(&roundtrip).map_err(|e| ApiError::internal(e.to_string()))?;

    Ok((StatusCode::CREATED, Json(value)))
}

// ── Compliance ───────────────────────────────────────────────────────────────

/// GET /api/v1/compliance
///
/// Run FIPS 140-3, CVE, MITRE ATT&CK, and CMMC 2.0 compliance checks.
pub async fn compliance(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;

    let checker = crate::compliance::ComplianceChecker::new();
    let status = checker
        .run_all_checks()
        .map_err(|e| ApiError::internal(e.to_string()))?;

    Ok(Json(serde_json::json!({
        "fips_140_3": status.fips_140_3,
        "cve_scan_passed": status.cve_scan_passed,
        "mitre_attack_aligned": status.mitre_attack_aligned,
        "cmmc_level": status.cmmc_level,
        "all_passed": status.violations.is_empty(),
        "violations": status.violations.iter().map(|v| serde_json::json!({
            "standard": v.standard,
            "control": v.control,
            "severity": v.severity,
            "description": v.description,
            "remediation": v.remediation,
        })).collect::<Vec<_>>(),
    })))
}

// ── RAG ──────────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct RagSearchRequest {
    query: String,
    limit: Option<usize>,
}

/// POST /api/v1/rag/search
///
/// Search the RAG document store.
pub async fn rag_search(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<RagSearchRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;

    if body.query.is_empty() || body.query.len() > 10_000 {
        return Err(ApiError::bad_request(
            "Query must be between 1 and 10,000 characters",
        ));
    }

    let vault = state.vault.read().await;
    let rag_path = vault.get_config().get_vault_path(None).join("rag");

    if !rag_path.exists() {
        return Ok(Json(
            serde_json::json!({ "results": [], "query": body.query }),
        ));
    }

    let kb_config = crate::rag::KnowledgeBaseConfig::default();
    let kb = crate::rag::KnowledgeBase::new("vault".to_string(), kb_config);
    let limit = body.limit.unwrap_or(10).min(100);
    // Without pre-computed embeddings, retrieve returns empty vec.
    // The endpoint is wired and ready for real embedding integration.
    let results = kb.retrieve(&[], Some(limit));

    Ok(Json(serde_json::json!({
        "query": body.query,
        "results": results.iter().map(|doc| serde_json::json!({
            "id": doc.id,
            "content": doc.content,
            "metadata": doc.metadata,
        })).collect::<Vec<_>>(),
    })))
}

#[derive(Deserialize)]
pub struct RagAddDocumentRequest {
    content: String,
    #[serde(default)]
    metadata: std::collections::HashMap<String, String>,
}

/// POST /api/v1/rag/documents
///
/// Add a document to the RAG knowledge base.
pub async fn rag_add_document(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<RagAddDocumentRequest>,
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
    let _claims = require_auth(&headers, &state)?;

    if body.content.is_empty() || body.content.len() > 1_000_000 {
        return Err(ApiError::bad_request(
            "Document content must be between 1 and 1,000,000 characters",
        ));
    }

    // Validate metadata keys/values
    for (k, v) in &body.metadata {
        if k.len() > 256 || v.len() > 4096 {
            return Err(ApiError::bad_request(
                "Metadata key max 256 chars, value max 4096 chars",
            ));
        }
    }

    let id = format!("doc_{}", uuid_v4_simple());

    let doc = crate::rag::Document {
        id: id.clone(),
        content: body.content.clone(),
        metadata: body.metadata.clone(),
        embedding: None,
        chunk_info: None,
    };

    let mut store = crate::rag::DocumentStore::new();
    store
        .add_document(doc)
        .map_err(|e| ApiError::internal(e.to_string()))?;

    // Acknowledge — note: in-memory store won't persist across requests,
    // but this wires the endpoint and demonstrates the API contract.
    let _ = state.vault.read().await; // verify vault is accessible
    Ok((
        StatusCode::CREATED,
        Json(serde_json::json!({
            "id": id,
            "content_length": body.content.len(),
            "metadata_keys": body.metadata.keys().collect::<Vec<_>>(),
        })),
    ))
}

/// Generate a simple unique ID (timestamp + random suffix).
fn uuid_v4_simple() -> String {
    use std::time::SystemTime;
    let ts = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    format!("{:x}", ts)
}

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

/// Extract and verify the Bearer JWT from the Authorization header.
/// Returns the decoded [`Claims`] on success, for role-based access control.
fn require_auth(headers: &HeaderMap, state: &AppState) -> Result<super::auth::Claims, ApiError> {
    let auth_header = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .ok_or_else(|| ApiError::unauthorized("Missing Authorization header"))?;

    let token = auth_header
        .strip_prefix("Bearer ")
        .ok_or_else(|| ApiError::unauthorized("Invalid Authorization format (expected Bearer)"))?;

    // Reject tokens with invalid structure before verification
    if token.is_empty() || token.len() > 4096 || token.chars().any(|c| c.is_control()) {
        return Err(ApiError::unauthorized("Malformed token"));
    }

    auth::verify_token(token, &state.config.jwt_secret)
        .map_err(|_| ApiError::unauthorized("Invalid or expired token"))
}

/// Parse a format string into a ModelFormat.
fn parse_format(s: &str) -> Result<ModelFormat, ApiError> {
    let f = match s.to_lowercase().as_str() {
        "safetensors" => ModelFormat::Safetensors,
        "gguf" => ModelFormat::GGUF,
        "pytorch" | "pt" | "pth" => ModelFormat::PyTorch,
        "onnx" => ModelFormat::ONNX,
        "tensorrt" | "trt" => ModelFormat::TensorRT,
        "coreml" | "mlmodel" => ModelFormat::CoreML,
        "tflite" => ModelFormat::TFLite,
        "tensorflow" | "tf" | "pb" => ModelFormat::TensorFlow,
        "keras" => ModelFormat::Keras,
        "openvino" => ModelFormat::OpenVINO,
        "mlx" => ModelFormat::MLX,
        "hdf5" | "h5" => ModelFormat::HDF5,
        "numpy" | "npy" | "npz" => ModelFormat::NumPy,
        "pickle" | "pkl" => ModelFormat::Pickle,
        "mxnet" | "params" => ModelFormat::MXNet,
        "caffe" | "caffemodel" => ModelFormat::Caffe,
        "ncnn" | "param" => ModelFormat::NCNN,
        "mnn" => ModelFormat::MNN,
        "rknn" => ModelFormat::RKNN,
        "darknet" | "weights" => ModelFormat::Darknet,
        other => {
            return Err(ApiError::bad_request(format!(
                "Unsupported format: '{other}'"
            )));
        }
    };
    Ok(f)
}

/// Validate a model name: must be 1-128 ASCII alphanumeric, hyphens, underscores, dots.
fn validate_model_name(name: &str) -> Result<(), ApiError> {
    if name.is_empty() || name.len() > 128 {
        return Err(ApiError::bad_request("Model name must be 1-128 characters"));
    }
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
    {
        return Err(ApiError::bad_request(
            "Model name must contain only ASCII alphanumeric, hyphens, underscores, or dots",
        ));
    }
    Ok(())
}

// ── Tags ─────────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct TagAddRequest {
    pub tags: Vec<String>,
}

/// POST /api/v1/models/:name/tags
pub async fn add_tags(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
    Json(body): Json<TagAddRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut store =
        crate::tags::TagStore::new(&vault_path).map_err(|e| ApiError::internal(e.to_string()))?;
    store
        .add_tags(&name, &body.tags)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(
        serde_json::json!({ "model": name, "tags": body.tags }),
    ))
}

/// GET /api/v1/models/:name/tags
pub async fn get_tags(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let store =
        crate::tags::TagStore::new(&vault_path).map_err(|e| ApiError::internal(e.to_string()))?;
    let tags = store.get_tags(&name);
    Ok(Json(serde_json::json!({ "model": name, "tags": tags })))
}

/// DELETE /api/v1/models/:name/tags
pub async fn remove_tags(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
    Json(body): Json<TagAddRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut store =
        crate::tags::TagStore::new(&vault_path).map_err(|e| ApiError::internal(e.to_string()))?;
    store
        .remove_tags(&name, &body.tags)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(
        serde_json::json!({ "model": name, "removed": body.tags }),
    ))
}

// ── Search ───────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct SearchRequest {
    pub query: Option<String>,
    pub tags: Option<Vec<String>>,
}

/// POST /api/v1/search
pub async fn search_models(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<SearchRequest>,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let store =
        crate::tags::TagStore::new(&vault_path).map_err(|e| ApiError::internal(e.to_string()))?;
    let sq = crate::tags::SearchQuery {
        tags: body.tags.unwrap_or_default(),
        name_pattern: body.query,
        annotations: vec![],
    };
    let known_models = vault.list_models();
    let results = store.search(&sq, &known_models);
    let out: Vec<serde_json::Value> = results
        .iter()
        .map(|r| {
            serde_json::json!({
                "model": r.model,
                "tags": r.tags,
                "annotations": r.annotations,
            })
        })
        .collect();
    Ok(Json(out))
}

// ── ACL ──────────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct AclGrantRequest {
    pub principal: String,
    pub role: String,
}

/// POST /api/v1/acl
pub async fn acl_grant(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<AclGrantRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut guard = crate::access_control::AclGuard::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let role: crate::access_control::Role = body
        .role
        .parse()
        .map_err(|e: crate::error::VaultError| ApiError::bad_request(e.to_string()))?;
    guard
        .grant(&body.principal, role)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(serde_json::json!({
        "principal": body.principal,
        "role": body.role,
    })))
}

/// GET /api/v1/acl
pub async fn acl_list(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let guard = crate::access_control::AclGuard::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let entries: Vec<serde_json::Value> = guard
        .list()
        .iter()
        .map(|e| {
            serde_json::json!({
                "principal": e.principal,
                "role": e.role.to_string(),
            })
        })
        .collect();
    Ok(Json(entries))
}

#[derive(Deserialize)]
pub struct AclRevokeRequest {
    pub principal: String,
}

/// DELETE /api/v1/acl
pub async fn acl_revoke(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<AclRevokeRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut guard = crate::access_control::AclGuard::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    guard
        .revoke(&body.principal)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(serde_json::json!({ "revoked": body.principal })))
}

// ── Webhooks ─────────────────────────────────────────────────────────────────

/// GET /api/v1/webhooks
pub async fn webhook_list(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let store = crate::webhooks::WebhookStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let hooks: Vec<serde_json::Value> = store
        .list()
        .iter()
        .map(|h| {
            serde_json::json!({
                "id": h.id,
                "url": h.url,
                "enabled": h.enabled,
                "events": h.events,
            })
        })
        .collect();
    Ok(Json(hooks))
}

#[derive(Deserialize)]
pub struct WebhookAddRequest {
    pub url: String,
    pub secret: Option<String>,
    pub events: Option<Vec<String>>,
}

/// POST /api/v1/webhooks
pub async fn webhook_add(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<WebhookAddRequest>,
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut store = crate::webhooks::WebhookStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let id = format!("wh_{}", uuid_v4_simple());
    let target = crate::webhooks::WebhookTarget {
        id: id.clone(),
        url: body.url.clone(),
        secret: body.secret,
        events: body.events.unwrap_or_default(),
        enabled: true,
    };
    store
        .add(target)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok((
        StatusCode::CREATED,
        Json(serde_json::json!({ "id": id, "url": body.url })),
    ))
}

/// DELETE /api/v1/webhooks/:id
pub async fn webhook_remove(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut store = crate::webhooks::WebhookStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let removed = store
        .remove(&id)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(serde_json::json!({ "id": id, "removed": removed })))
}

// ── Validation ───────────────────────────────────────────────────────────────

/// POST /api/v1/models/:name/validate
pub async fn validate_model(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let store = crate::validation::ValidationStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    // Use vault data dir as fallback path for validation
    let data_dir = vault_path.join("data");
    let file_path = data_dir.join(&name);
    match store.validate(&name, &file_path) {
        Ok(report) => Ok(Json(serde_json::json!({
            "model": name,
            "overall_pass": report.overall_pass,
            "results": report.results.iter().map(|r| serde_json::json!({
                "probe": r.probe_label,
                "passed": r.passed,
                "message": r.message,
            })).collect::<Vec<_>>(),
        }))),
        Err(e) => Err(ApiError::internal(e.to_string())),
    }
}

// ── GC ───────────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct GcQuery {
    #[serde(default)]
    dry_run: bool,
}

/// POST /api/v1/gc
pub async fn garbage_collect(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Query(q): Query<GcQuery>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let report =
        crate::gc::gc(&vault_path, q.dry_run).map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(serde_json::json!({
        "dry_run": q.dry_run,
        "orphaned_blobs": report.orphaned_blobs,
        "temp_files": report.temp_files,
        "reclaimable_bytes": report.reclaimable_bytes,
        "deleted": report.deleted,
    })))
}

// ── Policies ─────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub struct PolicySetRequest {
    pub max_versions: Option<usize>,
    pub max_age_days: Option<u32>,
    pub keep_minimum: Option<usize>,
}

/// PUT /api/v1/models/:name/policy
pub async fn policy_set(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
    Json(body): Json<PolicySetRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    validate_model_name(&name)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut store = crate::policies::PolicyStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let policy = crate::policies::RetentionPolicy {
        max_versions: body.max_versions.unwrap_or(0),
        max_age_days: body.max_age_days.unwrap_or(0),
        keep_minimum: body.keep_minimum.unwrap_or(1),
    };
    store
        .set(&name, policy)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(serde_json::json!({ "model": name, "policy": "set" })))
}

/// GET /api/v1/policies
pub async fn policy_list(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let store = crate::policies::PolicyStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let policies = store.list();
    let out: Vec<serde_json::Value> = policies
        .iter()
        .map(|(model, p)| {
            serde_json::json!({
                "model": model,
                "max_versions": p.max_versions,
                "max_age_days": p.max_age_days,
                "keep_minimum": p.keep_minimum,
            })
        })
        .collect();
    Ok(Json(serde_json::json!({ "policies": out })))
}

// ── Profiles ─────────────────────────────────────────────────────────────────

/// GET /api/v1/profiles
pub async fn profile_list(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let store = crate::profiles::ProfileStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let profiles: Vec<serde_json::Value> = store
        .list()
        .iter()
        .map(|p| {
            serde_json::json!({
                "name": p.name,
                "description": p.description,
                "overrides": p.overrides,
            })
        })
        .collect();
    let active = store.active().map(|p| p.name.clone());
    Ok(Json(serde_json::json!({
        "profiles": profiles,
        "active": active,
    })))
}

#[derive(Deserialize)]
pub struct ProfileCreateRequest {
    pub name: String,
    pub description: Option<String>,
    pub overrides: Option<std::collections::BTreeMap<String, String>>,
}

/// POST /api/v1/profiles
pub async fn profile_create(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<ProfileCreateRequest>,
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut store = crate::profiles::ProfileStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let profile = crate::profiles::Profile {
        name: body.name.clone(),
        description: body.description,
        overrides: body.overrides.unwrap_or_default(),
        created_at: Utc::now().to_rfc3339(),
    };
    store
        .set(profile)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok((
        StatusCode::CREATED,
        Json(serde_json::json!({ "name": body.name })),
    ))
}

/// POST /api/v1/profiles/:name/activate
pub async fn profile_activate(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut store = crate::profiles::ProfileStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    store
        .activate(&name)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(serde_json::json!({ "activated": name })))
}

// ── Lineage Graph ────────────────────────────────────────────────────────────

/// GET /api/v1/lineage-graph
pub async fn lineage_graph_show(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let graph = crate::lineage_graph::LineageGraph::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let edges: Vec<serde_json::Value> = graph
        .edges()
        .iter()
        .map(|e| {
            serde_json::json!({
                "parents": e.parents,
                "child": e.child,
                "kind": format!("{:?}", e.kind),
                "notes": e.notes,
            })
        })
        .collect();
    Ok(Json(serde_json::json!({ "edges": edges })))
}

#[derive(Deserialize)]
pub struct LineageAddRequest {
    pub child: String,
    pub parents: Vec<String>,
    pub kind: String,
    pub notes: Option<String>,
}

/// POST /api/v1/lineage-graph
pub async fn lineage_graph_add(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<LineageAddRequest>,
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut graph = crate::lineage_graph::LineageGraph::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let kind = match body.kind.to_lowercase().as_str() {
        "fine-tune" | "finetune" => crate::lineage_graph::DerivationKind::FineTune,
        "merge" => crate::lineage_graph::DerivationKind::Merge,
        "distillation" => crate::lineage_graph::DerivationKind::Distillation,
        "quantization" => crate::lineage_graph::DerivationKind::Quantization,
        "conversion" => crate::lineage_graph::DerivationKind::Conversion,
        "prune" => crate::lineage_graph::DerivationKind::Prune,
        other => crate::lineage_graph::DerivationKind::Custom(other.to_string()),
    };
    let mut notes = std::collections::BTreeMap::new();
    if let Some(n) = &body.notes {
        notes.insert("notes".to_string(), n.clone());
    }
    let edge = crate::lineage_graph::LineageEdge {
        parents: body.parents.clone(),
        child: body.child.clone(),
        kind,
        notes,
        created_at: Utc::now().to_rfc3339(),
    };
    graph
        .add_edge(edge)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok((
        StatusCode::CREATED,
        Json(serde_json::json!({ "child": body.child, "parents": body.parents })),
    ))
}

// ── Plugins ──────────────────────────────────────────────────────────────────

/// GET /api/v1/plugins
pub async fn plugin_list(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let registry = crate::plugins::PluginRegistry::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let plugins: Vec<serde_json::Value> = registry
        .list()
        .iter()
        .map(|p| {
            serde_json::json!({
                "id": p.manifest.id,
                "name": p.manifest.name,
                "version": p.manifest.version,
                "description": p.manifest.description,
                "loaded": p.loaded,
            })
        })
        .collect();
    Ok(Json(plugins))
}

// ── Quantization ─────────────────────────────────────────────────────────────

/// GET /api/v1/quantization/profiles
pub async fn quant_profile_list(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let store = crate::quantization::QuantProfileStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let profiles: Vec<serde_json::Value> = store
        .list()
        .iter()
        .map(|p| {
            serde_json::json!({
                "name": p.name,
                "method": p.method.to_string(),
                "description": p.description,
            })
        })
        .collect();
    Ok(Json(profiles))
}

#[derive(Deserialize)]
pub struct QuantProfileRequest {
    pub name: String,
    pub method: String,
    pub description: Option<String>,
}

/// POST /api/v1/quantization/profiles
pub async fn quant_profile_set(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<QuantProfileRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut store = crate::quantization::QuantProfileStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let method: crate::quantization::QuantMethod = body
        .method
        .parse()
        .map_err(|e: crate::VaultError| ApiError::bad_request(e.to_string()))?;
    let profile = crate::quantization::QuantProfile {
        name: body.name.clone(),
        method,
        description: body.description,
        metadata: std::collections::BTreeMap::new(),
    };
    store
        .set(profile)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(
        serde_json::json!({ "status": "ok", "name": body.name }),
    ))
}

#[derive(Deserialize)]
pub struct QuantEstimateRequest {
    pub size: u64,
    pub from: String,
    pub to: String,
}

/// POST /api/v1/quantization/estimate
pub async fn quant_estimate(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<QuantEstimateRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let from: crate::quantization::QuantMethod = body
        .from
        .parse()
        .map_err(|e: crate::VaultError| ApiError::bad_request(e.to_string()))?;
    let to: crate::quantization::QuantMethod = body
        .to
        .parse()
        .map_err(|e: crate::VaultError| ApiError::bad_request(e.to_string()))?;
    let estimated = crate::quantization::estimate_quantized_size(body.size, from, to);
    Ok(Json(serde_json::json!({
        "original_bytes": body.size,
        "estimated_bytes": estimated,
        "compression_ratio": body.size as f64 / estimated as f64,
        "from": from.to_string(),
        "to": to.to_string(),
    })))
}

// ── Evaluations ──────────────────────────────────────────────────────────────

/// GET /api/v1/evaluations
#[allow(clippy::implicit_hasher)]
pub async fn eval_list(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Query(params): Query<std::collections::HashMap<String, String>>,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let store = crate::evaluation::EvalStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let model = params.get("model");
    let version: Option<u64> = params.get("version").and_then(|v| v.parse().ok());
    let runs = if let Some(m) = model {
        store.get_runs(m, version)
    } else {
        store.get_runs("", None) // empty = all if model is not specified
    };
    let results: Vec<serde_json::Value> = runs
        .iter()
        .map(|r| {
            serde_json::json!({
                "model": r.model,
                "version": r.version,
                "suite": r.suite,
                "timestamp": r.timestamp,
                "metrics": r.metrics.iter().map(|m| serde_json::json!({
                    "name": m.name,
                    "value": m.value,
                    "unit": m.unit,
                    "higher_is_better": m.higher_is_better,
                })).collect::<Vec<_>>(),
            })
        })
        .collect();
    Ok(Json(results))
}

#[derive(Deserialize)]
pub struct EvalRecordRequest {
    pub model: String,
    pub version: u64,
    pub suite: String,
    pub metrics: Vec<EvalMetricInput>,
}

#[derive(Deserialize)]
pub struct EvalMetricInput {
    pub name: String,
    pub value: f64,
    #[serde(default = "default_unit")]
    pub unit: String,
    #[serde(default = "default_true")]
    pub higher_is_better: bool,
}

fn default_unit() -> String {
    "score".to_string()
}
fn default_true() -> bool {
    true
}

/// POST /api/v1/evaluations
pub async fn eval_record(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<EvalRecordRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut store = crate::evaluation::EvalStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let metrics: Vec<crate::evaluation::MetricResult> = body
        .metrics
        .into_iter()
        .map(|m| crate::evaluation::MetricResult {
            name: m.name,
            value: m.value,
            unit: m.unit,
            higher_is_better: m.higher_is_better,
        })
        .collect();
    let run = crate::evaluation::EvalRun {
        suite: body.suite.clone(),
        model: body.model.clone(),
        version: body.version,
        metrics,
        timestamp: Utc::now().to_rfc3339(),
        context: std::collections::BTreeMap::new(),
    };
    store
        .record(run)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(serde_json::json!({ "status": "recorded" })))
}

/// GET /api/v1/evaluations/suites
pub async fn eval_suites(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<Vec<String>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let store = crate::evaluation::EvalStore::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(store.suites()))
}

// ── Backup Schedules ─────────────────────────────────────────────────────────

/// GET /api/v1/backups/schedules
pub async fn backup_schedule_list(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mgr = crate::scheduler::BackupManager::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let schedules: Vec<serde_json::Value> = mgr
        .list_schedules()
        .iter()
        .map(|s| {
            serde_json::json!({
                "name": s.name,
                "frequency": s.frequency.to_string(),
                "max_backups": s.max_backups,
                "output_dir": s.output_dir.display().to_string(),
                "enabled": s.enabled,
                "created_at": s.created_at,
            })
        })
        .collect();
    Ok(Json(schedules))
}

#[derive(Deserialize)]
pub struct BackupScheduleRequest {
    pub name: String,
    pub frequency: String,
    #[serde(default = "default_max_backups")]
    pub max_backups: usize,
    pub output_dir: String,
}

fn default_max_backups() -> usize {
    7
}

/// POST /api/v1/backups/schedules
pub async fn backup_schedule_set(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<BackupScheduleRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mut mgr = crate::scheduler::BackupManager::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let freq: crate::scheduler::BackupFrequency = body
        .frequency
        .parse()
        .map_err(|e: crate::VaultError| ApiError::bad_request(e.to_string()))?;
    let schedule = crate::scheduler::BackupSchedule {
        name: body.name.clone(),
        frequency: freq,
        max_backups: body.max_backups,
        output_dir: std::path::PathBuf::from(&body.output_dir),
        enabled: true,
        created_at: Utc::now().to_rfc3339(),
    };
    mgr.set_schedule(schedule)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(
        serde_json::json!({ "status": "ok", "name": body.name }),
    ))
}

/// GET /api/v1/backups/history
#[allow(clippy::implicit_hasher)]
pub async fn backup_history(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Query(params): Query<std::collections::HashMap<String, String>>,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let vault_path = vault.get_config().get_vault_path(None);
    let mgr = crate::scheduler::BackupManager::new(&vault_path)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let schedule = params.get("schedule").map(|s| s.as_str());
    let history: Vec<serde_json::Value> = mgr
        .get_history(schedule)
        .iter()
        .map(|r| {
            serde_json::json!({
                "path": r.path.display().to_string(),
                "timestamp": r.timestamp,
                "size_bytes": r.size_bytes,
                "schedule_name": r.schedule_name,
            })
        })
        .collect();
    Ok(Json(history))
}

// ── Multi-Vault Registry ─────────────────────────────────────────────────────

/// GET /api/v1/vaults
pub async fn vault_list(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
) -> Result<Json<Vec<serde_json::Value>>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let config_dir = &vault.get_config().dirs.config_dir;
    let reg = crate::multi_vault::VaultRegistry::new(config_dir)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let vaults: Vec<serde_json::Value> = reg
        .list()
        .iter()
        .map(|v| {
            serde_json::json!({
                "name": v.name,
                "path": v.path.display().to_string(),
                "is_active": v.is_active,
                "exists": v.exists,
            })
        })
        .collect();
    Ok(Json(vaults))
}

#[derive(Deserialize)]
pub struct VaultRegisterRequest {
    pub name: String,
    pub path: String,
    pub description: Option<String>,
}

/// POST /api/v1/vaults
pub async fn vault_register(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Json(body): Json<VaultRegisterRequest>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let config_dir = &vault.get_config().dirs.config_dir;
    let mut reg = crate::multi_vault::VaultRegistry::new(config_dir)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    let entry = crate::multi_vault::VaultEntry {
        name: body.name.clone(),
        path: std::path::PathBuf::from(&body.path),
        description: body.description,
        registered_at: Utc::now().to_rfc3339(),
    };
    reg.register(entry)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    Ok(Json(
        serde_json::json!({ "status": "registered", "name": body.name }),
    ))
}

/// POST /api/v1/vaults/:name/activate
pub async fn vault_activate(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Path(name): Path<String>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let _claims = require_auth(&headers, &state)?;
    let vault = state.vault.read().await;
    let config_dir = &vault.get_config().dirs.config_dir;
    let mut reg = crate::multi_vault::VaultRegistry::new(config_dir)
        .map_err(|e| ApiError::internal(e.to_string()))?;
    reg.activate(&name)
        .map_err(|e| ApiError::bad_request(e.to_string()))?;
    Ok(Json(
        serde_json::json!({ "status": "activated", "name": name }),
    ))
}

/// Check if an audit entry is a security-sensitive event type.
///
/// Used by role-based filtering: non-admin roles cannot see these events.
fn is_security_event(entry: &serde_json::Value) -> bool {
    const SECURITY_TYPES: &[&str] = &[
        "SECURITY_VIOLATION",
        "INTEGRITY_FAILURE",
        "AUTH_FAILURE",
        "KEY_DERIVED",
    ];

    let event_type = entry
        .get("event_type")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    SECURITY_TYPES
        .iter()
        .any(|t| event_type.eq_ignore_ascii_case(t))
}

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

    #[test]
    fn test_parse_format_valid() {
        let cases = vec![
            ("safetensors", ModelFormat::Safetensors),
            ("gguf", ModelFormat::GGUF),
            ("pytorch", ModelFormat::PyTorch),
            ("pt", ModelFormat::PyTorch),
            ("pth", ModelFormat::PyTorch),
            ("onnx", ModelFormat::ONNX),
            ("tensorrt", ModelFormat::TensorRT),
            ("trt", ModelFormat::TensorRT),
            ("coreml", ModelFormat::CoreML),
            ("mlmodel", ModelFormat::CoreML),
            ("tflite", ModelFormat::TFLite),
            ("tensorflow", ModelFormat::TensorFlow),
            ("tf", ModelFormat::TensorFlow),
            ("pb", ModelFormat::TensorFlow),
            ("keras", ModelFormat::Keras),
            ("openvino", ModelFormat::OpenVINO),
            ("mlx", ModelFormat::MLX),
            ("hdf5", ModelFormat::HDF5),
            ("h5", ModelFormat::HDF5),
            ("numpy", ModelFormat::NumPy),
            ("npy", ModelFormat::NumPy),
            ("npz", ModelFormat::NumPy),
            ("pickle", ModelFormat::Pickle),
            ("pkl", ModelFormat::Pickle),
            ("mxnet", ModelFormat::MXNet),
            ("params", ModelFormat::MXNet),
            ("caffe", ModelFormat::Caffe),
            ("caffemodel", ModelFormat::Caffe),
            ("ncnn", ModelFormat::NCNN),
            ("param", ModelFormat::NCNN),
            ("mnn", ModelFormat::MNN),
            ("rknn", ModelFormat::RKNN),
            ("darknet", ModelFormat::Darknet),
            ("weights", ModelFormat::Darknet),
        ];
        for (input, expected) in cases {
            let result = parse_format(input).unwrap();
            assert_eq!(result, expected, "parse_format(\"{input}\") mismatch");
        }
    }

    #[test]
    fn test_parse_format_invalid() {
        let err = parse_format("nonexistent");
        assert!(err.is_err());
    }

    #[test]
    fn test_validate_model_name_valid() {
        assert!(validate_model_name("my-model").is_ok());
        assert!(validate_model_name("a").is_ok());
        assert!(validate_model_name("model_v2.1").is_ok());
        assert!(validate_model_name("ABC-123").is_ok());
    }

    #[test]
    fn test_validate_model_name_empty() {
        assert!(validate_model_name("").is_err());
    }

    #[test]
    fn test_validate_model_name_too_long() {
        let long = "a".repeat(129);
        assert!(validate_model_name(&long).is_err());
    }

    #[test]
    fn test_validate_model_name_invalid_chars() {
        assert!(validate_model_name("model name").is_err()); // space
        assert!(validate_model_name("model/path").is_err()); // slash
        assert!(validate_model_name("model;drop").is_err()); // semicolon
    }

    #[test]
    fn test_is_security_event_true() {
        for event_type in &[
            "SECURITY_VIOLATION",
            "INTEGRITY_FAILURE",
            "AUTH_FAILURE",
            "KEY_DERIVED",
            "security_violation", // case-insensitive
        ] {
            let entry = serde_json::json!({ "event_type": event_type });
            assert!(
                is_security_event(&entry),
                "{event_type} should be a security event"
            );
        }
    }

    #[test]
    fn test_is_security_event_false() {
        let entry = serde_json::json!({ "event_type": "MODEL_STORED" });
        assert!(!is_security_event(&entry));

        let entry2 = serde_json::json!({ "action": "store" });
        assert!(!is_security_event(&entry2));

        let entry3 = serde_json::json!({});
        assert!(!is_security_event(&entry3));
    }

    #[test]
    fn test_health_response_serialization() {
        let resp = HealthResponse {
            status: "ok".to_string(),
            version: "1.3.0".to_string(),
            vault_state: Some("locked".to_string()),
            model_count: Some(5),
            uptime_seconds: None,
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("ok"));
        assert!(json.contains("1.3.0"));
        assert!(json.contains("locked"));
        assert!(!json.contains("uptime_seconds")); // skipped
    }

    #[test]
    fn test_health_response_minimal() {
        let resp = HealthResponse {
            status: "ok".to_string(),
            version: "1.0.0".to_string(),
            vault_state: None,
            model_count: None,
            uptime_seconds: None,
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(!json.contains("vault_state"));
        assert!(!json.contains("model_count"));
    }

    #[test]
    fn test_conversion_info_serialization() {
        let info = ConversionInfo {
            name: "SafeTensorsToPyTorch".to_string(),
            source: "safetensors".to_string(),
            target: "pytorch".to_string(),
        };
        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("SafeTensorsToPyTorch"));
    }

    #[test]
    fn test_stats_response_serialization() {
        let resp = StatsResponse {
            model_count: 3,
            total_versions: 7,
            total_size_bytes: 1024 * 1024,
            file_count: 10,
        };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["model_count"], 3);
        assert_eq!(parsed["total_versions"], 7);
    }

    #[tokio::test]
    async fn test_health_without_state() {
        let resp = health(None).await;
        assert_eq!(resp.0.status, "ok");
        assert!(resp.0.vault_state.is_none());
        assert!(resp.0.model_count.is_none());
    }

    #[tokio::test]
    async fn test_list_conversions_returns_entries() {
        let Json(entries) = list_conversions().await;
        assert!(!entries.is_empty());
        for e in &entries {
            assert!(!e.name.is_empty());
            assert!(!e.source.is_empty());
            assert!(!e.target.is_empty());
        }
    }

    #[tokio::test]
    async fn test_openapi_json_returns_valid() {
        let Json(spec) = openapi_json().await;
        assert!(spec.get("openapi").is_some() || spec.get("info").is_some());
    }

    #[tokio::test]
    async fn test_dashboard_index_returns_html() {
        let Html(html) = dashboard_index().await;
        assert!(html.contains("<html") || html.contains("<!DOCTYPE"));
    }

    #[test]
    fn test_uuid_v4_simple_unique() {
        let a = uuid_v4_simple();
        std::thread::sleep(std::time::Duration::from_millis(1));
        let b = uuid_v4_simple();
        assert_ne!(a, b);
        assert!(!a.is_empty());
    }
}