pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
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
//! Preflight summary computation helpers.
//!
//! The routines in this module gather package metadata, estimate download and
//! install deltas, and derive risk heuristics used to populate the preflight
//! modal. All command execution is abstracted behind [`CommandRunner`] so the
//! logic can be exercised in isolation.

mod batch;
mod command;
mod metadata;
mod version;

use crate::state::modal::{
    PreflightAction, PreflightHeaderChips, PreflightPackageSummary, PreflightSummaryData, RiskLevel,
};
use crate::state::types::{PackageItem, Source};
use std::cmp::Ordering;

pub use command::{CommandError, CommandRunner, SystemCommandRunner};

use batch::{batch_fetch_installed_sizes, batch_fetch_installed_versions};
use version::{compare_versions, is_major_version_bump};

/// Packages that contribute additional risk when present in a transaction.
const CORE_CRITICAL_PACKAGES: &[&str] = &[
    "linux",
    "linux-lts",
    "linux-zen",
    "systemd",
    "glibc",
    "openssl",
    "pacman",
    "bash",
    "util-linux",
    "filesystem",
];

/// What: Outcome of preflight summary computation.
///
/// Inputs: Produced by the summary computation helpers from package items and dependencies.
///
/// Output:
/// - `summary`: Structured data powering the Summary tab.
/// - `header`: Condensed metrics displayed in the modal header and execution sidebar.
/// - `reverse_deps_report`: Optional reverse dependency report for Remove actions,
///   cached to avoid redundant resolution when switching to the Deps tab.
///
/// Details:
/// - Bundled together so downstream code can reuse the derived chip data without recomputation.
/// - Contains the preflight summary data along with header metrics and optional reverse dependency information.
/// - For Remove actions, the reverse dependency report is computed during summary
///   computation and cached here to avoid recomputation when the user switches tabs.
#[derive(Debug, Clone)]
pub struct PreflightSummaryOutcome {
    /// Preflight summary data.
    pub summary: PreflightSummaryData,
    /// Header chip metrics.
    pub header: PreflightHeaderChips,
    /// Cached reverse dependency report for Remove actions (None for Install actions).
    pub reverse_deps_report: Option<crate::logic::deps::ReverseDependencyReport>,
}

/// What: Compute preflight summary data using the system command runner.
///
/// Inputs:
/// - `items`: Packages scheduled for install/update/remove.
/// - `action`: Active operation (install vs. remove) shaping the analysis.
///
/// Output:
/// - [`PreflightSummaryOutcome`] combining Summary tab data and header chips.
///
/// Details:
/// - Delegates to [`compute_preflight_summary_with_runner`] with
///   [`SystemCommandRunner`].
/// - Metadata lookups that fail are logged and treated as best-effort.
#[must_use]
pub fn compute_preflight_summary(
    items: &[PackageItem],
    action: PreflightAction,
) -> PreflightSummaryOutcome {
    let runner = SystemCommandRunner;
    compute_preflight_summary_with_runner(items, action, &runner)
}

/// What: Intermediate state accumulated during package processing.
///
/// Inputs: Built incrementally while iterating packages.
///
/// Output: Used to construct the final summary and risk calculations.
///
/// Details: Groups related mutable state to reduce parameter passing.
struct ProcessingState {
    /// Packages being processed for preflight.
    packages: Vec<PreflightPackageSummary>,
    /// Count of AUR packages.
    aur_count: usize,
    /// Total download size in bytes.
    total_download_bytes: u64,
    /// Total install size delta in bytes (can be negative).
    total_install_delta_bytes: i64,
    /// Packages with major version bumps.
    major_bump_packages: Vec<String>,
    /// Core system packages being updated.
    core_system_updates: Vec<String>,
    /// Whether any package has a major version bump.
    any_major_bump: bool,
    /// Whether any core system package is being updated.
    any_core_update: bool,
    /// Whether any AUR package is included.
    any_aur: bool,
}

