rusty-fez 0.4.0

Agent-native management CLI for Fedora/RHEL (drives cockpit-bridge)
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
//! RPM package management over dnf5daemon (`org.rpm.dnf.v0`).
//!
//! Mirrors the structure of [`crate::capabilities::services`]: a single
//! [`classify`] splits the flat clap enum into reads and mutations, reads run
//! unprivileged and render a [`View`], mutations resolve the transaction first,
//! apply removal guardrails, audit, then execute. Every dnf5daemon session is
//! closed best-effort on every return path so the daemon never leaks sessions.
use crate::capabilities::{render, View};
use crate::cli::{Cli, PackagesAction};
use crate::error::{is_service_unknown, FezError, Result};
use crate::protocol::client::BridgeClient;
use serde_json::{json, Value};

const DNF_NAME: &str = "org.rpm.dnf.v0";
const SM_PATH: &str = "/org/rpm/dnf/v0";
const SM_IFACE: &str = "org.rpm.dnf.v0.SessionManager";
const RPM_IFACE: &str = "org.rpm.dnf.v0.rpm.Rpm";
const REPO_IFACE: &str = "org.rpm.dnf.v0.rpm.Repo";
const GOAL_IFACE: &str = "org.rpm.dnf.v0.Goal";

/// Package attributes requested from dnf5daemon's `Rpm.list`.
const PKG_ATTRS: &[&str] = &["name", "evr", "arch", "repo_id", "install_size", "summary"];

/// A staging mutation that goes through resolve-first/guardrail/execute.
#[derive(Clone, Copy)]
enum Mutation {
    Install,
    Remove,
    Upgrade,
}

impl Mutation {
    fn verb(self) -> &'static str {
        match self {
            Mutation::Install => "install",
            Mutation::Remove => "remove",
            Mutation::Upgrade => "upgrade",
        }
    }
    /// The dnf5daemon `Rpm` D-Bus method name to stage this mutation.
    ///
    /// Intentionally distinct from [`Mutation::verb`] (the user-facing display
    /// verb); the two happen to coincide today but answer different questions.
    fn method(self) -> &'static str {
        match self {
            Mutation::Install => "install",
            Mutation::Remove => "remove",
            Mutation::Upgrade => "upgrade",
        }
    }
}

/// A read subcommand and its arguments, borrowed from the parsed action.
///
/// Splitting reads out of [`PackagesAction`] keeps [`run_read`] total: every
/// variant here maps to a handler, so adding one is a compile error rather than
/// a runtime panic.
enum ReadAction<'a> {
    List(ListFilters<'a>),
    Info { spec: &'a str },
    Search { pattern: &'a str },
    CheckUpdate,
    Repolist { filter: RepoFilter },
}

/// Client-side filters and pagination for `packages list`.
#[derive(Clone, Copy)]
struct ListFilters<'a> {
    available: bool,
    repos: &'a [String],
    name: Option<&'a str>,
    limit: Option<usize>,
    offset: usize,
}

/// Which repositories `repolist` should report.
#[derive(Clone, Copy)]
enum RepoFilter {
    Enabled,
    Disabled,
    All,
}

impl RepoFilter {
    /// The dnf5daemon `enable_disable` option value.
    fn enable_disable(self) -> &'static str {
        match self {
            RepoFilter::Enabled => "enabled",
            RepoFilter::Disabled => "disabled",
            RepoFilter::All => "all",
        }
    }
    /// Whether a repo with `enabled` state should appear under this filter.
    fn accepts(self, enabled: bool) -> bool {
        match self {
            RepoFilter::Enabled => enabled,
            RepoFilter::Disabled => !enabled,
            RepoFilter::All => true,
        }
    }
}

/// The read/mutate split of a parsed [`PackagesAction`].
enum Plan<'a> {
    Read(ReadAction<'a>),
    Mutate {
        mutation: Mutation,
        specs: Vec<String>,
    },
}

