rufish 0.4.0

An asynchronous Redfish client library for BMC/server management in Rust.
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
use log::debug;
use reqwest::{Client, Response, StatusCode};
use serde_json::Value;

use crate::bios_config::{BiosConfig, BiosConfigSource};
use crate::enriched::{
    self, ControllerSummary, DriveSummary, EnrichedLogEntry, HealthStatus, StorageOverview,
    SubscribeParams, SystemHealth, UserAccount, VolumeSummary,
};
use crate::error::{RedfishError, Result};
use crate::registry::{
    self, RegistryAttribute, RegistryInfo, RegistryMessage,
};
use crate::sse::EventStream;
use crate::topology::{
    ChassisNode, ComponentNode, HardwareTopology, ManagerNode, SystemNode,
};
use crate::types::*;

/// Builder for constructing a [`RedfishClient`] with custom configuration.
pub struct RedfishClientBuilder {
    host: String,
    username: Option<String>,
    password: Option<String>,
    client: Option<Client>,
    session_token: Option<String>,
    session_uri: Option<String>,
}

impl RedfishClientBuilder {
    /// Set credentials for session-based authentication.
    pub fn credentials(mut self, username: &str, password: &str) -> Self {
        self.username = Some(username.to_string());
        self.password = Some(password.to_string());
        self
    }

    /// Provide a pre-configured reqwest Client.
    pub fn client(mut self, client: Client) -> Self {
        self.client = Some(client);
        self
    }

    /// Inject an existing session token and URI (for session persistence).
    pub fn session(mut self, token: &str, session_uri: &str) -> Self {
        self.session_token = Some(token.to_string());
        self.session_uri = Some(session_uri.to_string());
        self
    }

    /// Build the [`RedfishClient`].
    pub fn build(self) -> Result<RedfishClient> {
        let base_url = if self.host.starts_with("http") {
            self.host.trim_end_matches('/').to_string()
        } else {
            format!("https://{}", self.host.trim_end_matches('/'))
        };

        let client = match self.client {
            Some(c) => c,
            None => Client::builder()
                .danger_accept_invalid_certs(true)
                .timeout(std::time::Duration::from_secs(30))
                .build()?,
        };

        Ok(RedfishClient {
            base_url,
            username: self.username.unwrap_or_default(),
            password: self.password.unwrap_or_default(),
            client,
            session_token: self.session_token,
            session_uri: self.session_uri,
        })
    }
}

/// Async Redfish client for BMC management.
pub struct RedfishClient {
    base_url: String,
    username: String,
    password: String,
    client: Client,
    session_token: Option<String>,
    session_uri: Option<String>,
}

impl RedfishClient {
    /// Create a builder for configuring a RedfishClient.
    pub fn builder(host: &str) -> RedfishClientBuilder {
        RedfishClientBuilder {
            host: host.to_string(),
            username: None,
            password: None,
            client: None,
            session_token: None,
            session_uri: None,
        }
    }

    /// Create a new Redfish client.
    /// `host` can be IP or hostname. Uses HTTPS by default.
    pub fn new(host: &str, username: &str, password: &str) -> Result<Self> {
        Self::builder(host).credentials(username, password).build()
    }

    /// Inject an existing session token and URI.
    pub fn set_session(&mut self, token: &str, session_uri: &str) {
        self.session_token = Some(token.to_string());
        self.session_uri = Some(session_uri.to_string());
    }

    /// Get the current session token, if any.
    pub fn session_token(&self) -> Option<&str> {
        self.session_token.as_deref()
    }

    /// Get the current session URI, if any.
    pub fn session_uri(&self) -> Option<&str> {
        self.session_uri.as_deref()
    }

    /// Establish a Redfish session (POST to SessionService).
    pub async fn login(&mut self) -> Result<()> {
        let url = format!("{}/redfish/v1/SessionService/Sessions", self.base_url);
        let body = SessionCreate {
            user_name: self.username.clone(),
            password: self.password.clone(),
        };

        let resp = self.client.post(&url).json(&body).send().await?;
        if resp.status() == StatusCode::CREATED || resp.status() == StatusCode::OK {
            let token = resp
                .headers()
                .get("X-Auth-Token")
                .and_then(|v| v.to_str().ok())
                .map(|s| s.to_string())
                .ok_or(RedfishError::AuthFailed)?;
            let location = resp
                .headers()
                .get("Location")
                .and_then(|v| v.to_str().ok())
                .map(|s| s.to_string());
            self.session_token = Some(token);
            self.session_uri = location;
            debug!("Session established");
            Ok(())
        } else {
            Err(RedfishError::AuthFailed)
        }
    }

    /// Close the Redfish session.
    pub async fn logout(&mut self) -> Result<()> {
        if let (Some(token), Some(uri)) = (&self.session_token, &self.session_uri) {
            let url = if uri.starts_with("http") {
                uri.clone()
            } else {
                format!("{}{}", self.base_url, uri)
            };
            let _ = self.client
                .delete(&url)
                .header("X-Auth-Token", token)
                .send()
                .await;
        }
        self.session_token = None;
        self.session_uri = None;
        Ok(())
    }

    /// GET a Redfish resource by path (e.g. "/redfish/v1/Systems").
    pub async fn get(&self, path: &str) -> Result<Value> {
        let url = if path.starts_with("http") {
            path.to_string()
        } else {
            format!("{}{}", self.base_url, path)
        };
        let resp = self.auth_get(&url).await?;
        self.handle_response(resp).await
    }