impl ProcessingState {
    /// What: Create a new processing state with specified capacity.
    ///
    /// Inputs:
    /// - `capacity`: Initial capacity for the packages vector.
    ///
    /// Output: New `ProcessingState` with empty collections.
    ///
    /// Details: Initializes all fields to default/empty values with the specified capacity.
    fn new(capacity: usize) -> Self {
        Self {
            packages: Vec::with_capacity(capacity),
            aur_count: 0,
            total_download_bytes: 0,
            total_install_delta_bytes: 0,
            major_bump_packages: Vec::new(),
            core_system_updates: Vec::new(),
            any_major_bump: false,
            any_core_update: false,
            any_aur: false,
        }
    }
}

/// What: Process a single package item and update processing state.
///
/// Inputs:
/// - `item`: Package to process.
/// - `action`: Install vs. remove context.
/// - `runner`: Command execution abstraction.
/// - `installed_version`: Previously fetched installed version (if any).
/// - `installed_size`: Previously fetched installed size (if any).
/// - `state`: Mutable state accumulator.
///
/// Output: Updates `state` in place.
///
/// Details:
/// - Fetches metadata for official packages.
/// - Computes version comparisons and notes.
/// - Detects core packages and major version bumps.
fn process_package_item<R: CommandRunner>(
    item: &PackageItem,
    action: PreflightAction,
    runner: &R,
    installed_version: Option<String>,
    installed_size: Option<u64>,
    state: &mut ProcessingState,
) {
    if matches!(item.source, Source::Aur) {
        state.aur_count += 1;
        state.any_aur = true;
    }

    if installed_version.is_none() {
        tracing::debug!(
            "Preflight summary: failed to fetch installed version for {}",
            item.name
        );
    }
    if installed_size.is_none() {
        tracing::debug!(
            "Preflight summary: failed to fetch installed size for {}",
            item.name
        );
    }

    let (download_bytes, install_size_target) = fetch_package_metadata(runner, item);

    let install_delta_bytes = calculate_install_delta(action, install_size_target, installed_size);

    if let Some(bytes) = download_bytes {
        state.total_download_bytes = state.total_download_bytes.saturating_add(bytes);
    }
    if let Some(delta) = install_delta_bytes {
        state.total_install_delta_bytes = state.total_install_delta_bytes.saturating_add(delta);
    }

    let (notes, is_major_bump, is_downgrade) = analyze_version_changes(
        installed_version.as_ref(),
        &item.version,
        action,
        item.name.clone(),
        &mut state.major_bump_packages,
        &mut state.any_major_bump,
    );

    let core_note = check_core_package(
        item,
        action,
        &mut state.core_system_updates,
        &mut state.any_core_update,
    );
    let mut all_notes = notes;
    if let Some(note) = core_note {
        all_notes.push(note);
    }

    // For Install actions, add note about installed packages that depend on this package
    if matches!(action, PreflightAction::Install) && installed_version.is_some() {
        let dependents = crate::logic::deps::get_installed_required_by(&item.name);
        if !dependents.is_empty() {
            let dependents_list = if dependents.len() <= 3 {
                dependents.join(", ")
            } else {
                format!(
                    "{} (and {} more)",
                    dependents[..3].join(", "),
                    dependents.len() - 3
                )
            };
            all_notes.push(format!("Required by installed packages: {dependents_list}"));
        }
    }

    state.packages.push(PreflightPackageSummary {
        name: item.name.clone(),
        source: item.source.clone(),
        installed_version,
        target_version: item.version.clone(),
        is_downgrade,
        is_major_bump,
        download_bytes,
        install_delta_bytes,
        notes: all_notes,
    });
}