/// Map the flat clap enum onto the read/mutate [`Plan`] split.
///
/// This is the only exhaustive match over [`PackagesAction`]; everything
/// downstream consumes one arm of this and is therefore total, so a new variant
/// breaks the build here instead of hitting an `unreachable!` at runtime.
fn classify(action: &PackagesAction) -> Plan<'_> {
    match action {
        PackagesAction::List {
            installed: _installed,
            available,
            repo,
            name,
            limit,
            offset,
        } => Plan::Read(ReadAction::List(ListFilters {
            available: *available,
            repos: repo,
            name: name.as_deref(),
            limit: *limit,
            offset: *offset,
        })),
        PackagesAction::Info { spec } => Plan::Read(ReadAction::Info { spec }),
        PackagesAction::Search { pattern } => Plan::Read(ReadAction::Search { pattern }),
        PackagesAction::CheckUpdate => Plan::Read(ReadAction::CheckUpdate),
        PackagesAction::Repolist {
            enabled: _enabled,
            disabled,
            all,
        } => {
            let filter = if *all {
                RepoFilter::All
            } else if *disabled {
                RepoFilter::Disabled
            } else {
                RepoFilter::Enabled
            };
            Plan::Read(ReadAction::Repolist { filter })
        }
        PackagesAction::Install { specs } => Plan::Mutate {
            mutation: Mutation::Install,
            specs: specs.clone(),
        },
        PackagesAction::Remove { specs } => Plan::Mutate {
            mutation: Mutation::Remove,
            specs: specs.clone(),
        },
        PackagesAction::Upgrade { specs } => Plan::Mutate {
            mutation: Mutation::Upgrade,
            specs: specs.clone(),
        },
    }
}

/// Run the requested `packages` subcommand and return the process exit code.
pub fn dispatch(cli: &Cli, action: &PackagesAction) -> i32 {
    let view = match classify(action) {
        Plan::Read(read) => run_read(cli, read),
        Plan::Mutate { mutation, specs } => run_mutation(cli, mutation, &specs),
    };
    render(cli, view)
}

/// The [`FezError::DependencyMissing`] returned when dnf5daemon is absent.
fn dependency_missing() -> FezError {
    FezError::DependencyMissing {
        component: "dnf5daemon".into(),
        dbus_name: DNF_NAME.into(),
        remediation: "Install the dnf5daemon server on the target (dnf install dnf5daemon-server) and ensure its D-Bus service org.rpm.dnf.v0 is activatable, then retry.".into(),
    }
}

/// Wrap a value as a cockpit D-Bus variant (`{"t": signature, "v": value}`).
///
/// dnf5daemon's option arguments are typed `a{sv}` (a string-keyed dict of
/// variants). cockpit-bridge marshals each dict value as a variant, which on
/// the wire is an explicit `{"t","v"}` object: a bare JSON scalar makes the
/// bridge's marshaller raise `'bool' object is not subscriptable` (or the
/// equivalent for other types) when it tries to read `value["t"]`.
fn variant(signature: &str, value: Value) -> Value {
    json!({ "t": signature, "v": value })
}

/// Build an `a{sv}` options dict, variant-wrapping every value.
///
/// Each entry is `(key, dbus_signature, value)`; the value is wrapped via
/// [`variant`] so the bridge can marshal the dict without introspection.
fn options(entries: &[(&str, &str, Value)]) -> Value {
    let map: serde_json::Map<String, Value> = entries
        .iter()
        .map(|(k, sig, v)| ((*k).to_string(), variant(sig, v.clone())))
        .collect();
    Value::Object(map)
}

/// Open the dnf channel (privileged for mutations) and start a daemon session.
///
/// Returns `(channel, session_path)`; a ServiceUnknown D-Bus error (the daemon
/// is not installed/activatable) is mapped to [`dependency_missing`].
fn open_session(client: &mut BridgeClient, privileged: bool) -> Result<(String, String)> {
    let channel = if privileged {
        client.dbus_open_privileged(DNF_NAME)?
    } else {
        client.dbus_open(DNF_NAME)?
    };
    let out = client.dbus_call(
        &channel,
        SM_PATH,
        SM_IFACE,
        "open_session",
        json!([options(&[
            ("load_system_repo", "b", json!(true)),
            ("load_available_repos", "b", json!(true)),
        ])]),
    );
    let out = match out {
        Ok(v) => v,
        Err(FezError::Dbus { name, .. }) if is_service_unknown(&name) => {
            return Err(dependency_missing())
        }
        Err(e) => return Err(e),
    };
    let session = out.get(0).and_then(Value::as_str).unwrap_or("").to_string();
    Ok((channel, session))
}