    /// GET and deserialize into a typed struct.
    pub async fn get_as<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
        let val = self.get(path).await?;
        serde_json::from_value(val).map_err(|e| RedfishError::Parse(e.to_string()))
    }

    /// POST an action (e.g. Reset).
    pub async fn post(&self, path: &str, body: &Value) -> Result<Value> {
        let url = if path.starts_with("http") {
            path.to_string()
        } else {
            format!("{}{}", self.base_url, path)
        };
        let mut req = self.client.post(&url).json(body);
        if let Some(token) = &self.session_token {
            req = req.header("X-Auth-Token", token);
        } else {
            req = req.basic_auth(&self.username, Some(&self.password));
        }
        let resp = req.send().await?;
        self.handle_response(resp).await
    }

    /// PATCH a resource (update properties).
    pub async fn patch(&self, path: &str, body: &Value) -> Result<Value> {
        let url = if path.starts_with("http") {
            path.to_string()
        } else {
            format!("{}{}", self.base_url, path)
        };
        let mut req = self.client.patch(&url).json(body);
        if let Some(token) = &self.session_token {
            req = req.header("X-Auth-Token", token);
        } else {
            req = req.basic_auth(&self.username, Some(&self.password));
        }
        let resp = req.send().await?;
        self.handle_response(resp).await
    }

    /// DELETE a resource.
    pub async fn delete(&self, path: &str) -> Result<()> {
        let url = if path.starts_with("http") {
            path.to_string()
        } else {
            format!("{}{}", self.base_url, path)
        };
        let mut req = self.client.delete(&url);
        if let Some(token) = &self.session_token {
            req = req.header("X-Auth-Token", token);
        } else {
            req = req.basic_auth(&self.username, Some(&self.password));
        }
        let resp = req.send().await?;
        if resp.status().is_success() || resp.status() == StatusCode::NO_CONTENT {
            Ok(())
        } else {
            let status = resp.status().as_u16();
            let text = resp.text().await.unwrap_or_default();
            Err(RedfishError::Api { status, message: text })
        }
    }

    // --- High-level API ---

    /// Get Service Root.
    pub async fn get_service_root(&self) -> Result<ServiceRoot> {
        self.get_as("/redfish/v1/").await
    }

    /// List all computer systems.
    pub async fn list_systems(&self) -> Result<Collection> {
        self.get_as("/redfish/v1/Systems").await
    }

    /// Get a specific system by ID.
    pub async fn get_system(&self, id: &str) -> Result<ComputerSystem> {
        self.get_as(&format!("/redfish/v1/Systems/{}", id)).await
    }

    /// List all chassis.
    pub async fn list_chassis(&self) -> Result<Collection> {
        self.get_as("/redfish/v1/Chassis").await
    }

    /// Get a specific chassis by ID.
    pub async fn get_chassis(&self, id: &str) -> Result<Chassis> {
        self.get_as(&format!("/redfish/v1/Chassis/{}", id)).await
    }

    /// List all managers (BMCs).
    pub async fn list_managers(&self) -> Result<Collection> {
        self.get_as("/redfish/v1/Managers").await
    }

    /// Get a specific manager by ID.
    pub async fn get_manager(&self, id: &str) -> Result<Manager> {
        self.get_as(&format!("/redfish/v1/Managers/{}", id)).await
    }

    /// Get power info for a chassis.
    pub async fn get_power(&self, chassis_id: &str) -> Result<Power> {
        self.get_as(&format!("/redfish/v1/Chassis/{}/Power", chassis_id)).await
    }

    /// Get thermal info for a chassis.
    pub async fn get_thermal(&self, chassis_id: &str) -> Result<Thermal> {
        self.get_as(&format!("/redfish/v1/Chassis/{}/Thermal", chassis_id)).await
    }

    /// List processors for a system.
    pub async fn list_processors(&self, system_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Processors", system_id)).await
    }

    /// Get a specific processor.
    pub async fn get_processor(&self, system_id: &str, proc_id: &str) -> Result<Processor> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Processors/{}", system_id, proc_id)).await
    }

    /// List memory for a system.
    pub async fn list_memory(&self, system_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Memory", system_id)).await
    }

    /// Get a specific memory module.
    pub async fn get_memory(&self, system_id: &str, mem_id: &str) -> Result<Memory> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Memory/{}", system_id, mem_id)).await
    }

    /// List storage for a system.
    pub async fn list_storage(&self, system_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Storage", system_id)).await
    }

    /// Get a specific storage resource.
    pub async fn get_storage(&self, system_id: &str, storage_id: &str) -> Result<Storage> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Storage/{}", system_id, storage_id)).await
    }

    /// List ethernet interfaces for a system.
    pub async fn list_ethernet_interfaces(&self, system_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Systems/{}/EthernetInterfaces", system_id)).await
    }

    /// Get a specific ethernet interface.
    pub async fn get_ethernet_interface(&self, system_id: &str, iface_id: &str) -> Result<EthernetInterface> {
        self.get_as(&format!("/redfish/v1/Systems/{}/EthernetInterfaces/{}", system_id, iface_id)).await
    }

    /// Get account service.
    pub async fn get_account_service(&self) -> Result<AccountService> {
        self.get_as("/redfish/v1/AccountService").await
    }

    /// List user accounts.
    pub async fn list_accounts(&self) -> Result<Collection> {
        self.get_as("/redfish/v1/AccountService/Accounts").await
    }

    /// Get update service.
    pub async fn get_update_service(&self) -> Result<UpdateService> {
        self.get_as("/redfish/v1/UpdateService").await
    }

    /// Get event service.
    pub async fn get_event_service(&self) -> Result<EventService> {
        self.get_as("/redfish/v1/EventService").await
    }

    /// List log entries for a manager.
    pub async fn list_log_entries(&self, manager_id: &str, log_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Managers/{}/LogServices/{}/Entries", manager_id, log_id)).await
    }

    // --- Power Actions ---

    /// Reset/power control a system.
    /// reset_type: "On", "ForceOff", "GracefulShutdown", "GracefulRestart",
    ///             "ForceRestart", "Nmi", "ForceOn", "PushPowerButton", "PowerCycle"
    pub async fn reset_system(&self, system_id: &str, reset_type: &str) -> Result<Value> {
        let path = format!("/redfish/v1/Systems/{}/Actions/ComputerSystem.Reset", system_id);
        let body = serde_json::json!({ "ResetType": reset_type });
        self.post(&path, &body).await
    }

    /// Power on a system.
    pub async fn power_on(&self, system_id: &str) -> Result<Value> {
        self.reset_system(system_id, "On").await
    }

    /// Force power off a system.
    pub async fn power_off(&self, system_id: &str) -> Result<Value> {
        self.reset_system(system_id, "ForceOff").await
    }

    /// Graceful shutdown.
    pub async fn graceful_shutdown(&self, system_id: &str) -> Result<Value> {
        self.reset_system(system_id, "GracefulShutdown").await
    }

    /// Graceful restart.
    pub async fn graceful_restart(&self, system_id: &str) -> Result<Value> {
        self.reset_system(system_id, "GracefulRestart").await
    }

    /// Force restart.
    pub async fn force_restart(&self, system_id: &str) -> Result<Value> {
        self.reset_system(system_id, "ForceRestart").await
    }

    /// Power cycle.
    pub async fn power_cycle(&self, system_id: &str) -> Result<Value> {
        self.reset_system(system_id, "PowerCycle").await
    }

    // --- Boot Override ---

    /// Set boot source override.
    /// target: "None", "Pxe", "Cd", "Usb", "Hdd", "BiosSetup", "Diags"
    /// enabled: "Once", "Continuous", "Disabled"
    pub async fn set_boot_override(&self, system_id: &str, target: &str, enabled: Option<&str>) -> Result<Value> {
        let path = format!("/redfish/v1/Systems/{}", system_id);
        let body = serde_json::json!({
            "Boot": {
                "BootSourceOverrideTarget": target,
                "BootSourceOverrideEnabled": enabled.unwrap_or("Once")
            }
        });
        self.patch(&path, &body).await
    }

    /// Set next boot to PXE.
    pub async fn set_boot_pxe(&self, system_id: &str) -> Result<Value> {
        self.set_boot_override(system_id, "Pxe", Some("Once")).await
    }

    /// Set next boot to BIOS Setup.
    pub async fn set_boot_bios(&self, system_id: &str) -> Result<Value> {
        self.set_boot_override(system_id, "BiosSetup", Some("Once")).await
    }

    // --- Manager Actions ---

    /// Reset a manager (BMC).
    pub async fn reset_manager(&self, manager_id: &str, reset_type: &str) -> Result<Value> {
        let path = format!("/redfish/v1/Managers/{}/Actions/Manager.Reset", manager_id);
        let body = serde_json::json!({ "ResetType": reset_type });
        self.post(&path, &body).await
    }

    /// Clear a log service.
    pub async fn clear_log(&self, manager_id: &str, log_id: &str) -> Result<Value> {
        let path = format!("/redfish/v1/Managers/{}/LogServices/{}/Actions/LogService.ClearLog", manager_id, log_id);
        self.post(&path, &serde_json::json!({})).await
    }

    // --- Virtual Media ---

    /// List virtual media for a manager.
    pub async fn list_virtual_media(&self, manager_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Managers/{}/VirtualMedia", manager_id)).await
    }

    /// Get a virtual media resource.
    pub async fn get_virtual_media(&self, manager_id: &str, media_id: &str) -> Result<VirtualMedia> {
        self.get_as(&format!("/redfish/v1/Managers/{}/VirtualMedia/{}", manager_id, media_id)).await
    }

    /// Insert (mount) virtual media image.
    pub async fn insert_media(&self, manager_id: &str, media_id: &str, image_url: &str) -> Result<Value> {
        let path = format!("/redfish/v1/Managers/{}/VirtualMedia/{}/Actions/VirtualMedia.InsertMedia", manager_id, media_id);
        self.post(&path, &serde_json::json!({ "Image": image_url })).await
    }

    /// Eject (unmount) virtual media.
    pub async fn eject_media(&self, manager_id: &str, media_id: &str) -> Result<Value> {
        let path = format!("/redfish/v1/Managers/{}/VirtualMedia/{}/Actions/VirtualMedia.EjectMedia", manager_id, media_id);
        self.post(&path, &serde_json::json!({})).await
    }

    // --- BIOS ---

    /// Get BIOS attributes.
    pub async fn get_bios(&self, system_id: &str) -> Result<Bios> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Bios", system_id)).await
    }

    /// Get BIOS pending settings.
    pub async fn get_bios_settings(&self, system_id: &str) -> Result<Bios> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Bios/Settings", system_id)).await
    }

    /// Set BIOS attributes (applied on next boot).
    pub async fn set_bios_attributes(&self, system_id: &str, attributes: &Value) -> Result<Value> {
        let path = format!("/redfish/v1/Systems/{}/Bios/Settings", system_id);
        self.patch(&path, &serde_json::json!({ "Attributes": attributes })).await
    }

    /// Reset BIOS to factory defaults (requires reboot).
    pub async fn reset_bios_defaults(&self, system_id: &str) -> Result<Value> {
        let path = format!("/redfish/v1/Systems/{}/Bios/Actions/Bios.ResetBios", system_id);
        self.post(&path, &serde_json::json!({})).await
    }

    /// Get BIOS attributes with full registry metadata for UI rendering.
    ///
    /// This fetches the BIOS attribute registry and merges it with current
    /// and pending values, returning structured data suitable for building
    /// management UIs (dropdowns, toggles, grouped forms, etc.).
    pub async fn get_bios_attributes_full(&self, system_id: &str) -> Result<Vec<RegistryAttribute>> {
        let bios = self.get(&format!("/redfish/v1/Systems/{}/Bios", system_id)).await?;
        let pending = self.get(&format!("/redfish/v1/Systems/{}/Bios/Settings", system_id)).await.ok();

        let current_attrs = bios.pointer("/Attributes");
        let pending_attrs = pending.as_ref().and_then(|v| v.pointer("/Attributes"));

        // Find the BIOS attribute registry
        let registry_json = self.fetch_bios_registry(system_id).await?;

        Ok(registry::parse_bios_registry(&registry_json, current_attrs, pending_attrs))
    }

    // --- Registry ---

    /// List all registries available on this BMC.
    pub async fn list_registries(&self) -> Result<Collection> {
        self.get_as("/redfish/v1/Registries").await
    }

    /// Get a registry file by ID and return the parsed JSON body.
    ///
    /// Automatically resolves the registry location (local URI or public URI).
    pub async fn get_registry(&self, registry_id: &str) -> Result<Value> {
        let entry = self.get(&format!("/redfish/v1/Registries/{}", registry_id)).await?;
        self.resolve_registry_location(&entry).await
    }

    /// Get a message registry parsed into structured messages.
    pub async fn get_message_registry(&self, registry_id: &str) -> Result<(RegistryInfo, Vec<RegistryMessage>)> {
        let json = self.get_registry(registry_id).await?;
        Ok(registry::parse_message_registry(&json))
    }

    /// Get an attribute registry (non-BIOS) with current values merged.
    ///
    /// `resource_path` is the path to the resource whose attributes you want
    /// (e.g. "/redfish/v1/Managers/1/Attributes").
    pub async fn get_attributes_full(
        &self,
        registry_id: &str,
        resource_path: &str,
    ) -> Result<Vec<RegistryAttribute>> {
        let registry_json = self.get_registry(registry_id).await?;
        let resource = self.get(resource_path).await.ok();
        let current_attrs = resource.as_ref().and_then(|v| v.pointer("/Attributes"));
        Ok(registry::parse_attribute_registry(&registry_json, current_attrs))
    }

    /// Fetch the BIOS attribute registry for a system.
    async fn fetch_bios_registry(&self, system_id: &str) -> Result<Value> {
        // Try standard path first
        let bios = self.get(&format!("/redfish/v1/Systems/{}/Bios", system_id)).await?;

        // Check for AttributeRegistry link in BIOS resource
        if let Some(reg_id) = bios.get("AttributeRegistry").and_then(|v| v.as_str()) {
            return self.get_registry(reg_id).await;
        }

        // Fallback: search registries for one containing "Bios"
        let registries = self.get("/redfish/v1/Registries").await?;
        if let Some(members) = registries.get("Members").and_then(|v| v.as_array()) {
            for member in members {
                if let Some(id) = member.get("@odata.id").and_then(|v| v.as_str()) {
                    if let Ok(entry) = self.get(id).await {
                        let reg_id = entry.get("Id").and_then(|v| v.as_str()).unwrap_or("");
                        if reg_id.contains("Bios") || reg_id.contains("BIOS") {
                            return self.resolve_registry_location(&entry).await;
                        }
                    }
                }
            }
        }

        Err(RedfishError::NotFound("BIOS attribute registry".to_string()))
    }

    /// Resolve a registry entry to its actual JSON content.
    async fn resolve_registry_location(&self, registry_entry: &Value) -> Result<Value> {
        let locations = registry_entry
            .get("Location")
            .and_then(|v| v.as_array())
            .ok_or_else(|| RedfishError::NotFound("Registry location".to_string()))?;

        for loc in locations {
            // Try local URI first (most common)
            if let Some(uri) = loc.get("Uri").and_then(|v| v.as_str()) {
                if let Ok(body) = self.get(uri).await {
                    return Ok(body);
                }
            }
            // Try ArchiveUri with ArchiveFile
            if let Some(archive_uri) = loc.get("ArchiveUri").and_then(|v| v.as_str()) {
                if let Ok(body) = self.get(archive_uri).await {
                    return Ok(body);
                }
            }
        }

        Err(RedfishError::NotFound("Registry content".to_string()))
    }

    // --- Secure Boot ---

    /// Get Secure Boot status.
    pub async fn get_secure_boot(&self, system_id: &str) -> Result<SecureBoot> {
        self.get_as(&format!("/redfish/v1/Systems/{}/SecureBoot", system_id)).await
    }

    /// Enable or disable Secure Boot.
    pub async fn set_secure_boot(&self, system_id: &str, enabled: bool) -> Result<Value> {
        let path = format!("/redfish/v1/Systems/{}/SecureBoot", system_id);
        self.patch(&path, &serde_json::json!({ "SecureBootEnable": enabled })).await
    }

    // --- Network Protocol ---

    /// Get manager network protocol settings.
    pub async fn get_network_protocol(&self, manager_id: &str) -> Result<NetworkProtocol> {
        self.get_as(&format!("/redfish/v1/Managers/{}/NetworkProtocol", manager_id)).await
    }

    /// Update network protocol settings (e.g. NTP servers).
    pub async fn set_network_protocol(&self, manager_id: &str, settings: &Value) -> Result<Value> {
        self.patch(&format!("/redfish/v1/Managers/{}/NetworkProtocol", manager_id), settings).await
    }

    // --- Serial Interfaces ---

    /// List serial interfaces for a manager.
    pub async fn list_serial_interfaces(&self, manager_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Managers/{}/SerialInterfaces", manager_id)).await
    }

    /// Get a serial interface.
    pub async fn get_serial_interface(&self, manager_id: &str, iface_id: &str) -> Result<SerialInterface> {
        self.get_as(&format!("/redfish/v1/Managers/{}/SerialInterfaces/{}", manager_id, iface_id)).await
    }

    // --- Volumes / RAID ---

    /// List volumes for a storage resource.
    pub async fn list_volumes(&self, system_id: &str, storage_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Storage/{}/Volumes", system_id, storage_id)).await
    }

    /// Get a specific volume.
    pub async fn get_volume(&self, system_id: &str, storage_id: &str, volume_id: &str) -> Result<Volume> {
        self.get_as(&format!("/redfish/v1/Systems/{}/Storage/{}/Volumes/{}", system_id, storage_id, volume_id)).await
    }

    /// Create a volume (RAID).
    pub async fn create_volume(&self, system_id: &str, storage_id: &str, body: &Value) -> Result<Value> {
        let path = format!("/redfish/v1/Systems/{}/Storage/{}/Volumes", system_id, storage_id);
        self.post(&path, body).await
    }

    /// Delete a volume.
    pub async fn delete_volume(&self, system_id: &str, storage_id: &str, volume_id: &str) -> Result<()> {
        self.delete(&format!("/redfish/v1/Systems/{}/Storage/{}/Volumes/{}", system_id, storage_id, volume_id)).await
    }

    // --- Drives ---

    /// Get a specific drive.
    pub async fn get_drive(&self, path: &str) -> Result<Drive> {
        self.get_as(path).await
    }

    // --- Certificates ---

    /// List certificates for a manager.
    pub async fn list_certificates(&self, manager_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Managers/{}/NetworkProtocol/HTTPS/Certificates", manager_id)).await
    }

    /// Get a certificate.
    pub async fn get_certificate(&self, path: &str) -> Result<Certificate> {
        self.get_as(path).await
    }

    /// Replace a certificate (POST new cert to collection or PATCH existing).
    pub async fn replace_certificate(&self, path: &str, cert_pem: &str, cert_type: &str) -> Result<Value> {
        self.post(path, &serde_json::json!({
            "CertificateString": cert_pem,
            "CertificateType": cert_type
        })).await
    }

    // --- Event Subscriptions ---

    /// List event subscriptions.
    pub async fn list_subscriptions(&self) -> Result<Collection> {
        self.get_as("/redfish/v1/EventService/Subscriptions").await
    }

    /// Create an event subscription.
    pub async fn create_subscription(&self, destination: &str, event_types: &[&str], context: &str) -> Result<Value> {
        let types: Vec<String> = event_types.iter().map(|s| s.to_string()).collect();
        self.post("/redfish/v1/EventService/Subscriptions", &serde_json::json!({
            "Destination": destination,
            "EventTypes": types,
            "Protocol": "Redfish",
            "Context": context
        })).await
    }

    /// Delete an event subscription.
    pub async fn delete_subscription(&self, subscription_id: &str) -> Result<()> {
        self.delete(&format!("/redfish/v1/EventService/Subscriptions/{}", subscription_id)).await
    }

    // --- Firmware Update ---

    /// List firmware inventory.
    pub async fn list_firmware_inventory(&self) -> Result<Collection> {
        self.get_as("/redfish/v1/UpdateService/FirmwareInventory").await
    }

    /// Get a firmware inventory item.
    pub async fn get_firmware_item(&self, item_id: &str) -> Result<SoftwareInventory> {
        self.get_as(&format!("/redfish/v1/UpdateService/FirmwareInventory/{}", item_id)).await
    }

    /// Simple firmware update via URI (BMC pulls the image).
    pub async fn simple_update(&self, image_uri: &str) -> Result<Value> {
        self.post("/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate", &serde_json::json!({
            "ImageURI": image_uri
        })).await
    }

    // --- Tasks ---

    /// List tasks.
    pub async fn list_tasks(&self) -> Result<Collection> {
        self.get_as("/redfish/v1/TaskService/Tasks").await
    }

    /// Get a task by ID.
    pub async fn get_task(&self, task_id: &str) -> Result<Task> {
        self.get_as(&format!("/redfish/v1/TaskService/Tasks/{}", task_id)).await
    }

    /// Poll a task until completion (max wait in seconds).
    pub async fn wait_task(&self, task_id: &str, max_wait_secs: u64) -> Result<Task> {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(max_wait_secs);
        loop {
            let task = self.get_task(task_id).await?;
            match task.task_state.as_deref() {
                Some("Completed") | Some("Exception") | Some("Killed") | Some("Cancelled") => {
                    return Ok(task);
                }
                _ => {}
            }
            if std::time::Instant::now() > deadline {
                return Ok(task);
            }
            tokio::time::sleep(std::time::Duration::from_secs(2)).await;
        }
    }

    // --- Pagination ---

    /// GET a collection and automatically follow @odata.nextLink to get all members.
    pub async fn get_all_members(&self, path: &str) -> Result<Vec<OdataLink>> {
        let mut all = Vec::new();
        let mut current_path = path.to_string();
        loop {
            let val = self.get(&current_path).await?;
            if let Some(members) = val.get("Members").and_then(|m| m.as_array()) {
                for m in members {
                    if let Some(id) = m.get("@odata.id").and_then(|v| v.as_str()) {
                        all.push(OdataLink { odata_id: id.to_string() });
                    }
                }
            }
            match val.get("Members@odata.nextLink").and_then(|v| v.as_str()) {
                Some(next) => current_path = next.to_string(),
                None => break,
            }
        }
        Ok(all)
    }

    // --- Manager Ethernet Interfaces ---

    /// List ethernet interfaces for a manager (BMC network).
    pub async fn list_manager_ethernet_interfaces(&self, manager_id: &str) -> Result<Collection> {
        self.get_as(&format!("/redfish/v1/Managers/{}/EthernetInterfaces", manager_id)).await
    }

    /// Get a specific manager ethernet interface.
    pub async fn get_manager_ethernet_interface(&self, manager_id: &str, iface_id: &str) -> Result<EthernetInterface> {
        self.get_as(&format!("/redfish/v1/Managers/{}/EthernetInterfaces/{}", manager_id, iface_id)).await
    }

    /// Patch a manager ethernet interface (e.g. change IP settings).
    pub async fn patch_manager_ethernet_interface(&self, manager_id: &str, iface_id: &str, body: &Value) -> Result<Value> {
        self.patch(&format!("/redfish/v1/Managers/{}/EthernetInterfaces/{}", manager_id, iface_id), body).await
    }

    // --- Chassis Indicator LED ---

    /// Get chassis location indicator state.
    /// Returns `Some(true)` if active, `Some(false)` if off, `None` if unsupported.
    pub async fn get_chassis_indicator(&self, chassis_id: &str) -> Result<Option<bool>> {
        let val = self.get(&format!("/redfish/v1/Chassis/{}", chassis_id)).await?;
        if let Some(active) = val.get("LocationIndicatorActive").and_then(|v| v.as_bool()) {
            return Ok(Some(active));
        }
        if let Some(led) = val.get("IndicatorLED").and_then(|v| v.as_str()) {
            return Ok(Some(led != "Off"));
        }
        Ok(None)
    }

    /// Set chassis location indicator on or off.
    /// Tries `LocationIndicatorActive` first, falls back to `IndicatorLED`.
    pub async fn set_chassis_indicator(&self, chassis_id: &str, on: bool) -> Result<Value> {
        let path = format!("/redfish/v1/Chassis/{}", chassis_id);
        let val = self.get(&path).await?;
        if val.get("LocationIndicatorActive").is_some() {
            self.patch(&path, &serde_json::json!({"LocationIndicatorActive": on})).await
        } else {
            let led = if on { "Lit" } else { "Off" };
            self.patch(&path, &serde_json::json!({"IndicatorLED": led})).await
        }
    }

    // --- Enriched High-Level APIs ---

    /// Get aggregated system health (processors, memory, thermal, power, storage).
    ///
    /// Single call that fetches System, Thermal, and Power resources and returns
    /// a unified health summary suitable for dashboard display.
    pub async fn get_system_health(&self, system_id: &str, chassis_id: &str) -> Result<SystemHealth> {
        let system = self.get(&format!("/redfish/v1/Systems/{}", system_id)).await?;
        let thermal = self.get(&format!("/redfish/v1/Chassis/{}/Thermal", chassis_id)).await.ok();
        let power = self.get(&format!("/redfish/v1/Chassis/{}/Power", chassis_id)).await.ok();
        Ok(enriched::parse_system_health(&system, thermal.as_ref(), power.as_ref()))
    }

    /// Get log entries with message registry translation.
    ///
    /// Fetches log entries and the Base message registry, then returns entries
    /// with human-readable translated messages and resolution suggestions.
    pub async fn get_enriched_logs(
        &self,
        manager_id: &str,
        log_id: &str,
    ) -> Result<Vec<EnrichedLogEntry>> {
        let entries_val = self.get(&format!(
            "/redfish/v1/Managers/{}/LogServices/{}/Entries", manager_id, log_id
        )).await?;

        // Build message lookup from registries
        let mut msg_map = std::collections::HashMap::new();
        if let Ok((_, messages)) = self.get_message_registry("Base").await {
            for m in messages {
                msg_map.insert(m.message_id.clone(), (m.message.clone(), m.resolution.clone()));
            }
        }

        let entries = entries_val
            .get("Members")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        Ok(entries
            .iter()
            .filter_map(|e| enriched::parse_enriched_log_entry(e, &msg_map))
            .collect())
    }

    /// Get a complete storage overview for a system.
    ///
    /// Aggregates storage controllers, RAID volumes, and unassigned drives
    /// into a single topology view.
    pub async fn get_storage_overview(&self, system_id: &str) -> Result<StorageOverview> {
        let storage_collection = self.get(&format!("/redfish/v1/Systems/{}/Storage", system_id)).await?;
        let members = storage_collection
            .get("Members")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        let mut controllers = Vec::new();
        let mut volumes = Vec::new();
        let mut all_drives = Vec::new();
        let mut assigned_drive_ids = std::collections::HashSet::new();

        for member in &members {
            let path = match member.get("@odata.id").and_then(|v| v.as_str()) {
                Some(p) => p,
                None => continue,
            };
            let storage = match self.get(path).await {
                Ok(s) => s,
                Err(_) => continue,
            };

            // Controllers
            if let Some(ctrls) = storage.get("StorageControllers").and_then(|v| v.as_array()) {
                for c in ctrls {
                    if let Some(name) = c.get("Name").and_then(|v| v.as_str()) {
                        controllers.push(ControllerSummary {
                            name: name.to_string(),
                            manufacturer: c.get("Manufacturer").and_then(|v| v.as_str()).map(String::from),
                            model: c.get("Model").and_then(|v| v.as_str()).map(String::from),
                            firmware_version: c.get("FirmwareVersion").and_then(|v| v.as_str()).map(String::from),
                            status: HealthStatus::from_str_opt(
                                c.pointer("/Status/Health").and_then(|v| v.as_str()),
                            ),
                        });
                    }
                }
            }

            // Drives
            if let Some(drives) = storage.get("Drives").and_then(|v| v.as_array()) {
                for d in drives {
                    if let Some(drive_path) = d.get("@odata.id").and_then(|v| v.as_str()) {
                        if let Ok(drive) = self.get(drive_path).await {
                            let id = drive.get("Id").and_then(|v| v.as_str()).unwrap_or("").to_string();
                            all_drives.push((drive_path.to_string(), DriveSummary {
                                id: id.clone(),
                                name: drive.get("Name").and_then(|v| v.as_str()).unwrap_or(&id).to_string(),
                                manufacturer: drive.get("Manufacturer").and_then(|v| v.as_str()).map(String::from),
                                model: drive.get("Model").and_then(|v| v.as_str()).map(String::from),
                                capacity_bytes: drive.get("CapacityBytes").and_then(|v| v.as_u64()),
                                media_type: drive.get("MediaType").and_then(|v| v.as_str()).map(String::from),
                                protocol: drive.get("Protocol").and_then(|v| v.as_str()).map(String::from),
                                status: HealthStatus::from_str_opt(
                                    drive.pointer("/Status/Health").and_then(|v| v.as_str()),
                                ),
                            }));
                        }
                    }
                }
            }

            // Volumes
            let volumes_path = format!("{}/Volumes", path);
            if let Ok(vol_collection) = self.get(&volumes_path).await {
                if let Some(vol_members) = vol_collection.get("Members").and_then(|v| v.as_array()) {
                    for vm in vol_members {
                        if let Some(vol_path) = vm.get("@odata.id").and_then(|v| v.as_str()) {
                            if let Ok(vol) = self.get(vol_path).await {
                                let drive_links = vol.get("Links")
                                    .and_then(|l| l.get("Drives"))
                                    .and_then(|v| v.as_array())
                                    .map(|arr| {
                                        arr.iter()
                                            .filter_map(|d| d.get("@odata.id").and_then(|v| v.as_str()))
                                            .map(String::from)
                                            .collect::<Vec<_>>()
                                    })
                                    .unwrap_or_default();

                                for dl in &drive_links {
                                    assigned_drive_ids.insert(dl.clone());
                                }

                                volumes.push(VolumeSummary {
                                    id: vol.get("Id").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                                    name: vol.get("Name").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                                    capacity_bytes: vol.get("CapacityBytes").and_then(|v| v.as_u64()),
                                    raid_type: vol.get("RAIDType").and_then(|v| v.as_str()).map(String::from),
                                    status: HealthStatus::from_str_opt(
                                        vol.pointer("/Status/Health").and_then(|v| v.as_str()),
                                    ),
                                    drive_count: drive_links.len(),
                                });
                            }
                        }
                    }
                }
            }
        }

        let unassigned_drives = all_drives
            .into_iter()
            .filter(|(path, _)| !assigned_drive_ids.contains(path.as_str()))
            .map(|(_, d)| d)
            .collect();

        Ok(StorageOverview { controllers, volumes, unassigned_drives })
    }

    // --- Account Management (High-Level) ---

    /// List all user accounts as simplified structs.
    pub async fn list_users(&self) -> Result<Vec<UserAccount>> {
        let collection = self.get("/redfish/v1/AccountService/Accounts").await?;
        let members = collection
            .get("Members")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        let mut users = Vec::new();
        for m in &members {
            if let Some(path) = m.get("@odata.id").and_then(|v| v.as_str()) {
                if let Ok(acct) = self.get(path).await {
                    let username = acct.get("UserName").and_then(|v| v.as_str()).unwrap_or("");
                    if username.is_empty() { continue; }
                    users.push(UserAccount {
                        id: acct.get("Id").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                        username: username.to_string(),
                        role: acct.get("RoleId").and_then(|v| v.as_str()).map(String::from),
                        enabled: acct.get("Enabled").and_then(|v| v.as_bool()).unwrap_or(true),
                        locked: acct.get("Locked").and_then(|v| v.as_bool()).unwrap_or(false),
                    });
                }
            }
        }
        Ok(users)
    }

    /// Create a new user account.
    pub async fn create_user(
        &self,
        username: &str,
        password: &str,
        role: &str,
    ) -> Result<Value> {
        self.post("/redfish/v1/AccountService/Accounts", &serde_json::json!({
            "UserName": username,
            "Password": password,
            "RoleId": role,
            "Enabled": true
        })).await
    }

    /// Change a user's password.
    pub async fn change_password(&self, account_id: &str, new_password: &str) -> Result<Value> {
        self.patch(
            &format!("/redfish/v1/AccountService/Accounts/{}", account_id),
            &serde_json::json!({ "Password": new_password }),
        ).await
    }

    /// Set a user's role.
    pub async fn set_user_role(&self, account_id: &str, role: &str) -> Result<Value> {
        self.patch(
            &format!("/redfish/v1/AccountService/Accounts/{}", account_id),
            &serde_json::json!({ "RoleId": role }),
        ).await
    }

    /// Enable or disable a user account.
    pub async fn set_user_enabled(&self, account_id: &str, enabled: bool) -> Result<Value> {
        self.patch(
            &format!("/redfish/v1/AccountService/Accounts/{}", account_id),
            &serde_json::json!({ "Enabled": enabled }),
        ).await
    }

    /// Unlock a locked user account.
    pub async fn unlock_user(&self, account_id: &str) -> Result<Value> {
        self.patch(
            &format!("/redfish/v1/AccountService/Accounts/{}", account_id),
            &serde_json::json!({ "Locked": false }),
        ).await
    }

    /// Delete a user account.
    pub async fn delete_user(&self, account_id: &str) -> Result<()> {
        self.delete(&format!("/redfish/v1/AccountService/Accounts/{}", account_id)).await
    }

    // --- Event Subscription (Simplified) ---

    /// Subscribe to Redfish events with a simplified interface.
    ///
    /// `params.severity_filter` can be "OK", "Warning", or "Critical" (BMC support varies).
    pub async fn subscribe(&self, params: &SubscribeParams<'_>) -> Result<Value> {
        let mut body = serde_json::json!({
            "Destination": params.destination,
            "Protocol": "Redfish",
            "Context": params.context.unwrap_or("rufish-subscription"),
        });

        if let Some(types) = params.event_types {
            body["EventTypes"] = serde_json::json!(types);
        }
        if let Some(severity) = params.severity_filter {
            // RegistryPrefix-based filtering (Redfish 1.5+)
            body["RegistryPrefixes"] = serde_json::json!(["Base"]);
            body["MessageIds"] = Value::Null;
            // Some BMCs use EventFormatType + severity
            body["Context"] = serde_json::json!(
                format!("{}|severity={}", params.context.unwrap_or("rufish"), severity)
            );
        }

        self.post("/redfish/v1/EventService/Subscriptions", &body).await
    }

    // --- SSE (Server-Sent Events) ---

    /// Open an SSE stream for real-time Redfish events.
    ///
    /// Returns an async `Stream` that yields `RedfishEvent` items.
    /// The BMC must support SSE (check EventService.ServerSentEventUri).
    pub async fn subscribe_sse(&self) -> Result<EventStream> {
        let event_svc = self.get("/redfish/v1/EventService").await?;
        let sse_uri = event_svc
            .get("ServerSentEventUri")
            .and_then(|v| v.as_str())
            .unwrap_or("/redfish/v1/SSE");

        let url = format!("{}{}", self.base_url, sse_uri);
        let mut req = self.client.get(&url).header("Accept", "text/event-stream");
        if let Some(token) = &self.session_token {
            req = req.header("X-Auth-Token", token);
        } else {
            req = req.basic_auth(&self.username, Some(&self.password));
        }

        let resp = req.send().await?;
        if !resp.status().is_success() {
            return Err(RedfishError::Api {
                status: resp.status().as_u16(),
                message: "SSE connection failed".to_string(),
            });
        }

        Ok(EventStream::new(resp))
    }

    // --- BIOS Config Export/Import ---

    /// Export BIOS configuration from a system as a portable config.
    pub async fn export_bios_config(&self, system_id: &str) -> Result<BiosConfig> {
        let system = self.get(&format!("/redfish/v1/Systems/{}", system_id)).await?;
        let bios = self.get(&format!("/redfish/v1/Systems/{}/Bios", system_id)).await?;

        let attributes = bios
            .pointer("/Attributes")
            .and_then(|v| v.as_object())
            .map(|obj| obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
            .unwrap_or_default();

        Ok(BiosConfig {
            source: Some(BiosConfigSource {
                host: Some(self.base_url.clone()),
                system_id: Some(system_id.to_string()),
                model: system.get("Model").and_then(|v| v.as_str()).map(String::from),
                bios_version: system.get("BiosVersion").and_then(|v| v.as_str()).map(String::from),
                exported_at: Some(chrono_now()),
            }),
            attributes,
        })
    }

    /// Import (apply) a BIOS configuration to a system.
    /// Only applies attributes that exist in the config. Takes effect on next boot.
    pub async fn import_bios_config(&self, system_id: &str, config: &BiosConfig) -> Result<Value> {
        let attrs = serde_json::to_value(&config.attributes)
            .map_err(|e| RedfishError::Parse(e.to_string()))?;
        self.set_bios_attributes(system_id, &attrs).await
    }

    /// Compare current BIOS settings against a config, returning differences.
    pub async fn diff_bios_config(
        &self,
        system_id: &str,
        config: &BiosConfig,
    ) -> Result<crate::bios_config::BiosConfigDiff> {
        let current = self.export_bios_config(system_id).await?;
        Ok(config.diff(&current))
    }

    // --- Hardware Topology ---

    /// Get the full hardware topology for UI visualization.
    pub async fn get_topology(&self, system_id: &str) -> Result<HardwareTopology> {
        let sys_val = self.get(&format!("/redfish/v1/Systems/{}", system_id)).await?;

        let mut processors = Vec::new();
        if let Ok(proc_col) = self.get(&format!("/redfish/v1/Systems/{}/Processors", system_id)).await {
            if let Some(members) = proc_col.get("Members").and_then(|v| v.as_array()) {
                for m in members {
                    if let Some(path) = m.get("@odata.id").and_then(|v| v.as_str()) {
                        if let Ok(p) = self.get(path).await {
                            processors.push(ComponentNode {
                                id: p.get("Id").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                                name: p.get("Name").and_then(|v| v.as_str()).map(String::from),
                                description: p.get("Model").and_then(|v| v.as_str()).map(String::from),
                                status: HealthStatus::from_str_opt(
                                    p.pointer("/Status/Health").and_then(|v| v.as_str()),
                                ),
                            });
                        }
                    }
                }
            }
        }

        let mut memory = Vec::new();
        if let Ok(mem_col) = self.get(&format!("/redfish/v1/Systems/{}/Memory", system_id)).await {
            if let Some(members) = mem_col.get("Members").and_then(|v| v.as_array()) {
                for m in members {
                    if let Some(path) = m.get("@odata.id").and_then(|v| v.as_str()) {
                        if let Ok(mem) = self.get(path).await {
                            let cap = mem.get("CapacityMiB").and_then(|v| v.as_u64());
                            let desc = cap.map(|c| format!("{} MiB", c));
                            memory.push(ComponentNode {
                                id: mem.get("Id").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                                name: mem.get("Name").and_then(|v| v.as_str()).map(String::from),
                                description: desc,
                                status: HealthStatus::from_str_opt(
                                    mem.pointer("/Status/Health").and_then(|v| v.as_str()),
                                ),
                            });
                        }
                    }
                }
            }
        }

        let system_node = SystemNode {
            id: system_id.to_string(),
            name: sys_val.get("Name").and_then(|v| v.as_str()).map(String::from),
            model: sys_val.get("Model").and_then(|v| v.as_str()).map(String::from),
            manufacturer: sys_val.get("Manufacturer").and_then(|v| v.as_str()).map(String::from),
            serial_number: sys_val.get("SerialNumber").and_then(|v| v.as_str()).map(String::from),
            power_state: sys_val.get("PowerState").and_then(|v| v.as_str()).map(String::from),
            status: HealthStatus::from_str_opt(
                sys_val.pointer("/Status/Health").and_then(|v| v.as_str()),
            ),
            processors,
            memory,
        };

        let mut chassis_nodes = Vec::new();
        if let Ok(chassis_col) = self.get("/redfish/v1/Chassis").await {
            if let Some(members) = chassis_col.get("Members").and_then(|v| v.as_array()) {
                for m in members {
                    if let Some(path) = m.get("@odata.id").and_then(|v| v.as_str()) {
                        if let Ok(c) = self.get(path).await {
                            chassis_nodes.push(ChassisNode {
                                id: c.get("Id").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                                name: c.get("Name").and_then(|v| v.as_str()).map(String::from),
                                chassis_type: c.get("ChassisType").and_then(|v| v.as_str()).map(String::from),
                                model: c.get("Model").and_then(|v| v.as_str()).map(String::from),
                                serial_number: c.get("SerialNumber").and_then(|v| v.as_str()).map(String::from),
                                status: HealthStatus::from_str_opt(
                                    c.pointer("/Status/Health").and_then(|v| v.as_str()),
                                ),
                            });
                        }
                    }
                }
            }
        }

        let mut manager_nodes = Vec::new();
        if let Ok(mgr_col) = self.get("/redfish/v1/Managers").await {
            if let Some(members) = mgr_col.get("Members").and_then(|v| v.as_array()) {
                for m in members {
                    if let Some(path) = m.get("@odata.id").and_then(|v| v.as_str()) {
                        if let Ok(mgr) = self.get(path).await {
                            manager_nodes.push(ManagerNode {
                                id: mgr.get("Id").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                                name: mgr.get("Name").and_then(|v| v.as_str()).map(String::from),
                                manager_type: mgr.get("ManagerType").and_then(|v| v.as_str()).map(String::from),
                                firmware_version: mgr.get("FirmwareVersion").and_then(|v| v.as_str()).map(String::from),
                                status: HealthStatus::from_str_opt(
                                    mgr.pointer("/Status/Health").and_then(|v| v.as_str()),
                                ),
                            });
                        }
                    }
                }
            }
        }

        Ok(HardwareTopology {
            system: system_node,
            chassis: chassis_nodes,
            managers: manager_nodes,
        })
    }

    // --- Firmware Update with Progress ---

    /// Perform a firmware update and track progress until completion.
    ///
    /// `progress_cb` is called with (task_state, percent_complete) on each poll.
    pub async fn update_firmware_with_progress<F>(
        &self,
        image_uri: &str,
        max_wait_secs: u64,
        mut progress_cb: F,
    ) -> Result<Task>
    where
        F: FnMut(&str, Option<u32>),
    {
        let resp = self.post(
            "/redfish/v1/UpdateService/Actions/UpdateService.SimpleUpdate",
            &serde_json::json!({ "ImageURI": image_uri }),
        ).await?;

        let task_id = resp
            .pointer("/Id")
            .or_else(|| resp.pointer("/@odata.id"))
            .and_then(|v| v.as_str())
            .map(|s| s.rsplit('/').next().unwrap_or(s).to_string())
            .ok_or_else(|| RedfishError::Parse("No task ID in update response".to_string()))?;

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(max_wait_secs);
        loop {
            let task_val = self.get(&format!("/redfish/v1/TaskService/Tasks/{}", task_id)).await?;
            let state = task_val.get("TaskState").and_then(|v| v.as_str()).unwrap_or("Unknown");
            let percent = task_val.get("PercentComplete").and_then(|v| v.as_u64()).map(|p| p as u32);

            progress_cb(state, percent);

            match state {
                "Completed" | "Exception" | "Killed" | "Cancelled" => {
                    return self.get_task(&task_id).await;
                }
                _ => {}
            }
            if std::time::Instant::now() > deadline {
                return self.get_task(&task_id).await;
            }
            tokio::time::sleep(std::time::Duration::from_secs(3)).await;
        }
    }

    // --- Auto-Retry with Session Renewal ---

    /// GET with automatic retry and session renewal on 401.
    pub async fn get_with_retry(&mut self, path: &str, max_retries: u32) -> Result<Value> {
        let mut retries = 0;
        loop {
            match self.get(path).await {
                Ok(val) => return Ok(val),
                Err(RedfishError::SessionExpired) if retries < max_retries => {
                    log::debug!("Session expired, re-authenticating (attempt {})", retries + 1);
                    self.login().await?;
                    retries += 1;
                }
                Err(RedfishError::Http(_)) if retries < max_retries => {
                    retries += 1;
                    tokio::time::sleep(std::time::Duration::from_secs(1 << retries)).await;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// PATCH with automatic retry and session renewal on 401.
    pub async fn patch_with_retry(
        &mut self,
        path: &str,
        body: &Value,
        max_retries: u32,
    ) -> Result<Value> {
        let mut retries = 0;
        loop {
            match self.patch(path, body).await {
                Ok(val) => return Ok(val),
                Err(RedfishError::SessionExpired) if retries < max_retries => {
                    self.login().await?;
                    retries += 1;
                }
                Err(RedfishError::Http(_)) if retries < max_retries => {
                    retries += 1;
                    tokio::time::sleep(std::time::Duration::from_secs(1 << retries)).await;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// POST with automatic retry and session renewal on 401.
    pub async fn post_with_retry(
        &mut self,
        path: &str,
        body: &Value,
        max_retries: u32,
    ) -> Result<Value> {
        let mut retries = 0;
        loop {
            match self.post(path, body).await {
                Ok(val) => return Ok(val),
                Err(RedfishError::SessionExpired) if retries < max_retries => {
                    self.login().await?;
                    retries += 1;
                }
                Err(RedfishError::Http(_)) if retries < max_retries => {
                    retries += 1;
                    tokio::time::sleep(std::time::Duration::from_secs(1 << retries)).await;
                }
                Err(e) => return Err(e),
            }
        }
    }

    // --- Internal helpers ---

    async fn auth_get(&self, url: &str) -> Result<Response> {
        let mut req = self.client.get(url);
        if let Some(token) = &self.session_token {
            req = req.header("X-Auth-Token", token);
        } else {
            req = req.basic_auth(&self.username, Some(&self.password));
        }
        Ok(req.send().await?)
    }

    async fn handle_response(&self, resp: Response) -> Result<Value> {
        let status = resp.status();
        if status.is_success() {
            let body = resp.text().await?;
            if body.is_empty() {
                Ok(Value::Null)
            } else {
                serde_json::from_str(&body).map_err(|e| RedfishError::Parse(e.to_string()))
            }
        } else if status == StatusCode::NOT_FOUND {
            Err(RedfishError::NotFound(resp.url().to_string()))
        } else if status == StatusCode::UNAUTHORIZED {
            Err(RedfishError::SessionExpired)
        } else {
            let code = status.as_u16();
            let text = resp.text().await.unwrap_or_default();
            Err(RedfishError::Api { status: code, message: text })
        }
    }
}

/// Simple ISO 8601 timestamp without external chrono dependency.
fn chrono_now() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    // Basic UTC timestamp
    let days = secs / 86400;
    let time_secs = secs % 86400;
    let hours = time_secs / 3600;
    let minutes = (time_secs % 3600) / 60;
    let seconds = time_secs % 60;

    // Days since 1970-01-01
    let mut y = 1970i64;
    let mut remaining_days = days as i64;
    loop {
        let days_in_year = if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) { 366 } else { 365 };
        if remaining_days < days_in_year { break; }
        remaining_days -= days_in_year;
        y += 1;
    }
    let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
    let month_days = [31, if leap { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    let mut m = 0;
    for md in &month_days {
        if remaining_days < *md { break; }
        remaining_days -= md;
        m += 1;
    }
    format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", y, m + 1, remaining_days + 1, hours, minutes, seconds)
}