/// What: Fetch metadata for official and AUR packages.
///
/// Inputs:
/// - `runner`: Command execution abstraction.
/// - `item`: Package item to fetch metadata for.
///
/// Output: Tuple of (`download_bytes`, `install_size_target`), both `Option`.
///
/// Details:
/// - For official packages: uses `pacman -Si`.
/// - For AUR packages: checks local caches (pacman cache, AUR helper caches) for built package files.
fn fetch_package_metadata<R: CommandRunner>(
    runner: &R,
    item: &PackageItem,
) -> (Option<u64>, Option<u64>) {
    match &item.source {
        Source::Official { repo, .. } => {
            match metadata::fetch_official_metadata(runner, repo, &item.name, item.version.as_str())
            {
                Ok(meta) => (meta.download_size, meta.install_size),
                Err(err) => {
                    tracing::debug!(
                        "Preflight summary: failed to fetch metadata for {repo}/{pkg}: {err}",
                        pkg = item.name
                    );
                    (None, None)
                }
            }
        }
        Source::Aur => {
            let meta =
                metadata::fetch_aur_metadata(runner, &item.name, Some(item.version.as_str()));
            if meta.download_size.is_some() || meta.install_size.is_some() {
                tracing::debug!(
                    "Preflight summary: found AUR package sizes for {}: DL={:?}, Install={:?}",
                    item.name,
                    meta.download_size,
                    meta.install_size
                );
            }
            (meta.download_size, meta.install_size)
        }
    }
}

/// What: Calculate install size delta based on action type.
///
/// Inputs:
/// - `action`: Install vs. remove context.
/// - `install_size_target`: Target install size (for installs).
/// - `installed_size`: Current installed size.
///
/// Output: Delta in bytes (positive for installs, negative for removes).
///
/// Details: Returns None if metadata is unavailable.
fn calculate_install_delta(
    action: PreflightAction,
    install_size_target: Option<u64>,
    installed_size: Option<u64>,
) -> Option<i64> {
    match action {
        PreflightAction::Install => install_size_target.and_then(|target| {
            let current = installed_size.unwrap_or(0);
            let target_i64 = i64::try_from(target).ok()?;
            let current_i64 = i64::try_from(current).ok()?;
            Some(target_i64 - current_i64)
        }),
        PreflightAction::Remove => {
            installed_size.and_then(|size| i64::try_from(size).ok().map(|s| -s))
        }
        PreflightAction::Downgrade => install_size_target.and_then(|target| {
            // For downgrade, calculate delta similar to install (replacing with older version)
            let current = installed_size.unwrap_or(0);
            let target_i64 = i64::try_from(target).ok()?;
            let current_i64 = i64::try_from(current).ok()?;
            Some(target_i64 - current_i64)
        }),
    }
}

/// What: Analyze version changes and generate notes.
///
/// Inputs:
/// - `installed_version`: Current installed version (if any).
/// - `target_version`: Target version.
/// - `action`: Install vs. remove context.
/// - `package_name`: Name of the package.
/// - `major_bump_packages`: Mutable list to append to if major bump detected.
/// - `any_major_bump`: Mutable flag to set if major bump detected.
///
/// Output: Tuple of (`notes`, `is_major_bump`, `is_downgrade`).
///
/// Details: Detects downgrades, major version bumps, and new installations.
fn analyze_version_changes(
    installed_version: Option<&String>,
    target_version: &str,
    action: PreflightAction,
    package_name: String,
    major_bump_packages: &mut Vec<String>,
    any_major_bump: &mut bool,
) -> (Vec<String>, bool, bool) {
    let mut notes = Vec::new();
    let mut is_major_bump = false;
    let mut is_downgrade = false;

    if let Some(current) = installed_version {
        match compare_versions(current, target_version) {
            Ordering::Greater => {
                if matches!(action, PreflightAction::Install) {
                    is_downgrade = true;
                    notes.push(format!("Downgrade detected: {current} → {target_version}"));
                }
            }
            Ordering::Less => {
                if is_major_version_bump(current, target_version) {
                    is_major_bump = true;
                    *any_major_bump = true;
                    major_bump_packages.push(package_name);
                    notes.push(format!("Major version bump: {current} → {target_version}"));
                }
            }
            Ordering::Equal => {}
        }
    } else if matches!(action, PreflightAction::Install) {
        notes.push("New installation".to_string());
    }

    (notes, is_major_bump, is_downgrade)
}