/// Close a dnf5daemon session, ignoring any error (best-effort cleanup).
fn close_session(client: &mut BridgeClient, channel: &str, session: &str) {
    let _ = client.dbus_call(
        channel,
        SM_PATH,
        SM_IFACE,
        "close_session",
        json!([session]),
    );
}

/// Pull a variant-wrapped (`{"t":..,"v":..}`) or flat string field as a `String`.
fn sv(v: &Value, key: &str) -> String {
    v.get(key)
        .and_then(|f| f.get("v").unwrap_or(f).as_str())
        .unwrap_or("")
        .to_string()
}

/// Pull a variant-wrapped (`{"t":"t","v":..}`) numeric field as a `u64`,
/// tolerating either a JSON number or a numeric string payload.
fn sv_u64(v: &Value, key: &str) -> u64 {
    let field = v.get(key).map(|f| f.get("v").unwrap_or(f));
    match field {
        Some(f) if f.is_u64() => f.as_u64().unwrap_or(0),
        Some(f) if f.is_i64() => u64::try_from(f.as_i64().unwrap_or(0)).unwrap_or(0),
        Some(f) => f.as_str().and_then(|s| s.parse().ok()).unwrap_or(0),
        None => 0,
    }
}

/// Pull a variant-wrapped (`{"t":"b","v":..}`) or flat boolean field.
fn sv_bool(v: &Value, key: &str) -> bool {
    v.get(key)
        .and_then(|f| f.get("v").unwrap_or(f).as_bool())
        .unwrap_or(false)
}

/// A single package row in list/info/search/check-update output.
fn package_json(p: &Value) -> Value {
    json!({
        "name": sv(p, "name"),
        "evr": sv(p, "evr"),
        "arch": sv(p, "arch"),
        "repo_id": sv(p, "repo_id"),
        "install_size": sv_u64(p, "install_size"),
        "summary": sv(p, "summary"),
    })
}

/// Column order for the columnar `PackageList`/`PackageSearch` payloads.
///
/// Stated once here so the header and each [`package_row`] stay aligned; the
/// record-shaped [`package_json`] (used by single-package `PackageInfo`) keeps
/// the same field names.
const PKG_COLUMNS: &[&str] = &["name", "evr", "arch", "repo_id", "install_size", "summary"];

/// Project one raw package into a positional row aligned to [`PKG_COLUMNS`].
///
/// `install_size` stays an integer; every other cell is a string.
fn package_row(p: &Value) -> Value {
    json!([
        sv(p, "name"),
        sv(p, "evr"),
        sv(p, "arch"),
        sv(p, "repo_id"),
        sv_u64(p, "install_size"),
        sv(p, "summary"),
    ])
}

/// Connect, open an unprivileged session, dispatch the read, and always close.
///
/// When dnf5daemon is absent (the `open_session` ServiceUnknown path, surfaced
/// as [`FezError::DependencyMissing`]), the read transparently falls back to the
/// PackageKit backend (RHEL 10). Only when PackageKit is *also* absent does the
/// call return a dependency-missing error naming both daemons.
fn run_read(cli: &Cli, action: ReadAction<'_>) -> Result<View> {
    let transport = crate::transport::from_host(cli.host.as_deref());
    let mut client = BridgeClient::connect(transport.as_ref())?;
    let host = client.host().to_string();
    let (channel, session) = match open_session(&mut client, false) {
        Ok(pair) => pair,
        Err(FezError::DependencyMissing { .. }) => {
            return read_via_packagekit(&mut client, host, action);
        }
        Err(e) => return Err(e),
    };
    let result = match action {
        ReadAction::List(filters) => list(&mut client, &channel, &session, host, filters),
        ReadAction::Info { spec } => info(&mut client, &channel, &session, host, spec),
        ReadAction::Search { pattern } => search(&mut client, &channel, &session, host, pattern),
        ReadAction::CheckUpdate => check_update(&mut client, &channel, &session, host),
        ReadAction::Repolist { filter } => repolist(&mut client, &channel, &session, host, filter),
    };
    close_session(&mut client, &channel, &session);
    result
}

/// Convert a PackageKit backend result into a dnf-backend [`View`].
fn from_pk(pk: crate::capabilities::packages_pk::PkView, host: String) -> View {
    View::new(pk.kind, host, pk.data, pk.human).with_hints_opt(pk.hints)
}

