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
use crate::cli::{
    InstanceCommand, InstanceCreateArgs, InstanceListArgs, InstancePriceArgs, parse_size_to_mib,
};
use crate::common::{resolve_account, resolve_address, submit_or_preview};
use aleph_sdk::client::{AlephAggregateClient, AlephClient, AlephMessageClient, MessageFilter};
use aleph_sdk::messages::InstanceBuilder;
use aleph_sdk::scheduler::{SchedulerClient, VmEntry};
use aleph_types::account::Account;
use aleph_types::chain::Address;
use aleph_types::channel::Channel;
use aleph_types::item_hash::ItemHash;
use aleph_types::message::execution::base::{Payment, PaymentType};
use aleph_types::message::execution::environment::{
    GpuDeviceClass, GpuProperties, HostRequirements, Hypervisor, NodeRequirements,
    TrustedExecutionEnvironment,
};
use aleph_types::message::execution::volume::{
    BaseVolume, EphemeralVolume, ImmutableVolume, MachineVolume, PersistentVolume,
    PersistentVolumeSize, VolumePersistence,
};
use aleph_types::message::{Message, MessageContentEnum, MessageType};
use aleph_types::timestamp::Timestamp;
use anyhow::{Context, Result, anyhow, bail};
use futures_util::StreamExt;
use memsizes::MiB;
use url::Url;

/// Source filter that surfaced this row from the CCN.
///
/// CCN queries are run separately for `addresses=` (sender) and `owners=`
/// (resource owner). A row may be in one set, the other, or both. Used to
/// decide whether the per-VM scheduler fallback should fire (only for rows
/// that came from the sender filter and were not enriched by the bulk call).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct SourceFlags {
    pub owner: bool,
    pub sender: bool,
}

impl SourceFlags {
    pub fn merge(&mut self, other: SourceFlags) {
        self.owner |= other.owner;
        self.sender |= other.sender;
    }
}

/// One row of `aleph instance list` output, extracted from an INSTANCE message.
///
/// Fields populated post-merge with data from the scheduler stay `None` when
/// the scheduler is unreachable or has no record of the VM.
#[derive(Debug, Clone)]
pub(crate) struct InstanceRow {
    pub item_hash: ItemHash,
    pub name: Option<String>,
    pub owner: Address,
    pub node_hash: Option<String>,
    pub created_at: Timestamp,
    /// Effective scheduler status, e.g. `dispatched`, `unschedulable`.
    pub status: Option<String>,
    /// Node hash where the VM is currently allocated, per the scheduler.
    pub allocated_node: Option<String>,
    /// Full scheduler entry, used for `--json` passthrough.
    pub scheduler_raw: Option<VmEntry>,
    pub source_flags: SourceFlags,
}