/// What: Check if package is a core/system package and generate note.
///
/// Inputs:
/// - `item`: Package item to check.
/// - `action`: Install vs. remove context.
/// - `core_system_updates`: Mutable list to append to if core package.
/// - `any_core_update`: Mutable flag to set if core package.
///
/// Output: Optional note string if core package detected.
///
/// Details: Normalizes package name for comparison against critical packages list.
fn check_core_package(
    item: &PackageItem,
    action: PreflightAction,
    core_system_updates: &mut Vec<String>,
    any_core_update: &mut bool,
) -> Option<String> {
    let normalized_name = item.name.to_ascii_lowercase();
    if CORE_CRITICAL_PACKAGES
        .iter()
        .any(|candidate| normalized_name == *candidate)
    {
        *any_core_update = true;
        core_system_updates.push(item.name.clone());
        Some(if matches!(action, PreflightAction::Remove) {
            "Removing core/system package".to_string()
        } else {
            "Core/system package update".to_string()
        })
    } else {
        None
    }
}

/// What: Calculate risk reasons and score from processing state.
///
/// Inputs:
/// - `state`: Processing state with accumulated flags.
/// - `pacnew_candidates`: Count of packages that may produce .pacnew files.
/// - `service_restart_units`: List of services that need restart.
/// - `action`: Preflight action (Install vs Remove).
/// - `dependent_count`: Number of packages that depend on packages being removed (for Remove actions).
///
/// Output: Tuple of (`risk_reasons`, `risk_score`, `risk_level`).
///
/// Details: Applies the risk heuristic scoring system.
fn calculate_risk_metrics(
    state: &ProcessingState,
    pacnew_candidates: usize,
    service_restart_units: &[String],
    action: PreflightAction,
    dependent_count: usize,
) -> (Vec<String>, u8, RiskLevel) {
    let mut risk_reasons = Vec::new();
    let mut risk_score: u8 = 0;

    if state.any_core_update {
        risk_reasons.push("Core/system packages involved (+3)".to_string());
        risk_score = risk_score.saturating_add(3);
    }
    if state.any_major_bump {
        risk_reasons.push("Major version bump detected (+2)".to_string());
        risk_score = risk_score.saturating_add(2);
    }
    if state.any_aur {
        risk_reasons.push("AUR packages included (+2)".to_string());
        risk_score = risk_score.saturating_add(2);
    }
    if pacnew_candidates > 0 {
        risk_reasons.push("Configuration files may produce .pacnew (+1)".to_string());
        risk_score = risk_score.saturating_add(1);
    }
    if !service_restart_units.is_empty() {
        risk_reasons.push("Services likely require restart (+1)".to_string());
        risk_score = risk_score.saturating_add(1);
    }
    // For Remove actions, add risk when removing packages with dependencies
    if matches!(action, PreflightAction::Remove) && dependent_count > 0 {
        let risk_points = if dependent_count >= 5 {
            3 // High risk for many dependencies
        } else if dependent_count >= 2 {
            2 // Medium risk for multiple dependencies
        } else {
            1 // Low risk for single dependency
        };
        risk_reasons.push(format!(
            "Removing packages with {dependent_count} dependent package(s) (+{risk_points})"
        ));
        risk_score = risk_score.saturating_add(risk_points);
    }
    // For Install actions, add risk when updating packages with installed dependents
    // Add +2 risk points for each installed package that depends on packages being updated
    if matches!(action, PreflightAction::Install) && dependent_count > 0 {
        let risk_points = dependent_count.saturating_mul(2).min(255); // +2 per dependent package, cap at u8::MAX
        let risk_points_u8 = u8::try_from(risk_points).unwrap_or(255);
        risk_reasons.push(format!(
            "{dependent_count} installed package(s) depend on packages being updated (+{risk_points_u8})"
        ));
        risk_score = risk_score.saturating_add(risk_points_u8);
    }

    let risk_level = match risk_score {
        0 => RiskLevel::Low,
        1..=4 => RiskLevel::Medium,
        _ => RiskLevel::High,
    };

    (risk_reasons, risk_score, risk_level)
}