/// Dependency-missing error when BOTH dnf5daemon and PackageKit are absent.
fn both_missing() -> FezError {
    FezError::DependencyMissing {
        component: "dnf5daemon or PackageKit".into(),
        dbus_name: "org.rpm.dnf.v0 / org.freedesktop.PackageKit".into(),
        remediation: "Install a package backend: dnf5daemon-server (Fedora) providing org.rpm.dnf.v0, or PackageKit providing org.freedesktop.PackageKit, then retry.".into(),
    }
}

/// Run a read over the PackageKit backend, mapping PackageKit's own absence to a
/// dependency-missing error naming both daemons.
fn read_via_packagekit(
    client: &mut BridgeClient,
    host: String,
    action: ReadAction<'_>,
) -> Result<View> {
    use crate::capabilities::packages_pk as pk;
    let result = match action {
        ReadAction::List(filters) => pk::list(
            client,
            filters.available,
            filters.repos,
            filters.name,
            filters.limit,
            filters.offset,
        ),
        ReadAction::Info { spec } => pk::info(client, spec),
        ReadAction::Search { pattern } => pk::search(client, pattern),
        ReadAction::CheckUpdate => pk::check_update(client),
        ReadAction::Repolist { filter } => {
            pk::repolist(client, move |enabled| filter.accepts(enabled))
        }
    };
    match result {
        Ok(view) => Ok(from_pk(view, host)),
        Err(FezError::Dbus { name, .. }) if is_service_unknown(&name) => Err(both_missing()),
        Err(e) => Err(e),
    }
}

/// Call `Rpm.list` on the session with the given scope/patterns and return the
/// raw package array.
fn rpm_list(
    client: &mut BridgeClient,
    channel: &str,
    session: &str,
    scope: &str,
    patterns: &[String],
) -> Result<Vec<Value>> {
    let out = client.dbus_call(
        channel,
        session,
        RPM_IFACE,
        "list",
        json!([options(&[
            ("scope", "s", json!(scope)),
            ("patterns", "as", json!(patterns)),
            ("package_attrs", "as", json!(PKG_ATTRS)),
        ])]),
    )?;
    Ok(out
        .get(0)
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default())
}

fn list(
    client: &mut BridgeClient,
    channel: &str,
    session: &str,
    host: String,
    filters: ListFilters<'_>,
) -> Result<View> {
    let scope = if filters.available {
        "available"
    } else {
        "installed"
    };
    let raw = rpm_list(client, channel, session, scope, &[])?;
    // dnf5daemon's Rpm.list has no server-side repo filter (only install/upgrade
    // accept `repo_ids`, for resolution), so we filter client-side on the exact
    // `repo_id`. Multiple --repo flags union: a row is kept if its repo id is in
    // the requested set. An empty set means no filter (issue #59).
    let filtered: Vec<&Value> = raw
        .iter()
        .filter(|p| {
            filters.repos.is_empty() || filters.repos.iter().any(|r| r == &sv(p, "repo_id"))
        })
        .filter(|p| {
            filters
                .name
                .is_none_or(|pattern| sv(p, "name").contains(pattern))
        })
        .collect();
    let total = filtered.len();
    let start = filters.offset.min(total);
    let end = match filters.limit {
        Some(limit) => (start + limit).min(total),
        None => total,
    };
    let page = &filtered[start..end];
    let mut human = format!(
        "{:<24} {:<20} {:<10} {}\n",
        "NAME", "VERSION", "ARCH", "REPO"
    );
    for p in page {
        human.push_str(&format!(
            "{:<24} {:<20} {:<10} {}\n",
            sv(p, "name"),
            sv(p, "evr"),
            sv(p, "arch"),
            sv(p, "repo_id"),
        ));
    }
    let rows: Vec<Value> = page.iter().map(|p| package_row(p)).collect();
    let mut data = crate::envelope::table_data(PKG_COLUMNS, rows);
    data["scope"] = json!(scope);
    // Echo the requested repo filter so callers can confirm what was applied.
    data["repos"] = json!(filters.repos);
    data["name"] = json!(filters.name);
    data["total"] = json!(total);
    data["returned"] = json!(end - start);
    data["limit"] = json!(filters.limit);
    data["offset"] = json!(filters.offset);
    data["next_offset"] = json!((end < total).then_some(end));
    data["backend"] = json!("dnf5daemon");
    let hints = if filters.limit.is_none() && total > 1000 {
        Some(json!([format!(
            "This response has {total} rows. Prefer packages search <pattern>, use --name, or use --limit."
        )]))
    } else {
        None
    };
    Ok(View::new("PackageList", host, data, human).with_hints_opt(hints))
}