fn name_from_metadata(
    metadata: Option<&std::collections::HashMap<String, serde_json::Value>>,
) -> Option<String> {
    metadata
        .and_then(|m| m.get("name"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}

fn node_from_requirements(requirements: Option<&HostRequirements>) -> Option<String> {
    requirements
        .and_then(|r| r.node.as_ref())
        .and_then(|n| n.node_hash.clone())
}

/// First 12 chars of the item hash, lower-cased. Used in the text table.
fn format_item_hash_short(hash: &ItemHash) -> String {
    let s = hash.to_string();
    s.chars().take(12).collect()
}

/// Last 10 chars of a node hash. Returns `s` unchanged if shorter than 10.
fn format_node_short(node: &str) -> String {
    if node.len() <= 10 {
        return node.to_string();
    }
    node[node.len() - 10..].to_string()
}

/// Pure merge: copy scheduler fields onto rows whose `item_hash` is present
/// in the map. Rows without a match are left unchanged. Map entries with no
/// matching row are dropped (CCN remains authoritative).
pub(crate) fn merge_scheduler_into_rows(
    rows: &mut [InstanceRow],
    scheduler_by_hash: &std::collections::HashMap<ItemHash, VmEntry>,
) {
    for row in rows.iter_mut() {
        if let Some(entry) = scheduler_by_hash.get(&row.item_hash) {
            row.status = Some(entry.status.clone());
            row.allocated_node = entry.allocated_node.clone();
            row.scheduler_raw = Some(entry.clone());
        }
    }
}

/// Convert an INSTANCE message into a row. Returns `None` for non-instance
/// messages (defensive — callers already filter by `MessageType::Instance`,
/// but the CCN can occasionally return a mis-typed payload).
pub(crate) fn extract_instance_row(message: &Message) -> Option<InstanceRow> {
    let MessageContentEnum::Instance(instance) = message.content() else {
        return None;
    };
    Some(InstanceRow {
        item_hash: message.item_hash.clone(),
        name: name_from_metadata(instance.base.metadata.as_ref()),
        owner: message.owner().clone(),
        node_hash: node_from_requirements(instance.base.requirements.as_ref()),
        created_at: message.content.time.clone(),
        status: None,
        allocated_node: None,
        scheduler_raw: None,
        source_flags: SourceFlags::default(),
    })
}

/// Fetch all INSTANCE rows for `address`, deduped by item_hash.
/// Runs the sender filter and the owner filter in sequence and merges them
/// (the CCN ANDs `addresses` and `owners`; we want OR).
async fn fetch_instance_rows(
    aleph_client: &AlephClient,
    address: &Address,
) -> Result<Vec<InstanceRow>> {
    use std::collections::HashMap;

    let mut by_hash: HashMap<ItemHash, InstanceRow> = HashMap::new();

    let filters = [
        (
            MessageFilter {
                message_type: Some(MessageType::Instance),
                addresses: Some(vec![address.clone()]),
                ..Default::default()
            },
            SourceFlags {
                sender: true,
                owner: false,
            },
        ),
        (
            MessageFilter {
                message_type: Some(MessageType::Instance),
                owners: Some(vec![address.clone()]),
                ..Default::default()
            },
            SourceFlags {
                sender: false,
                owner: true,
            },
        ),
    ];

    for (filter, flags) in filters {
        let mut stream = Box::pin(aleph_client.get_messages_iterator(filter, None));
        while let Some(message) = stream.next().await {
            let message = message?;
            if let Some(mut row) = extract_instance_row(&message) {
                row.source_flags = flags;
                by_hash
                    .entry(row.item_hash.clone())
                    .and_modify(|existing| existing.source_flags.merge(flags))
                    .or_insert(row);
            } else {
                eprintln!(
                    "warning: skipping message {} with non-instance content",
                    message.item_hash
                );
            }
        }
    }

    let mut rows: Vec<InstanceRow> = by_hash.into_values().collect();
    // Newest first: sort by content.time descending.
    rows.sort_by(|a, b| {
        b.created_at
            .as_f64()
            .partial_cmp(&a.created_at.as_f64())
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    Ok(rows)
}

/// Bulk-fetch every VM the scheduler knows about for `address`, indexed by
/// `item_hash`. On HTTP / network error, prints a warning to stderr and
/// returns an empty map so the caller can degrade gracefully.
async fn fetch_scheduler_map(
    scheduler: &SchedulerClient,
    address: &Address,
) -> std::collections::HashMap<ItemHash, VmEntry> {
    use std::collections::HashMap;

    match scheduler.list_vms_by_owner(address).await {
        Ok(entries) => entries
            .into_iter()
            .map(|entry| (entry.vm_hash.clone(), entry))
            .collect(),
        Err(err) => {
            eprintln!("warning: scheduler unreachable, status/allocation unavailable: {err}");
            HashMap::new()
        }
    }
}

/// For rows the bulk owner-filtered call did not enrich (the rare
/// "sender but not owner" case), fire one per-VM call to fill in the gap.
/// Errors and 404s are silent: the row simply stays unenriched.
///
/// This is replaced by a single second bulk call once the scheduler ships
/// its `created_by` filter.
async fn enrich_with_fallback(
    scheduler: &SchedulerClient,
    rows: &[InstanceRow],
    scheduler_map: &mut std::collections::HashMap<ItemHash, VmEntry>,
) {
    for row in rows {
        let needs_fallback = !scheduler_map.contains_key(&row.item_hash)
            && row.source_flags.sender
            && !row.source_flags.owner;
        if !needs_fallback {
            continue;
        }
        match scheduler.get_vm(&row.item_hash).await {
            Ok(Some(entry)) => {
                scheduler_map.insert(row.item_hash.clone(), entry);
            }
            Ok(None) => {} // 404: scheduler has no record; row stays unenriched.
            Err(_) => {}   // silent per spec; bulk-call warning already printed.
        }
    }
}

async fn handle_instance_list(
    aleph_client: &AlephClient,
    scheduler_url: Url,
    json: bool,
    args: InstanceListArgs,
) -> Result<()> {
    let address = match args.address.as_deref() {
        Some(value) => resolve_address(value)?,
        None => {
            // Fall back to the current default signing account's address.
            // No --private-key is passed so chain is unused.
            let identity = crate::cli::IdentityArgs {
                account: None,
                private_key: None,
                chain: None,
            };
            let account = resolve_account(&identity)?;
            account.address().clone()
        }
    };

    let mut rows = fetch_instance_rows(aleph_client, &address).await?;

    let scheduler = SchedulerClient::new(scheduler_url);
    let mut scheduler_map = fetch_scheduler_map(&scheduler, &address).await;
    enrich_with_fallback(&scheduler, &rows, &mut scheduler_map).await;
    merge_scheduler_into_rows(&mut rows, &scheduler_map);

    render_rows(&rows, json)
}

const MISSING_VALUE: &str = "-";

fn format_rows_json(rows: &[InstanceRow]) -> serde_json::Value {
    let items: Vec<serde_json::Value> = rows
        .iter()
        .map(|r| {
            serde_json::json!({
                "item_hash": r.item_hash.to_string(),
                "name": r.name,
                "owner": r.owner.to_string(),
                "node_hash": r.node_hash,
                "created_at": r.created_at
                    .to_datetime()
                    .ok()
                    .map(|dt| dt.to_rfc3339()),
                "scheduler": r.scheduler_raw,
            })
        })
        .collect();
    serde_json::Value::Array(items)
}

fn format_rows_text(rows: &[InstanceRow]) -> String {
    use std::fmt::Write;

    const HASH_HEADER: &str = "ITEM_HASH";
    const NAME_HEADER: &str = "NAME";
    const OWNER_HEADER: &str = "OWNER";
    const STATUS_HEADER: &str = "STATUS";
    const ALLOC_HEADER: &str = "ALLOCATED";

    // Hash column: 12-char prefix.
    let hash_w = HASH_HEADER.len().max(12);
    let name_w = rows
        .iter()
        .map(|r| r.name.as_deref().unwrap_or(MISSING_VALUE).len())
        .chain(std::iter::once(NAME_HEADER.len()))
        .max()
        .unwrap_or(NAME_HEADER.len());
    let owner_w = rows
        .iter()
        .map(|r| r.owner.to_string().len())
        .chain(std::iter::once(OWNER_HEADER.len()))
        .max()
        .unwrap_or(OWNER_HEADER.len());
    let status_w = rows
        .iter()
        .map(|r| r.status.as_deref().unwrap_or(MISSING_VALUE).len())
        .chain(std::iter::once(STATUS_HEADER.len()))
        .max()
        .unwrap_or(STATUS_HEADER.len());

    let mut out = String::new();
    writeln!(
        out,
        "{:<hash_w$}  {:<name_w$}  {:<owner_w$}  {:<status_w$}  {}",
        HASH_HEADER,
        NAME_HEADER,
        OWNER_HEADER,
        STATUS_HEADER,
        ALLOC_HEADER,
        hash_w = hash_w,
        name_w = name_w,
        owner_w = owner_w,
        status_w = status_w,
    )
    .expect("writing to String cannot fail");

    for row in rows {
        let name = row.name.as_deref().unwrap_or(MISSING_VALUE);
        let status = row.status.as_deref().unwrap_or(MISSING_VALUE);
        let allocated = row
            .allocated_node
            .as_deref()
            .map(format_node_short)
            .unwrap_or_else(|| MISSING_VALUE.to_string());
        writeln!(
            out,
            "{:<hash_w$}  {:<name_w$}  {:<owner_w$}  {:<status_w$}  {}",
            format_item_hash_short(&row.item_hash),
            name,
            row.owner,
            status,
            allocated,
            hash_w = hash_w,
            name_w = name_w,
            owner_w = owner_w,
            status_w = status_w,
        )
        .expect("writing to String cannot fail");
    }
    out
}

fn render_rows(rows: &[InstanceRow], json: bool) -> Result<()> {
    if json {
        println!("{}", serde_json::to_string_pretty(&format_rows_json(rows))?);
    } else {
        print!("{}", format_rows_text(rows));
    }
    Ok(())
}

pub async fn handle_instance_command(
    aleph_client: &AlephClient,
    ccn_url: &Url,
    network_override: Option<&str>,
    json: bool,
    command: InstanceCommand,
) -> Result<()> {
    use super::crn;
    match command {
        InstanceCommand::Create(args) => {
            handle_instance_create(aleph_client, ccn_url, json, args).await?;
        }
        InstanceCommand::Price(args) => {
            handle_instance_price(aleph_client, json, args).await?;
        }
        InstanceCommand::List(args) => {
            let scheduler_url = crate::common::resolve_scheduler_url(network_override)?;
            handle_instance_list(aleph_client, scheduler_url, json, args).await?;
        }
        InstanceCommand::Start(args) => crn::handle_start(json, args).await?,
        InstanceCommand::Stop(args) => crn::handle_operation(json, args, "stop").await?,
        InstanceCommand::Reboot(args) => crn::handle_operation(json, args, "reboot").await?,
        InstanceCommand::Erase(args) => crn::handle_operation(json, args, "erase").await?,
        InstanceCommand::Logs(args) => crn::handle_logs(json, args).await?,
        InstanceCommand::Ssh(args) => {
            let scheduler_url = crate::common::resolve_scheduler_url(network_override)?;
            super::instance_ssh::handle_ssh(scheduler_url, args).await?;
        }
    }
    Ok(())
}

const SSH_PUBKEY_PREFIXES: &[&str] = &[
    "ssh-rsa",
    "ssh-ed25519",
    "ssh-dss",
    "ecdsa-sha2-nistp256",
    "ecdsa-sha2-nistp384",
    "ecdsa-sha2-nistp521",
    "sk-ssh-ed25519@openssh.com",
    "sk-ecdsa-sha2-nistp256@openssh.com",
];

pub(crate) fn validate_ssh_pubkey(key: &str, path: &std::path::Path) -> Result<()> {
    let has_valid_prefix = SSH_PUBKEY_PREFIXES
        .iter()
        .any(|prefix| key.starts_with(prefix));
    if !has_valid_prefix {
        bail!(
            "'{}' does not look like an SSH public key (expected a line starting with ssh-rsa, ssh-ed25519, etc.)",
            path.display()
        );
    }
    Ok(())
}

/// Parse a "key=value,key=value" string into a list of (key, value) pairs.
fn parse_kv_pairs(s: &str) -> Result<Vec<(&str, &str)>, String> {
    s.split(',')
        .map(|pair| {
            let (k, v) = pair
                .split_once('=')
                .ok_or_else(|| format!("invalid key=value pair: '{pair}'"))?;
            Ok((k.trim(), v.trim()))
        })
        .collect()
}

pub(crate) fn parse_persistent_volumes(specs: &[String]) -> Result<Vec<MachineVolume>> {
    specs
        .iter()
        .map(|spec| {
            let pairs = parse_kv_pairs(spec).map_err(anyhow::Error::msg)?;
            let mut name: Option<String> = None;
            let mut mount: Option<String> = None;
            let mut size_mib: Option<u64> = None;
            let mut persistence: Option<VolumePersistence> = None;
            let mut comment: Option<String> = None;
            for (k, v) in pairs {
                match k {
                    "name" => name = Some(v.to_string()),
                    "mount" => mount = Some(v.to_string()),
                    "size" => size_mib = Some(parse_size_to_mib(v).map_err(anyhow::Error::msg)?),
                    "persistence" => {
                        persistence = Some(match v {
                            "host" => VolumePersistence::Host,
                            "store" => VolumePersistence::Store,
                            _ => bail!("invalid persistence: '{v}'"),
                        })
                    }
                    "comment" => comment = Some(v.to_string()),
                    _ => bail!("unknown persistent volume key: '{k}'"),
                }
            }
            let size_mib = size_mib.context("persistent volume requires size")?;
            let mount = mount.context("persistent volume requires mount")?;
            Ok(MachineVolume::Persistent(PersistentVolume {
                base: BaseVolume {
                    comment,
                    mount: Some(mount.into()),
                },
                parent: None,
                persistence,
                name,
                size_mib: PersistentVolumeSize::try_from(size_mib)?,
            }))
        })
        .collect()
}

pub(crate) fn parse_ephemeral_volumes(specs: &[String]) -> Result<Vec<MachineVolume>> {
    specs
        .iter()
        .map(|spec| {
            let pairs = parse_kv_pairs(spec).map_err(anyhow::Error::msg)?;
            let mut mount: Option<String> = None;
            let mut size_mib: Option<u64> = None;
            for (k, v) in pairs {
                match k {
                    "mount" => mount = Some(v.to_string()),
                    "size" => size_mib = Some(parse_size_to_mib(v).map_err(anyhow::Error::msg)?),
                    _ => bail!("unknown ephemeral volume key: '{k}'"),
                }
            }
            let size_mib = size_mib.context("ephemeral volume requires size")?;
            let mount = mount.context("ephemeral volume requires mount")?;
            Ok(MachineVolume::Ephemeral(EphemeralVolume::new(
                size_mib, mount,
            )?))
        })
        .collect()
}

pub(crate) fn parse_immutable_volumes(specs: &[String]) -> Result<Vec<MachineVolume>> {
    specs
        .iter()
        .map(|spec| {
            let pairs = parse_kv_pairs(spec).map_err(anyhow::Error::msg)?;
            let mut reference: Option<String> = None;
            let mut mount: Option<String> = None;
            let mut use_latest = true;
            for (k, v) in pairs {
                match k {
                    "ref" => reference = Some(v.to_string()),
                    "mount" => mount = Some(v.to_string()),
                    "use_latest" => {
                        use_latest = v
                            .parse()
                            .map_err(|_| anyhow!("invalid use_latest: '{v}'"))?
                    }
                    _ => bail!("unknown immutable volume key: '{k}'"),
                }
            }
            let reference = reference.context("immutable volume requires ref")?;
            let mount = mount.context("immutable volume requires mount")?;
            let item_hash = reference.parse().map_err(|e| anyhow!("invalid ref: {e}"))?;
            Ok(MachineVolume::Immutable(ImmutableVolume {
                base: BaseVolume {
                    comment: None,
                    mount: Some(mount.into()),
                },
                reference: item_hash,
                use_latest,
            }))
        })
        .collect()
}

/// Resolve (vcpus, memory_mib, disk_mib) from flags when no `--size` slug is used.
/// Defaults: 1 vCPU, 2048 MiB memory; disk must be provided.
pub(crate) fn resolve_instance_specs_from_flags(
    vcpus: Option<u32>,
    memory_mib: Option<u64>,
    disk_mib: Option<u64>,
) -> Result<(u32, u64, u64)> {
    let disk_mib = disk_mib.context(
        "--disk-size is required when --size is not used \
         (or use --size to specify a tier slug like 1vcpu-2gb)",
    )?;
    Ok((vcpus.unwrap_or(1), memory_mib.unwrap_or(2048), disk_mib))
}

async fn handle_instance_create(
    aleph_client: &AlephClient,
    ccn_url: &Url,
    json: bool,
    mut args: InstanceCreateArgs,
) -> Result<()> {
    let dry_run = args.signing.dry_run;
    let account = resolve_account(&args.signing.identity)?;

    if args.interactive {
        crate::commands::instance_interactive::resolve_interactive(&mut args, aleph_client).await?;
    }

    // Read and validate SSH public keys
    let mut ssh_keys = Vec::new();
    for path in &args.ssh_pubkey_file {
        let content = std::fs::read_to_string(path).map_err(|e| {
            anyhow!(
                "failed to read SSH public key file '{}': {e}",
                path.display()
            )
        })?;
        let key = content.trim().to_string();
        validate_ssh_pubkey(&key, path)?;
        ssh_keys.push(key);
    }

    // Resolve instance specs: either from --size (tier lookup) or explicit flags.
    let (vcpus, memory_mib, disk_size_mib) = if let Some(slug) = &args.size {
        let pricing = aleph_client
            .get_pricing_aggregate()
            .await
            .map_err(|e| anyhow!("failed to fetch pricing tiers: {e}"))?;
        let instance_pricing = &pricing.pricing.instance;

        let tier = instance_pricing.find_tier_by_slug(slug).ok_or_else(|| {
            let available = instance_pricing.available_slugs().join(", ");
            anyhow!("unknown size '{slug}'. Available sizes: {available}")
        })?;

        let vcpus = args.vcpus.unwrap_or(tier.vcpus);
        let memory_mib = args.memory.unwrap_or(tier.memory_mib);
        let disk_size_mib = args.disk_size.unwrap_or(tier.disk_mib);

        eprintln!(
            "Size '{slug}': {vcpus} vCPUs, {} MiB memory, {} MiB disk",
            memory_mib, disk_size_mib,
        );

        (vcpus, memory_mib, disk_size_mib)
    } else {
        resolve_instance_specs_from_flags(args.vcpus, args.memory, args.disk_size)?
    };

    let disk_size = PersistentVolumeSize::try_from(disk_size_mib)
        .map_err(|e| anyhow!("invalid disk size: {e}"))?;

    let image = args.image.context("--image is required (or use -i)")?;
    let mut builder = InstanceBuilder::new(&account, image, disk_size)
        .vcpus(vcpus)
        .memory(MiB::from(memory_mib))
        .hypervisor(Hypervisor::Qemu)
        .payment(Payment {
            chain: None,
            receiver: None,
            payment_type: PaymentType::Credit,
        })
        .ssh_keys(ssh_keys);

    if let Some(owner) = args.on_behalf_of {
        builder = builder.on_behalf_of(resolve_address(&owner)?);
    }

    let mut metadata = std::collections::HashMap::new();
    metadata.insert("name".to_string(), serde_json::json!(args.name));
    builder = builder.metadata(metadata);

    // Confidential VM
    if args.confidential {
        let firmware: ItemHash = args
            .confidential_firmware
            .parse()
            .map_err(|e| anyhow!("invalid confidential firmware hash: {e}"))?;
        builder = builder.trusted_execution(TrustedExecutionEnvironment {
            firmware: Some(firmware),
            policy: 0x1, // NoDebug
        });
    }

    // GPU requirements
    let gpu_props = if let Some(gpu_names) = &args.gpu {
        let mut gpus = Vec::new();
        for name in gpu_names {
            gpus.push(resolve_gpu(name)?);
        }
        Some(gpus)
    } else {
        None
    };

    // Build host requirements if CRN hash or GPU is specified
    if args.crn_hash.is_some() || gpu_props.is_some() {
        let requirements = HostRequirements {
            cpu: None,
            node: args.crn_hash.map(|hash| NodeRequirements {
                owner: None,
                address_regex: None,
                node_hash: Some(hash.to_string()),
                terms_and_conditions: None,
            }),
            gpu: gpu_props,
        };
        builder = builder.requirements(requirements);
    }

    // Parse volumes
    let mut volumes = Vec::new();
    if let Some(specs) = &args.persistent_volume {
        volumes.extend(parse_persistent_volumes(specs)?);
    }
    if let Some(specs) = &args.ephemeral_volume {
        volumes.extend(parse_ephemeral_volumes(specs)?);
    }
    if let Some(specs) = &args.immutable_volume {
        volumes.extend(parse_immutable_volumes(specs)?);
    }
    if !volumes.is_empty() {
        builder = builder.volumes(volumes);
    }

    if let Some(ch) = args.channel {
        builder = builder.channel(Channel::from(ch));
    }

    let pending = builder.build()?;
    submit_or_preview(aleph_client, ccn_url, &pending, dry_run, json).await
}

/// Known GPU presets: (slug, pricing_model, vendor, device_name, device_class, device_id).
/// `pricing_model` matches the `model` field in pricing aggregate tiers.
const GPU_PRESETS: &[(&str, &str, &str, &str, &str, &str)] = &[
    (
        "rtx3090",
        "RTX 3090",
        "NVIDIA",
        "GA102 [GeForce RTX 3090]",
        "0300",
        "10de:2204",
    ),
    (
        "rtx4000ada",
        "RTX 4000 ADA",
        "NVIDIA",
        "AD104GL [RTX 4000 SFF Ada Generation]",
        "0300",
        "10de:27b0",
    ),
    (
        "rtx4090",
        "RTX 4090",
        "NVIDIA",
        "AD102 [GeForce RTX 4090]",
        "0300",
        "10de:2684",
    ),
    (
        "rtx5090",
        "RTX 5090",
        "NVIDIA",
        "GB202 [GeForce RTX 5090]",
        "0300",
        "10de:2684",
    ),
    (
        "l40s",
        "L40S",
        "NVIDIA",
        "AD102GL [L40S]",
        "0302",
        "10de:26b9",
    ),
    (
        "a100",
        "A100",
        "NVIDIA",
        "GA100 [A100 PCIe 80GB]",
        "0302",
        "10de:20b5",
    ),
    (
        "h100",
        "H100",
        "NVIDIA",
        "GH100 [H100 PCIe]",
        "0302",
        "10de:2331",
    ),
];

fn resolve_gpu(name: &str) -> Result<GpuProperties> {
    let lower = name.to_ascii_lowercase();
    for &(slug, _, vendor, device_name, class, device_id) in GPU_PRESETS {
        if lower == slug {
            let device_class = match class {
                "0300" => GpuDeviceClass::VgaCompatibleController,
                "0302" => GpuDeviceClass::_3DController,
                _ => unreachable!(),
            };
            return Ok(GpuProperties {
                vendor: vendor.to_string(),
                device_name: device_name.to_string(),
                device_class,
                device_id: device_id.to_string(),
            });
        }
    }
    let available: Vec<&str> = GPU_PRESETS.iter().map(|(n, ..)| *n).collect();
    Err(anyhow!(
        "unknown GPU model '{name}'. Available models: {}",
        available.join(", ")
    ))
}

fn print_available_gpus(pricing: &aleph_sdk::aggregate_models::pricing::PricingData) {
    let models = pricing.available_gpu_models();
    if models.is_empty() {
        eprintln!("No GPU models available.");
        return;
    }
    eprintln!("  {:<20} {:<16} {:<16} Tier", "Model", "Min size", "VRAM");
    for gpu in &models {
        let entity = match gpu.tier.as_str() {
            "standard" => &pricing.instance_gpu_standard,
            "premium" => &pricing.instance_gpu_premium,
            _ => continue,
        };
        let min_size = entity.slug_for_compute_units(gpu.compute_units);
        let vram = gpu
            .vram_mib
            .map(|v| format!("{} GiB", v / 1024))
            .unwrap_or_default();
        eprintln!(
            "  {:<20} {:<16} {:<16} {}",
            gpu.slug(),
            min_size,
            vram,
            gpu.tier
        );
    }
}

async fn handle_instance_price(
    aleph_client: &AlephClient,
    json: bool,
    args: InstancePriceArgs,
) -> Result<()> {
    let pricing = aleph_client
        .get_pricing_aggregate()
        .await
        .map_err(|e| anyhow!("failed to fetch pricing tiers: {e}"))?;

    if args.confidential && args.gpu.is_some() {
        bail!("--confidential and --gpu cannot be combined");
    }

    if args.list_gpus || args.gpu.as_deref() == Some("") {
        print_available_gpus(&pricing.pricing);
        return Ok(());
    }

    // Match the user-provided GPU name against pricing tier model names
    let gpu_model = if let Some(slug) = args.gpu.as_deref() {
        let models = pricing.pricing.available_gpu_models();
        let matched = models.iter().find(|m| m.slug() == slug);
        match matched {
            Some(m) => Some(m.clone()),
            None => {
                let names: Vec<String> = models.iter().map(|m| m.slug()).collect();
                bail!(
                    "unknown GPU model '{slug}'. Available models: {}",
                    names.join(", ")
                );
            }
        }
    } else {
        None
    };
    let instance_pricing = pricing.pricing.for_instance(
        args.confidential,
        gpu_model.as_ref().map(|m| m.name.as_str()),
    );

    let cu_price = instance_pricing
        .price
        .get("compute_unit")
        .context("missing compute_unit price in pricing aggregate")?;

    let credit_per_cu: f64 = cu_price
        .credit
        .parse()
        .map_err(|_| anyhow!("invalid credit price: '{}'", cu_price.credit))?;

    // Resolve specs: GPU tier, --size tier, or fully manual
    let (size_slug, compute_units, vcpus, memory_mib, disk_mib) = if let Some(gpu) = &gpu_model {
        // GPU: tier CU count is a lower bound; --size or --vcpus/--memory can raise it.
        let tier = instance_pricing
            .tiers
            .iter()
            .find(|t| t.model.as_deref() == Some(&gpu.name))
            .ok_or_else(|| anyhow!("GPU tier not found for '{}'", gpu.name))?;
        let min_cu = tier.compute_units;
        let cu_spec = &instance_pricing.compute_unit;
        let min_slug = instance_pricing.slug_for_compute_units(min_cu);

        let cu = if let Some(slug) = &args.size {
            // Resolve size slug to CU count and validate against GPU minimum
            let size_tier = instance_pricing.find_tier_by_slug(slug).ok_or_else(|| {
                let available: Vec<String> = instance_pricing
                    .tiers
                    .iter()
                    .filter(|t| t.model.is_none() && t.compute_units >= min_cu)
                    .map(|t| instance_pricing.tier_slug(t))
                    .collect();
                anyhow!(
                    "unknown size '{slug}' for GPU tier. Available sizes: {}",
                    available.join(", ")
                )
            })?;
            if size_tier.compute_units < min_cu {
                bail!(
                    "size '{slug}' ({} CU) is below the minimum for GPU '{}' (min: {min_slug}, {min_cu} CU)",
                    size_tier.compute_units,
                    gpu.slug(),
                );
            }
            size_tier.compute_units
        } else if args.vcpus.is_some() || args.memory.is_some() {
            // Compute CU count from raw resources, validate against GPU minimum
            let cu_from_vcpus = args.vcpus.map(|v| v.div_ceil(cu_spec.vcpus)).unwrap_or(0);
            let cu_from_mem = args
                .memory
                .map(|m| m.div_ceil(cu_spec.memory_mib) as u32)
                .unwrap_or(0);
            let requested_cu = cu_from_vcpus.max(cu_from_mem);
            if requested_cu < min_cu {
                bail!(
                    "requested resources are below the minimum for GPU '{}' (min: {min_slug}, {min_cu} CU)",
                    gpu.slug(),
                );
            }
            requested_cu
        } else {
            min_cu
        };

        let disk = args.disk_size.unwrap_or(cu as u64 * cu_spec.disk_mib);
        (
            None,
            cu,
            cu * cu_spec.vcpus,
            cu as u64 * cu_spec.memory_mib,
            disk,
        )
    } else if let Some(slug) = &args.size {
        let tier = instance_pricing.find_tier_by_slug(slug).ok_or_else(|| {
            let available = instance_pricing.available_slugs().join(", ");
            anyhow!("unknown size '{slug}'. Available sizes: {available}")
        })?;
        (
            Some(slug.clone()),
            tier.compute_units,
            args.vcpus.unwrap_or(tier.vcpus),
            args.memory.unwrap_or(tier.memory_mib),
            args.disk_size.unwrap_or(tier.disk_mib),
        )
    } else {
        match (args.vcpus, args.memory, args.disk_size) {
            (Some(vcpus), Some(memory), Some(disk)) => {
                let cu = &instance_pricing.compute_unit;
                let cu_from_vcpus = vcpus.div_ceil(cu.vcpus);
                let cu_from_mem = memory.div_ceil(cu.memory_mib) as u32;
                let compute_units = cu_from_vcpus.max(cu_from_mem);
                let actual_vcpus = compute_units * cu.vcpus;
                let actual_memory = compute_units as u64 * cu.memory_mib;
                (None, compute_units, actual_vcpus, actual_memory, disk)
            }
            _ => {
                bail!(
                    "--size is required unless --vcpus, --memory, and --disk-size are all specified"
                );
            }
        }
    };

    // Compute cost (credits/hour)
    let compute_credits = credit_per_cu * compute_units as f64;

    // Storage cost (credits/hour): all disk is charged, then a discount is applied
    // for the storage included in each compute unit.
    let storage_credit_per_mib: f64 = instance_pricing
        .price
        .get("storage")
        .map(|p| p.credit.parse::<f64>().unwrap_or(0.0))
        .unwrap_or(0.0);

    let storage_credits = storage_credit_per_mib * disk_mib as f64;
    let included_storage_mib = instance_pricing.compute_unit.disk_mib as f64 * compute_units as f64;
    let max_storage_discount = storage_credit_per_mib * included_storage_mib;
    let storage_discount = storage_credits.min(max_storage_discount);
    let extra_storage_credits = storage_credits - storage_discount;

    let total_credits = compute_credits + extra_storage_credits;
    let total_dollars = total_credits * 1e-6;

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "size": size_slug,
                "compute_units": compute_units,
                "vcpus": vcpus,
                "memory_mib": memory_mib,
                "disk_mib": disk_mib,
                "gpu": gpu_model.as_ref().map(|m| m.slug()),
                "confidential": args.confidential,
                "compute_credits_per_hour": compute_credits,
                "storage_credits_per_hour": extra_storage_credits,
                "total_credits_per_hour": total_credits,
                "dollars_per_hour": total_dollars,
            }))?
        );
    } else {
        if let Some(slug) = &size_slug {
            eprintln!("Size:    {slug}");
        }
        if let Some(gpu) = &gpu_model {
            eprintln!("GPU:     {}", gpu.slug());
        }
        if args.confidential {
            eprintln!("Type:    confidential");
        }
        eprintln!("vCPUs:   {}", vcpus);
        eprintln!("Memory:  {} MiB", memory_mib);
        eprintln!("Disk:    {} MiB", disk_mib);
        if extra_storage_credits > 0.0 {
            eprintln!(
                "Cost:    {:.0} credits/hour (${:.4}/hour) — compute: {:.0}, extra storage: {:.0}",
                total_credits, total_dollars, compute_credits, extra_storage_credits
            );
        } else {
            eprintln!(
                "Cost:    {:.0} credits/hour (${:.4}/hour)",
                total_credits, total_dollars
            );
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::{parse_image, parse_size_to_mib};

    #[test]
    fn parse_kv_pairs_basic() {
        let pairs = parse_kv_pairs("name=data,mount=/opt/data,size=1GiB").unwrap();
        assert_eq!(
            pairs,
            vec![("name", "data"), ("mount", "/opt/data"), ("size", "1GiB")]
        );
    }

    #[test]
    fn parse_kv_pairs_missing_equals() {
        assert!(parse_kv_pairs("invalid").is_err());
    }

    #[test]
    fn parse_size_binary_units() {
        assert_eq!(parse_size_to_mib("100MiB").unwrap(), 100);
        assert_eq!(parse_size_to_mib("1GiB").unwrap(), 1024);
        assert_eq!(parse_size_to_mib("2GiB").unwrap(), 2048);
        assert_eq!(parse_size_to_mib("1TiB").unwrap(), 1024 * 1024);
    }

    #[test]
    fn parse_size_decimal_units() {
        // 1 GB = 1_000_000_000 bytes = ~953.674 MiB
        assert_eq!(parse_size_to_mib("1GB").unwrap(), 954);
        // 20 GB = ~19073.486 MiB
        assert_eq!(parse_size_to_mib("20GB").unwrap(), 19073);
        // 100 MB = ~95.367 MiB
        assert_eq!(parse_size_to_mib("100MB").unwrap(), 95);
    }

    #[test]
    fn parse_size_case_insensitive() {
        assert_eq!(parse_size_to_mib("1gib").unwrap(), 1024);
        assert_eq!(parse_size_to_mib("1GIB").unwrap(), 1024);
        assert_eq!(
            parse_size_to_mib("1gb").unwrap(),
            parse_size_to_mib("1GB").unwrap()
        );
    }

    #[test]
    fn parse_size_rejects_bare_numbers() {
        assert!(parse_size_to_mib("1024").is_err());
    }

    #[test]
    fn parse_size_rejects_unknown_units() {
        assert!(parse_size_to_mib("100KiB").is_err());
    }

    #[test]
    fn parse_persistent_volume_basic() {
        let specs = vec!["name=data,mount=/opt/data,size=1GiB".to_string()];
        let volumes = parse_persistent_volumes(&specs).unwrap();
        assert_eq!(volumes.len(), 1);
        assert!(matches!(volumes[0], MachineVolume::Persistent(_)));
    }

    #[test]
    fn parse_persistent_volume_with_persistence() {
        let specs = vec!["name=db,mount=/var/db,size=500MiB,persistence=store".to_string()];
        let volumes = parse_persistent_volumes(&specs).unwrap();
        if let MachineVolume::Persistent(v) = &volumes[0] {
            assert_eq!(v.persistence, Some(VolumePersistence::Store));
            assert_eq!(v.name, Some("db".to_string()));
        } else {
            panic!("expected persistent volume");
        }
    }

    #[test]
    fn parse_persistent_volume_with_comment() {
        let specs = vec!["name=db,mount=/var/db,size=500MiB,comment=My database".to_string()];
        let volumes = parse_persistent_volumes(&specs).unwrap();
        if let MachineVolume::Persistent(v) = &volumes[0] {
            assert_eq!(v.base.comment, Some("My database".to_string()));
        } else {
            panic!("expected persistent volume");
        }
    }

    #[test]
    fn parse_persistent_volume_missing_size() {
        let specs = vec!["name=data,mount=/opt/data".to_string()];
        assert!(parse_persistent_volumes(&specs).is_err());
    }

    #[test]
    fn parse_persistent_volume_missing_mount() {
        let specs = vec!["name=data,size=1GiB".to_string()];
        assert!(parse_persistent_volumes(&specs).is_err());
    }

    #[test]
    fn parse_ephemeral_volume_basic() {
        let specs = vec!["mount=/tmp/scratch,size=100MiB".to_string()];
        let volumes = parse_ephemeral_volumes(&specs).unwrap();
        assert_eq!(volumes.len(), 1);
        assert!(matches!(volumes[0], MachineVolume::Ephemeral(_)));
    }

    #[test]
    fn parse_ephemeral_volume_missing_mount() {
        let specs = vec!["size=100MiB".to_string()];
        assert!(parse_ephemeral_volumes(&specs).is_err());
    }

    #[test]
    fn parse_immutable_volume_basic() {
        let specs = vec![
            "ref=d281eb8a69ba1f4dda2d71aaf3ded06caa92edd690ef3d0632f41aa91167762c,mount=/opt/pkg"
                .to_string(),
        ];
        let volumes = parse_immutable_volumes(&specs).unwrap();
        assert_eq!(volumes.len(), 1);
        if let MachineVolume::Immutable(v) = &volumes[0] {
            assert!(v.use_latest); // default
        } else {
            panic!("expected immutable volume");
        }
    }

    #[test]
    fn parse_immutable_volume_use_latest_false() {
        let specs = vec![
            "ref=d281eb8a69ba1f4dda2d71aaf3ded06caa92edd690ef3d0632f41aa91167762c,mount=/opt/pkg,use_latest=false"
                .to_string(),
        ];
        let volumes = parse_immutable_volumes(&specs).unwrap();
        if let MachineVolume::Immutable(v) = &volumes[0] {
            assert!(!v.use_latest);
        } else {
            panic!("expected immutable volume");
        }
    }

    #[test]
    fn parse_immutable_volume_missing_ref() {
        let specs = vec!["mount=/opt/pkg".to_string()];
        assert!(parse_immutable_volumes(&specs).is_err());
    }

    #[test]
    fn parse_multiple_volumes() {
        let persistent = vec![
            "name=a,mount=/a,size=100MiB".to_string(),
            "name=b,mount=/b,size=200MiB".to_string(),
        ];
        let volumes = parse_persistent_volumes(&persistent).unwrap();
        assert_eq!(volumes.len(), 2);
    }

    #[test]
    fn validate_ssh_pubkey_accepts_valid_keys() {
        let path = std::path::Path::new("test.pub");
        validate_ssh_pubkey("ssh-rsa AAAAB3... user@host", path).unwrap();
        validate_ssh_pubkey("ssh-ed25519 AAAAC3... user@host", path).unwrap();
        validate_ssh_pubkey("ecdsa-sha2-nistp256 AAAAE2... user@host", path).unwrap();
        validate_ssh_pubkey("sk-ssh-ed25519@openssh.com AAAAG... user@host", path).unwrap();
    }

    #[test]
    fn validate_ssh_pubkey_rejects_private_key() {
        let path = std::path::Path::new("id_rsa");
        assert!(validate_ssh_pubkey("-----BEGIN OPENSSH PRIVATE KEY-----", path).is_err());
    }

    #[test]
    fn validate_ssh_pubkey_rejects_garbage() {
        let path = std::path::Path::new("garbage.txt");
        assert!(validate_ssh_pubkey("not a key at all", path).is_err());
    }

    #[test]
    fn parse_image_preset_ubuntu24() {
        let hash = parse_image("ubuntu24").unwrap();
        assert_eq!(
            hash.to_string(),
            "5330dcefe1857bcd97b7b7f24d1420a7d46232d53f27be280c8a7071d88bd84e"
        );
    }

    #[test]
    fn parse_image_preset_case_insensitive() {
        let hash = parse_image("Ubuntu22").unwrap();
        assert_eq!(
            hash.to_string(),
            "4a0f62da42f4478544616519e6f5d58adb1096e069b392b151d47c3609492d0c"
        );
    }

    #[test]
    fn parse_image_raw_hash() {
        let hash = parse_image("d281eb8a69ba1f4dda2d71aaf3ded06caa92edd690ef3d0632f41aa91167762c")
            .unwrap();
        assert_eq!(
            hash.to_string(),
            "d281eb8a69ba1f4dda2d71aaf3ded06caa92edd690ef3d0632f41aa91167762c"
        );
    }

    #[test]
    fn parse_image_ipfs_cid() {
        let hash = parse_image("QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG").unwrap();
        assert!(matches!(hash, aleph_types::item_hash::ItemHash::Ipfs(_)));
    }

    #[test]
    fn parse_image_invalid() {
        assert!(parse_image("windows11").is_err());
        assert!(parse_image("abc").is_err());
    }

    use std::collections::HashMap;

    #[test]
    fn name_from_metadata_returns_string_value() {
        let mut meta = HashMap::new();
        meta.insert("name".to_string(), serde_json::json!("my-vm"));
        assert_eq!(name_from_metadata(Some(&meta)), Some("my-vm".to_string()));
    }

    #[test]
    fn name_from_metadata_returns_none_when_missing() {
        assert_eq!(name_from_metadata(None), None);
        let empty: HashMap<String, serde_json::Value> = HashMap::new();
        assert_eq!(name_from_metadata(Some(&empty)), None);
    }

    #[test]
    fn name_from_metadata_returns_none_for_non_string() {
        let mut meta = HashMap::new();
        meta.insert("name".to_string(), serde_json::json!(42));
        assert_eq!(name_from_metadata(Some(&meta)), None);
    }

    #[test]
    fn node_from_requirements_returns_node_hash() {
        let req = HostRequirements {
            cpu: None,
            node: Some(NodeRequirements {
                owner: None,
                address_regex: None,
                node_hash: Some("aa00".to_string()),
                terms_and_conditions: None,
            }),
            gpu: None,
        };
        assert_eq!(node_from_requirements(Some(&req)), Some("aa00".to_string()));
    }

    #[test]
    fn node_from_requirements_returns_none_when_no_requirements() {
        assert_eq!(node_from_requirements(None), None);
    }

    #[test]
    fn node_from_requirements_returns_none_when_no_node() {
        let req = HostRequirements {
            cpu: None,
            node: None,
            gpu: None,
        };
        assert_eq!(node_from_requirements(Some(&req)), None);
    }

    #[test]
    fn node_from_requirements_returns_none_when_node_hash_missing() {
        let req = HostRequirements {
            cpu: None,
            node: Some(NodeRequirements {
                owner: None,
                address_regex: None,
                node_hash: None,
                terms_and_conditions: None,
            }),
            gpu: None,
        };
        assert_eq!(node_from_requirements(Some(&req)), None);
    }

    #[test]
    fn extract_instance_row_from_fixture() {
        const FIXTURE: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../fixtures/messages/instance/instance-gpu-payg.json"
        ));
        let message: Message = serde_json::from_str(FIXTURE).expect("fixture parses");
        let row = extract_instance_row(&message).expect("instance row extracted");
        assert_eq!(
            row.item_hash.to_string(),
            "a41fb91c3e68370759b72338dd1947f18e2ed883837aec5dc731d5f427f90564"
        );
        assert_eq!(row.name.as_deref(), Some("gpu-l40s-2"));
        assert_eq!(
            row.owner.to_string(),
            "0x238224C744F4b90b4494516e074D2676ECfC6803"
        );
        assert_eq!(
            row.node_hash.as_deref(),
            Some("dc3d1d194a990b5c54380c3c0439562fefa42f5a46807cba1c500ec3affecf04")
        );
    }

    fn sample_row(
        hash: &str,
        name: Option<&str>,
        node: Option<&str>,
        epoch_seconds: f64,
    ) -> InstanceRow {
        InstanceRow {
            item_hash: hash.parse().expect("valid item hash"),
            name: name.map(|s| s.to_string()),
            owner: Address::from("0xAbCd1234567890aBcDEf1234567890AbCdEF1234".to_string()),
            node_hash: node.map(|s| s.to_string()),
            created_at: Timestamp::from(epoch_seconds),
            status: None,
            allocated_node: None,
            scheduler_raw: None,
            source_flags: Default::default(),
        }
    }

    #[test]
    fn format_rows_json_shape() {
        // Unix epoch 1_700_000_000 = 2023-11-14T22:13:20Z — used as a known-good
        // anchor to verify `created_at` is emitted as RFC 3339.
        let rows = vec![
            sample_row(
                "0000000000000000000000000000000000000000000000000000000000000001",
                Some("vm-a"),
                Some("aa00"),
                1_700_000_000.0,
            ),
            sample_row(
                "0000000000000000000000000000000000000000000000000000000000000002",
                None,
                None,
                1_700_000_001.0,
            ),
        ];
        let value = format_rows_json(&rows);
        let arr = value.as_array().expect("top-level is array");
        assert_eq!(arr.len(), 2);

        // First row: all fields populated.
        assert_eq!(
            arr[0]["item_hash"],
            "0000000000000000000000000000000000000000000000000000000000000001"
        );
        assert_eq!(arr[0]["name"], "vm-a");
        assert_eq!(
            arr[0]["owner"],
            "0xAbCd1234567890aBcDEf1234567890AbCdEF1234"
        );
        assert_eq!(arr[0]["node_hash"], "aa00");
        assert_eq!(arr[0]["created_at"], "2023-11-14T22:13:20+00:00");

        // Second row: missing name and node_hash serialize as JSON null.
        assert!(arr[1]["name"].is_null());
        assert!(arr[1]["node_hash"].is_null());

        // No scheduler data in these fixture rows: field must be null.
        assert!(arr[0]["scheduler"].is_null());
        assert!(arr[1]["scheduler"].is_null());
    }

    #[test]
    fn format_rows_json_includes_scheduler_object_when_enriched() {
        // Build a row and populate scheduler fields manually (mimics what
        // merge_scheduler_into_rows would do).
        let mut row = sample_row(
            "5a586d6f59f6c2e6862f155204626dcf01a6ec1107e7aba67063cd48ffe41d99",
            Some("foo"),
            Some("requested-node"),
            1_700_000_000.0,
        );
        row.status = Some("dispatched".to_string());
        row.allocated_node =
            Some("d704be0b15e2fb600c5998581cb9af01bd74a9cf61b586ccc849ad78e0709d77".to_string());
        row.scheduler_raw = Some(make_vm_entry(
            "5a586d6f59f6c2e6862f155204626dcf01a6ec1107e7aba67063cd48ffe41d99",
            "dispatched",
            Some("d704be0b15e2fb600c5998581cb9af01bd74a9cf61b586ccc849ad78e0709d77"),
        ));

        let v = format_rows_json(&[row]);
        let arr = v.as_array().expect("json array");
        assert_eq!(arr[0]["scheduler"]["status"], "dispatched");
        assert_eq!(
            arr[0]["scheduler"]["allocated_node"],
            "d704be0b15e2fb600c5998581cb9af01bd74a9cf61b586ccc849ad78e0709d77"
        );
        // Top-level node_hash (CCN-requested) preserved alongside scheduler.allocated_node.
        assert_eq!(arr[0]["node_hash"], "requested-node");
    }

    #[test]
    fn format_rows_json_scheduler_is_null_when_unenriched() {
        let row = sample_row(
            "5a586d6f59f6c2e6862f155204626dcf01a6ec1107e7aba67063cd48ffe41d99",
            Some("foo"),
            None,
            1_700_000_000.0,
        );
        let v = format_rows_json(&[row]);
        let arr = v.as_array().expect("json array");
        assert!(arr[0]["scheduler"].is_null());
    }

    #[test]
    fn format_rows_text_header_and_placeholders() {
        let rows = vec![
            sample_row(
                "0000000000000000000000000000000000000000000000000000000000000001",
                Some("vm-a"),
                Some("aa00"),
                1_700_000_000.0,
            ),
            sample_row(
                "0000000000000000000000000000000000000000000000000000000000000002",
                None,
                None,
                1_700_000_001.0,
            ),
        ];
        let text = format_rows_text(&rows);
        let lines: Vec<&str> = text.lines().collect();

        // Header + two data rows.
        assert_eq!(lines.len(), 3);
        assert!(lines[0].contains("ITEM_HASH"));
        assert!(lines[0].contains("NAME"));
        assert!(lines[0].contains("OWNER"));
        assert!(lines[0].contains("STATUS"));
        assert!(lines[0].contains("ALLOCATED"));

        // Populated row renders the 12-char hash prefix (not full 64-char hash).
        assert!(lines[1].contains("000000000000"));
        assert!(
            !lines[1].contains("0000000000000000000000000000000000000000000000000000000000000001")
        );
        assert!(lines[1].contains("vm-a"));

        // Missing fields use the ASCII `-` placeholder (not `—`).
        assert!(!lines[2].contains('—'));
        // Exactly three `-` placeholders on the missing-fields row: NAME, STATUS,
        // and ALLOCATED. Check with word boundaries (space on each side).
        assert_eq!(
            lines[2].matches(" - ").count() + lines[2].ends_with(" -") as usize,
            3
        );
    }

    #[test]
    fn format_rows_text_empty_has_header_only() {
        let text = format_rows_text(&[]);
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines.len(), 1);
        assert!(lines[0].contains("ITEM_HASH"));
    }

    #[test]
    fn resolve_instance_specs_without_size_uses_defaults() {
        let specs = resolve_instance_specs_from_flags(None, None, Some(20 * 1024));
        assert_eq!(specs.unwrap(), (1, 2048, 20 * 1024));
    }

    #[test]
    fn resolve_instance_specs_without_size_requires_disk() {
        assert!(resolve_instance_specs_from_flags(None, None, None).is_err());
    }

    #[test]
    fn resolve_instance_specs_applies_overrides() {
        let specs = resolve_instance_specs_from_flags(Some(4), Some(8192), Some(40 * 1024));
        assert_eq!(specs.unwrap(), (4, 8192, 40 * 1024));
    }

    use aleph_sdk::scheduler::VmEntry;

    fn make_vm_entry(hash: &str, status: &str, node: Option<&str>) -> VmEntry {
        let json = serde_json::json!({
            "vm_hash": hash,
            "vm_type": "instance",
            "allocated_node": node,
            "status": status,
            "scheduling_status": "scheduled",
            "migration_target": null,
            "owner": "0xaAf798d5F80dAEE72AEe8557B890809E9f5B6072"
        });
        serde_json::from_value(json).expect("valid VmEntry json")
    }

    #[test]
    fn merge_populates_status_and_allocated_when_scheduler_has_entry() {
        const MERGE_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000042";
        let mut rows = vec![sample_row(MERGE_HASH, None, None, 0.0)];
        let hash: ItemHash = rows[0].item_hash.clone();
        let entry = make_vm_entry(
            &hash.to_string(),
            "dispatched",
            Some("d704be0b15e2fb600c5998581cb9af01bd74a9cf61b586ccc849ad78e0709d77"),
        );
        let mut map = std::collections::HashMap::new();
        map.insert(hash, entry);

        merge_scheduler_into_rows(&mut rows, &map);

        assert_eq!(rows[0].status.as_deref(), Some("dispatched"));
        assert_eq!(
            rows[0].allocated_node.as_deref(),
            Some("d704be0b15e2fb600c5998581cb9af01bd74a9cf61b586ccc849ad78e0709d77")
        );
        assert!(rows[0].scheduler_raw.is_some());
    }

    #[test]
    fn merge_leaves_row_blank_when_hash_not_in_map() {
        const MERGE_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000042";
        let mut rows = vec![sample_row(MERGE_HASH, None, None, 0.0)];
        let map = std::collections::HashMap::<ItemHash, VmEntry>::new();
        merge_scheduler_into_rows(&mut rows, &map);
        assert!(rows[0].status.is_none());
        assert!(rows[0].allocated_node.is_none());
        assert!(rows[0].scheduler_raw.is_none());
    }

    #[test]
    fn merge_does_not_add_scheduler_only_rows() {
        let mut rows: Vec<InstanceRow> = vec![];
        let mut map = std::collections::HashMap::new();
        let scheduler_only_hash: ItemHash =
            "5a586d6f59f6c2e6862f155204626dcf01a6ec1107e7aba67063cd48ffe41d99"
                .parse()
                .expect("valid item hash");
        map.insert(
            scheduler_only_hash.clone(),
            make_vm_entry(
                &scheduler_only_hash.to_string(),
                "dispatched",
                Some("anything"),
            ),
        );
        merge_scheduler_into_rows(&mut rows, &map);
        assert!(rows.is_empty());
    }

    #[test]
    fn format_item_hash_short_takes_first_12() {
        let hash: ItemHash = "5a586d6f59f6c2e6862f155204626dcf01a6ec1107e7aba67063cd48ffe41d99"
            .parse()
            .expect("valid item hash");
        assert_eq!(format_item_hash_short(&hash), "5a586d6f59f6");
    }

    #[test]
    fn format_node_short_takes_last_10() {
        let s = "d704be0b15e2fb600c5998581cb9af01bd74a9cf61b586ccc849ad78e0709d77";
        assert_eq!(format_node_short(s), "78e0709d77");
    }

    #[test]
    fn format_node_short_passthrough_when_short() {
        assert_eq!(format_node_short("abc"), "abc");
        assert_eq!(format_node_short("0123456789"), "0123456789");
    }
}