/// What: Build summary notes from processing state.
///
/// Inputs:
/// - `state`: Processing state with accumulated flags.
///
/// Output: Vector of summary note strings.
///
/// Details: Generates informational notes for the summary tab.
fn build_summary_notes(state: &ProcessingState) -> Vec<String> {
    let mut notes = Vec::new();
    if state.any_core_update {
        notes.push("Core/system packages will be modified.".to_string());
    }
    if state.any_major_bump {
        notes.push("Major version changes detected; review changelogs.".to_string());
    }
    if state.any_aur {
        notes.push("AUR packages present; build steps may vary.".to_string());
    }
    notes
}

/// What: Process all package items and populate processing state.
///
/// Inputs:
/// - `items`: Packages to process.
/// - `action`: Install vs. remove context.
/// - `runner`: Command execution abstraction.
/// - `state`: Mutable state accumulator.
///
/// Output: Updates `state` in place.
///
/// Details: Batch fetches installed versions/sizes and processes each package.
fn process_all_packages<R: CommandRunner>(
    items: &[PackageItem],
    action: PreflightAction,
    runner: &R,
    state: &mut ProcessingState,
) {
    let installed_versions = batch_fetch_installed_versions(runner, items);
    let installed_sizes = batch_fetch_installed_sizes(runner, items);

    for (idx, item) in items.iter().enumerate() {
        let installed_version = installed_versions
            .get(idx)
            .and_then(|v| v.as_ref().ok())
            .cloned();
        let installed_size = installed_sizes
            .get(idx)
            .and_then(|s| s.as_ref().ok())
            .copied();

        process_package_item(
            item,
            action,
            runner,
            installed_version,
            installed_size,
            state,
        );
    }
}

/// What: Resolve reverse dependencies for Remove actions and count installed dependents for Install actions.
///
/// Inputs:
/// - `items`: Packages being removed or installed/updated.
/// - `action`: Preflight action (Install vs Remove).
///
/// Output: Tuple of (`dependent_count`, `reverse_deps_report`).
///
/// Details:
/// - For Remove actions: resolves and counts all dependent packages.
/// - For Install actions: counts the total number of installed packages that depend on packages being updated.
fn resolve_reverse_deps(
    items: &[PackageItem],
    action: PreflightAction,
) -> (usize, Option<crate::logic::deps::ReverseDependencyReport>) {
    if matches!(action, PreflightAction::Remove) {
        let report = crate::logic::deps::resolve_reverse_dependencies(items);
        let count = report.dependencies.len();
        (count, Some(report))
    } else {
        // For Install actions, count the total number of installed dependent packages
        // across all packages being updated
        let mut total_dependents = 0;
        for item in items {
            // Only check installed packages (updates/reinstalls)
            if crate::index::is_installed(&item.name) {
                let dependents = crate::logic::deps::get_installed_required_by(&item.name);
                total_dependents += dependents.len();
            }
        }
        (total_dependents, None)
    }
}