fn info(
    client: &mut BridgeClient,
    channel: &str,
    session: &str,
    host: String,
    spec: &str,
) -> Result<View> {
    let raw = rpm_list(client, channel, session, "all", &[spec.to_string()])?;
    let first = raw
        .first()
        .ok_or_else(|| FezError::NotFound(spec.to_string()))?;
    let mut pkg = package_json(first);
    pkg["backend"] = json!("dnf5daemon");
    let human = format!(
        "Name        : {}\nVersion     : {}\nArch        : {}\nRepo        : {}\nInstall size: {}\nSummary     : {}\n",
        sv(first, "name"),
        sv(first, "evr"),
        sv(first, "arch"),
        sv(first, "repo_id"),
        sv_u64(first, "install_size"),
        sv(first, "summary"),
    );
    Ok(View::new("PackageInfo", host, pkg, human))
}

fn search(
    client: &mut BridgeClient,
    channel: &str,
    session: &str,
    host: String,
    pattern: &str,
) -> Result<View> {
    let glob = format!("*{pattern}*");
    let raw = rpm_list(client, channel, session, "available", &[glob])?;
    let mut human = String::new();
    for p in &raw {
        human.push_str(&format!("{} - {}\n", sv(p, "name"), sv(p, "summary")));
    }
    let rows: Vec<Value> = raw.iter().map(package_row).collect();
    let mut data = crate::envelope::table_data(PKG_COLUMNS, rows);
    data["pattern"] = json!(pattern);
    data["backend"] = json!("dnf5daemon");
    Ok(View::new("PackageSearch", host, data, human))
}

fn check_update(
    client: &mut BridgeClient,
    channel: &str,
    session: &str,
    host: String,
) -> Result<View> {
    let raw = rpm_list(client, channel, session, "upgrades", &[])?;
    let mut human = format!("{:<24} {:<20} {}\n", "NAME", "VERSION", "REPO");
    for p in &raw {
        human.push_str(&format!(
            "{:<24} {:<20} {}\n",
            sv(p, "name"),
            sv(p, "evr"),
            sv(p, "repo_id"),
        ));
    }
    let rows: Vec<Value> = raw.iter().map(package_row).collect();
    let mut data = crate::envelope::table_data(PKG_COLUMNS, rows);
    data["backend"] = json!("dnf5daemon");
    Ok(View::new("PackageUpdates", host, data, human))
}

/// Column order for the columnar `RepoList` payload (`enabled` stays a bool).
const REPO_COLUMNS: &[&str] = &["id", "name", "enabled"];

fn repolist(
    client: &mut BridgeClient,
    channel: &str,
    session: &str,
    host: String,
    filter: RepoFilter,
) -> Result<View> {
    let out = client.dbus_call(
        channel,
        session,
        REPO_IFACE,
        "list",
        json!([options(&[
            ("enable_disable", "s", json!(filter.enable_disable())),
            ("repo_attrs", "as", json!(["id", "name", "enabled"])),
        ])]),
    )?;
    let raw = out
        .get(0)
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    let mut rows = Vec::new();
    let mut human = format!("{:<24} {:<10} {}\n", "REPO ID", "ENABLED", "NAME");
    for r in &raw {
        let enabled = sv_bool(r, "enabled");
        if !filter.accepts(enabled) {
            continue;
        }
        let id = sv(r, "id");
        let name = sv(r, "name");
        human.push_str(&format!("{id:<24} {enabled:<10} {name}\n"));
        rows.push(json!([id, name, enabled]));
    }
    let mut data = crate::envelope::table_data(REPO_COLUMNS, rows);
    data["backend"] = json!("dnf5daemon");
    Ok(View::new("RepoList", host, data, human))
}

/// A resolved dnf5daemon transaction, bucketed by action for rendering and
/// guardrails.
struct ResolvedPlan {
    install: Vec<String>,
    remove: Vec<String>,
    upgrade: Vec<String>,
    downgrade: Vec<String>,
    install_size_total: u64,
    remove_names: Vec<String>,
}

impl ResolvedPlan {
    /// The plan rendered as the `fez/v1` data payload.
    fn data(&self) -> Value {
        json!({
            "install": self.install,
            "remove": self.remove,
            "upgrade": self.upgrade,
            "downgrade": self.downgrade,
            "install_size_total": self.install_size_total,
            "counts": {
                "install": self.install.len(),
                "remove": self.remove.len(),
                "upgrade": self.upgrade.len(),
                "downgrade": self.downgrade.len(),
            },
        })
    }
}

/// Format a package object's NEVRA label (`name-evr.arch`).
fn nevra(object: &Value) -> String {
    format!(
        "{}-{}.{}",
        sv(object, "name"),
        sv(object, "evr"),
        sv(object, "arch")
    )
}

/// Parse a `Goal.resolve` `transaction_items` array into a [`ResolvedPlan`].
///
/// Each item is a 5-element array `[object_type, action, reason, attrs, object]`;
/// `action` is at index 1, `object` at index 4. Removal-class actions push the
/// bare name into `remove_names` (guardrail input) and the label into `remove`.
fn parse_plan(items: &Value) -> ResolvedPlan {
    let mut plan = ResolvedPlan {
        install: Vec::new(),
        remove: Vec::new(),
        upgrade: Vec::new(),
        downgrade: Vec::new(),
        install_size_total: 0,
        remove_names: Vec::new(),
    };
    let Some(arr) = items.as_array() else {
        return plan;
    };
    for item in arr {
        let action = item.get(1).and_then(Value::as_str).unwrap_or("");
        let object = item.get(4).cloned().unwrap_or(Value::Null);
        let label = nevra(&object);
        match action {
            "Install" => {
                plan.install_size_total += sv_u64(&object, "install_size");
                plan.install.push(label);
            }
            "Upgrade" => plan.upgrade.push(label),
            "Downgrade" => plan.downgrade.push(label),
            "Remove" | "Replaced" | "Obsoleted" | "Erase" => {
                plan.remove_names.push(sv(&object, "name"));
                plan.remove.push(label);
            }
            _ => {}
        }
    }
    plan
}

/// Resolve-first mutation: stage, resolve, optionally short-circuit on dry-run,
/// apply removal guardrails, audit, execute, and always close the session.
fn run_mutation(cli: &Cli, m: Mutation, specs: &[String]) -> Result<View> {
    let host = cli.resolved_host();
    let transport = crate::transport::from_host(cli.host.as_deref());
    let mut client = BridgeClient::connect(transport.as_ref())?;
    let (channel, session) = match open_session(&mut client, true) {
        Ok(pair) => pair,
        Err(FezError::DependencyMissing { .. }) => {
            return mutate_via_packagekit(&mut client, m, specs, &host, cli.dry_run, cli.force);
        }
        Err(e) => return Err(e),
    };
    // Do the work in an inner closure so the session is closed on every path,
    // success or failure, before the result propagates.
    let result = mutation_inner(cli, &mut client, &channel, &session, m, specs, &host);
    close_session(&mut client, &channel, &session);
    result
}

/// Run a mutation over the PackageKit backend, mapping PackageKit's own absence
/// to a dependency-missing error naming both daemons.
fn mutate_via_packagekit(
    client: &mut BridgeClient,
    m: Mutation,
    specs: &[String],
    host: &str,
    dry_run: bool,
    force: bool,
) -> Result<View> {
    match crate::capabilities::packages_pk::mutate(client, m.verb(), specs, host, dry_run, force) {
        Ok(view) => Ok(from_pk(view, host.to_string())),
        Err(FezError::Dbus { name, .. }) if is_service_unknown(&name) => Err(both_missing()),
        Err(e) => Err(e),
    }
}

#[allow(clippy::too_many_arguments)]
fn mutation_inner(
    cli: &Cli,
    client: &mut BridgeClient,
    channel: &str,
    session: &str,
    m: Mutation,
    specs: &[String],
    host: &str,
) -> Result<View> {
    // 1. Stage the goal.
    client.dbus_call(channel, session, RPM_IFACE, m.method(), json!([specs, {}]))?;
    // 2. Resolve into a concrete plan.
    let out = client.dbus_call(channel, session, GOAL_IFACE, "resolve", json!([{}]))?;
    let items = out.get(0).cloned().unwrap_or(Value::Null);
    let plan = parse_plan(&items);

    // 3. Dry-run: report the plan without executing.
    if cli.dry_run {
        return Ok(plan_view(m, host, specs, &plan, true));
    }

    // 4. Removal guardrails (protected package / cascade) before any execution.
    crate::safety::check_removal_plan(&plan.remove_names, cli.force)?;

    // 5. Audit attempt, execute, audit result.
    crate::audit::run_audited(host, m.verb(), &specs.join(","), || {
        client.dbus_call(channel, session, GOAL_IFACE, "do_transaction", json!([{}]))?;
        Ok(plan_view(m, host, specs, &plan, false))
    })
}