/// What: Build summary data structure from processing state and risk metrics.
///
/// Inputs:
/// - `state`: Processing state with accumulated data.
/// - `items`: Original package items (for count).
/// - `risk_reasons`: Risk reason strings.
/// - `risk_score`: Calculated risk score.
/// - `risk_level`: Calculated risk level.
///
/// Output: [`PreflightSummaryData`] structure.
///
/// Details: Constructs the complete summary data structure.
fn build_summary_data(
    state: ProcessingState,
    items: &[PackageItem],
    risk_reasons: &[String],
    risk_score: u8,
    risk_level: RiskLevel,
) -> PreflightSummaryData {
    let summary_notes = build_summary_notes(&state);
    let mut summary_warnings = Vec::new();
    if summary_warnings.is_empty() {
        summary_warnings.extend(risk_reasons.iter().cloned());
    }

    PreflightSummaryData {
        packages: state.packages,
        package_count: items.len(),
        aur_count: state.aur_count,
        download_bytes: state.total_download_bytes,
        install_delta_bytes: state.total_install_delta_bytes,
        risk_score,
        risk_level,
        risk_reasons: risk_reasons.to_vec(),
        major_bump_packages: state.major_bump_packages,
        core_system_updates: state.core_system_updates,
        pacnew_candidates: 0,
        pacsave_candidates: 0,
        config_warning_packages: Vec::new(),
        service_restart_units: Vec::new(),
        summary_warnings,
        summary_notes,
    }
}

/// What: Build header chips from extracted state values and risk metrics.
///
/// Inputs:
/// - `package_count`: Number of packages.
/// - `download_bytes`: Total download size in bytes.
/// - `install_delta_bytes`: Total install size delta in bytes.
/// - `aur_count`: Number of AUR packages.
/// - `risk_score`: Calculated risk score.
/// - `risk_level`: Calculated risk level.
///
/// Output: [`PreflightHeaderChips`] structure.
///
/// Details: Constructs the header chip metrics.
const fn build_header_chips(
    package_count: usize,
    download_bytes: u64,
    install_delta_bytes: i64,
    aur_count: usize,
    risk_score: u8,
    risk_level: RiskLevel,
) -> PreflightHeaderChips {
    PreflightHeaderChips {
        package_count,
        download_bytes,
        install_delta_bytes,
        aur_count,
        risk_score,
        risk_level,
    }
}

/// What: Compute preflight summary data using a custom command runner.
///
/// Inputs:
/// - `items`: Packages to analyse.
/// - `action`: Install vs. remove context.
/// - `runner`: Command execution abstraction (mockable).
///
/// Output:
/// - [`PreflightSummaryOutcome`] with fully materialised Summary data and
///   header chip metrics.
///
/// Details:
/// - Fetches installed versions/sizes via `pacman` when possible.
/// - Applies the initial risk heuristic outlined in the specification.
/// - Gracefully degrades metrics when metadata is unavailable.
pub fn compute_preflight_summary_with_runner<R: CommandRunner>(
    items: &[PackageItem],
    action: PreflightAction,
    runner: &R,
) -> PreflightSummaryOutcome {
    let _span = tracing::info_span!(
        "compute_preflight_summary",
        stage = "summary",
        item_count = items.len()
    )
    .entered();
    let start_time = std::time::Instant::now();

    let mut state = ProcessingState::new(items.len());
    process_all_packages(items, action, runner, &mut state);

    let (dependent_count, reverse_deps_report) = resolve_reverse_deps(items, action);

    let (risk_reasons, risk_score, risk_level) =
        calculate_risk_metrics(&state, 0, &[], action, dependent_count);

    let header = build_header_chips(
        items.len(),
        state.total_download_bytes,
        state.total_install_delta_bytes,
        state.aur_count,
        risk_score,
        risk_level,
    );

    let summary = build_summary_data(state, items, &risk_reasons, risk_score, risk_level);

    let elapsed = start_time.elapsed();
    let duration_ms = u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
    tracing::info!(
        stage = "summary",
        item_count = items.len(),
        duration_ms = duration_ms,
        "Preflight summary computation complete"
    );

    PreflightSummaryOutcome {
        summary,
        header,
        reverse_deps_report,
    }
}

#[cfg(all(test, unix))]
mod tests;