/// Build the [`View`] for a resolved plan (dry-run preview or executed mutation).
fn plan_view(
    m: Mutation,
    host: &str,
    specs: &[String],
    plan: &ResolvedPlan,
    dry_run: bool,
) -> View {
    let kind = if dry_run {
        "PackagePlan"
    } else {
        "PackageMutation"
    };
    let mut data = plan.data();
    if let Value::Object(map) = &mut data {
        map.insert("operation".into(), json!(m.verb()));
        map.insert("specs".into(), json!(specs));
        map.insert("dry_run".into(), json!(dry_run));
        map.insert("backend".into(), json!("dnf5daemon"));
    }
    let human = if dry_run {
        format!(
            "DRY-RUN: {} {} on {} would install {}, remove {}, upgrade {}, downgrade {} package(s)\n",
            m.verb(),
            specs.join(" "),
            host,
            plan.install.len(),
            plan.remove.len(),
            plan.upgrade.len(),
            plan.downgrade.len(),
        )
    } else {
        format!(
            "{} {} on {}: installed {}, removed {}, upgraded {}, downgraded {} package(s)\n",
            m.verb(),
            specs.join(" "),
            host,
            plan.install.len(),
            plan.remove.len(),
            plan.upgrade.len(),
            plan.downgrade.len(),
        )
    };
    View::new(kind, host.to_string(), data, human)
}

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

    fn item(action: &str, name: &str, size: u64) -> Value {
        json!([ "Package", action, "User", {}, {
            "name": {"t":"s","v": name},
            "evr": {"t":"s","v":"1-1"},
            "arch": {"t":"s","v":"x86_64"},
            "repo_id": {"t":"s","v":"fedora"},
            "install_size": {"t":"t","v": size.to_string()}
        }])
    }

    #[test]
    fn variant_wraps_value_with_signature() {
        assert_eq!(variant("b", json!(true)), json!({"t": "b", "v": true}));
        assert_eq!(variant("s", json!("x")), json!({"t": "s", "v": "x"}));
    }

    #[test]
    fn options_wraps_every_value_as_a_variant() {
        let opts = options(&[
            ("load_system_repo", "b", json!(true)),
            ("scope", "s", json!("installed")),
            ("patterns", "as", json!(["htop"])),
        ]);
        // Every value must be the explicit {"t","v"} variant form, never a bare
        // scalar, or cockpit's a{sv} marshaller raises a TypeError.
        assert_eq!(
            opts,
            json!({
                "load_system_repo": {"t": "b", "v": true},
                "scope": {"t": "s", "v": "installed"},
                "patterns": {"t": "as", "v": ["htop"]},
            })
        );
    }

    #[test]
    fn parse_plan_buckets_by_action() {
        let items = json!([
            item("Install", "htop", 100),
            item("Remove", "oldpkg", 50),
            item("Upgrade", "nginx", 200),
            item("Downgrade", "foo", 10)
        ]);
        let plan = parse_plan(&items);
        assert_eq!(plan.install, vec!["htop-1-1.x86_64"]);
        assert_eq!(plan.remove, vec!["oldpkg-1-1.x86_64"]);
        assert_eq!(plan.upgrade, vec!["nginx-1-1.x86_64"]);
        assert_eq!(plan.downgrade, vec!["foo-1-1.x86_64"]);
        assert_eq!(plan.remove_names, vec!["oldpkg".to_string()]);
    }

    #[test]
    fn parse_plan_counts_replaced_as_removed() {
        let items = json!([
            item("Install", "newpkg", 100),
            item("Replaced", "oldpkg", 50)
        ]);
        assert_eq!(parse_plan(&items).remove_names, vec!["oldpkg".to_string()]);
    }

    #[test]
    fn parse_plan_totals_install_size() {
        let items = json!([item("Install", "a", 100), item("Install", "b", 200)]);
        assert_eq!(parse_plan(&items).install_size_total, 300);
    }
}