romm-cli 0.34.0

Rust-based CLI and TUI for the ROMM API
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
use std::path::PathBuf;
use std::time::Duration;

use anyhow::{anyhow, Result};
use clap::{Args, Subcommand};
use dialoguer::Confirm;
use indicatif::{ProgressBar, ProgressStyle};
use serde_json::json;

use crate::client::RommClient;
use crate::commands::library_scan::{
    run_scan_library_flow, ScanCacheInvalidate, ScanLibraryOptions,
};
use crate::commands::print::print_roms_table;
use crate::commands::OutputFormat;
use crate::endpoints::roms::{
    DeleteRomNote, DeleteRoms, GetRomByHash, GetRomByMetadataProvider, GetRomFilters, GetRomNotes,
    GetRoms, GetSearchCover, GetSearchRoms, PostRomNote, PutRomNote, PutRomUserProps,
};
use crate::services::{self};
use crate::services::{
    resolve_manual_collection_id, resolve_platform_ids, resolve_smart_collection_id, RomService,
};

/// Optional tri-state: CLI passes `true` / `false` / `yes` / `no` / `1` / `0`.
fn parse_opt_bool(label: &str, raw: &Option<String>) -> Result<Option<bool>> {
    let Some(s) = raw else {
        return Ok(None);
    };
    let t = s.trim().to_ascii_lowercase();
    if t.is_empty() {
        return Ok(None);
    }
    match t.as_str() {
        "true" | "1" | "yes" | "y" => Ok(Some(true)),
        "false" | "0" | "no" | "n" => Ok(Some(false)),
        _ => Err(anyhow!(
            "Invalid boolean for {}: {:?} (use true or false)",
            label,
            s
        )),
    }
}

/// `roms list` flags (also used as default when no subcommand).
#[derive(Args, Debug, Clone, Default)]
pub struct RomListArgs {
    #[arg(long, visible_aliases = ["query", "q"])]
    pub search_term: Option<String>,
    /// Platform slug or name; repeat for multiple `platform_ids`
    #[arg(long, action = clap::ArgAction::Append, visible_alias = "p")]
    pub platform: Vec<String>,
    /// Manual collection id or exact name
    #[arg(long)]
    pub collection: Option<String>,
    /// Smart collection id or exact name
    #[arg(long)]
    pub smart_collection: Option<String>,
    /// Virtual collection id (e.g. recent)
    #[arg(long)]
    pub virtual_collection: Option<String>,
    #[arg(long)]
    pub limit: Option<u32>,
    #[arg(long)]
    pub offset: Option<u32>,
    #[arg(long)]
    pub matched: Option<String>,
    #[arg(long)]
    pub favorite: Option<String>,
    #[arg(long)]
    pub duplicate: Option<String>,
    #[arg(long)]
    pub last_played: Option<String>,
    #[arg(long)]
    pub playable: Option<String>,
    #[arg(long)]
    pub missing: Option<String>,
    #[arg(long)]
    pub has_ra: Option<String>,
    #[arg(long)]
    pub verified: Option<String>,
    #[arg(long)]
    pub group_by_meta_id: Option<String>,
    #[arg(long)]
    pub with_char_index: Option<String>,
    #[arg(long)]
    pub with_filter_values: Option<String>,
    #[arg(long = "genre", action = clap::ArgAction::Append)]
    pub genres: Vec<String>,
    #[arg(long = "franchise", action = clap::ArgAction::Append)]
    pub franchises: Vec<String>,
    #[arg(long = "collection-tag", action = clap::ArgAction::Append)]
    pub collection_tags: Vec<String>,
    #[arg(long = "company", action = clap::ArgAction::Append)]
    pub companies: Vec<String>,
    #[arg(long = "age-rating", action = clap::ArgAction::Append)]
    pub age_ratings: Vec<String>,
    #[arg(long = "status", action = clap::ArgAction::Append)]
    pub statuses: Vec<String>,
    #[arg(long = "region", action = clap::ArgAction::Append)]
    pub regions: Vec<String>,
    #[arg(long = "language", action = clap::ArgAction::Append)]
    pub languages: Vec<String>,
    #[arg(long = "player-count", action = clap::ArgAction::Append)]
    pub player_counts: Vec<String>,
    #[arg(long)]
    pub genres_logic: Option<String>,
    #[arg(long)]
    pub franchises_logic: Option<String>,
    #[arg(long)]
    pub collections_logic: Option<String>,
    #[arg(long)]
    pub companies_logic: Option<String>,
    #[arg(long)]
    pub age_ratings_logic: Option<String>,
    #[arg(long)]
    pub regions_logic: Option<String>,
    #[arg(long)]
    pub languages_logic: Option<String>,
    #[arg(long)]
    pub statuses_logic: Option<String>,
    #[arg(long)]
    pub player_counts_logic: Option<String>,
    #[arg(long)]
    pub order_by: Option<String>,
    #[arg(long)]
    pub order_dir: Option<String>,
    #[arg(long)]
    pub updated_after: Option<String>,
}

async fn build_get_roms(client: &RommClient, a: RomListArgs) -> Result<GetRoms> {
    let platform_ids = resolve_platform_ids(client, &a.platform).await?;
    let mut platform_id = None;
    let mut extra = platform_ids;
    if extra.len() == 1 {
        platform_id = Some(extra[0]);
        extra.clear();
    } else if extra.len() > 1 {
        platform_id = None;
    }

    Ok(GetRoms {
        search_term: a.search_term,
        platform_id,
        platform_ids: extra,
        collection_id: resolve_manual_collection_id(client, a.collection.as_deref()).await?,
        smart_collection_id: resolve_smart_collection_id(client, a.smart_collection.as_deref())
            .await?,
        virtual_collection_id: a
            .virtual_collection
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty()),
        matched: parse_opt_bool("matched", &a.matched)?,
        favorite: parse_opt_bool("favorite", &a.favorite)?,
        duplicate: parse_opt_bool("duplicate", &a.duplicate)?,
        last_played: parse_opt_bool("last_played", &a.last_played)?,
        playable: parse_opt_bool("playable", &a.playable)?,
        missing: parse_opt_bool("missing", &a.missing)?,
        has_ra: parse_opt_bool("has_ra", &a.has_ra)?,
        verified: parse_opt_bool("verified", &a.verified)?,
        group_by_meta_id: parse_opt_bool("group_by_meta_id", &a.group_by_meta_id)?,
        with_char_index: parse_opt_bool("with_char_index", &a.with_char_index)?,
        with_filter_values: parse_opt_bool("with_filter_values", &a.with_filter_values)?,
        genres: a.genres,
        franchises: a.franchises,
        collections: a.collection_tags,
        companies: a.companies,
        age_ratings: a.age_ratings,
        statuses: a.statuses,
        regions: a.regions,
        languages: a.languages,
        player_counts: a.player_counts,
        genres_logic: a.genres_logic,
        franchises_logic: a.franchises_logic,
        collections_logic: a.collections_logic,
        companies_logic: a.companies_logic,
        age_ratings_logic: a.age_ratings_logic,
        regions_logic: a.regions_logic,
        languages_logic: a.languages_logic,
        statuses_logic: a.statuses_logic,
        player_counts_logic: a.player_counts_logic,
        order_by: a.order_by,
        order_dir: a.order_dir,
        updated_after: a.updated_after,
        limit: a.limit,
        offset: a.offset,
    })
}

/// CLI entrypoint for listing/searching ROMs via `/api/roms`.
#[derive(Args, Debug)]
pub struct RomsCommand {
    /// Output as JSON (overrides global --json when set).
    #[arg(long, global = true)]
    pub json: bool,

    /// Flags for the default `list` action (`romm-cli roms` with no subcommand, or before a subcommand).
    #[command(flatten)]
    pub list: RomListArgs,

    #[command(subcommand)]
    pub action: Option<RomsAction>,
}

#[derive(Subcommand, Debug)]
pub enum RomsAction {
    /// Get detailed information for a single ROM
    #[command(visible_alias = "info")]
    Get {
        /// The ID of the ROM
        id: u64,
    },
    /// Lookup ROM by file hash or metadata provider id
    Find {
        #[arg(long)]
        crc: Option<String>,
        #[arg(long)]
        md5: Option<String>,
        #[arg(long)]
        sha1: Option<String>,
        #[arg(long)]
        igdb_id: Option<i64>,
        #[arg(long)]
        moby_id: Option<i64>,
        #[arg(long)]
        ss_id: Option<i64>,
        #[arg(long)]
        ra_id: Option<i64>,
        #[arg(long)]
        launchbox_id: Option<i64>,
        #[arg(long)]
        hasheous_id: Option<i64>,
        #[arg(long)]
        tgdb_id: Option<i64>,
        #[arg(long)]
        flashpoint_id: Option<String>,
        #[arg(long)]
        hltb_id: Option<i64>,
    },
    /// Print canonical filter values from `GET /api/roms/filters`
    Filters,
    /// Delete ROMs from the database (optional filesystem delete)
    Delete {
        /// ROM ids to remove from the database
        #[arg(required = true)]
        rom_ids: Vec<u64>,
        /// Also delete these ROM ids from disk (repeat ids as needed)
        #[arg(long, action = clap::ArgAction::Append)]
        delete_from_fs: Vec<u64>,
        /// Skip confirmation
        #[arg(long)]
        yes: bool,
    },
    /// Update per-user ROM properties (`PUT /api/roms/{id}/props`)
    Props {
        id: u64,
        #[arg(long)]
        is_main_sibling: Option<String>,
        #[arg(long)]
        backlogged: Option<String>,
        #[arg(long)]
        now_playing: Option<String>,
        #[arg(long)]
        hidden: Option<String>,
        #[arg(long)]
        rating: Option<u8>,
        #[arg(long)]
        difficulty: Option<u8>,
        #[arg(long)]
        completion: Option<u8>,
        #[arg(long)]
        status: Option<String>,
        #[arg(long)]
        update_last_played: bool,
        #[arg(long)]
        remove_last_played: bool,
    },
    /// List notes for a ROM
    NotesList {
        rom_id: u64,
        #[arg(long)]
        public_only: Option<String>,
        #[arg(long)]
        search: Option<String>,
        #[arg(long = "tag", action = clap::ArgAction::Append)]
        tags: Vec<String>,
    },
    /// Add a note (JSON body string, e.g. {\"title\":\"t\",\"content\":\"c\"})
    NotesAdd {
        rom_id: u64,
        /// JSON object
        #[arg(long)]
        json: String,
    },
    /// Update a note
    NotesUpdate {
        rom_id: u64,
        note_id: u64,
        #[arg(long)]
        json: String,
    },
    /// Delete a note
    NotesDelete { rom_id: u64, note_id: u64 },
    /// Upload a manual file (`POST /api/roms/{id}/manuals`)
    ManualsAdd { rom_id: u64, file: PathBuf },
    /// Search covers and metadata matches
    CoverSearch {
        rom_id: u64,
        #[arg(long)]
        query: String,
        #[arg(long, default_value = "name")]
        search_by: String,
    },
    /// Upload a ROM file to a platform
    #[command(visible_alias = "up")]
    Upload {
        /// Platform slug or name (e.g. "3ds", "Nintendo 3DS")
        #[arg(long)]
        platform: String,
        /// File or directory to upload
        file: PathBuf,
        /// Trigger a library scan after upload completes
        #[arg(short, long)]
        scan: bool,
        /// Wait until the library scan finishes (requires `--scan`; polls every 2 seconds)
        #[arg(long, requires = "scan")]
        wait: bool,
        /// Max seconds to wait when `--wait` is set (default: 3600)
        #[arg(long, requires = "wait")]
        wait_timeout_secs: Option<u64>,
    },
}

fn make_progress_style() -> ProgressStyle {
    ProgressStyle::with_template(
        "[{elapsed_precise}] {bar:40.cyan/blue} {bytes}/{total_bytes} ({eta}) {msg}",
    )
    .unwrap()
    .progress_chars("#>-")
}

async fn upload_one(
    client: &RommClient,
    platform_id: u64,
    file_path: std::path::PathBuf,
    pb: ProgressBar,
) -> Result<()> {
    let filename = file_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("file")
        .to_string();

    pb.set_message(format!("Uploading {}", filename));

    client
        .upload_rom(platform_id, &file_path, {
            let pb = pb.clone();
            move |uploaded, total| {
                if pb.length() != Some(total) {
                    pb.set_length(total);
                }
                pb.set_position(uploaded);
            }
        })
        .await?;

    pb.finish_with_message(format!("✓ Upload complete: {}", filename));
    Ok(())
}

pub async fn handle(cmd: RomsCommand, client: &RommClient, format: OutputFormat) -> Result<()> {
    match cmd.action {
        None => {
            let ep = build_get_roms(client, cmd.list.clone()).await?;
            let service = RomService::new(client);
            let results = service.search_roms(&ep).await?;
            match format {
                OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&results)?),
                OutputFormat::Text => print_roms_table(&results),
            }
        }
        Some(RomsAction::Get { id }) => {
            let service = RomService::new(client);
            let rom = service.get_rom(id).await?;
            match format {
                OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&rom)?),
                OutputFormat::Text => println!("{}", serde_json::to_string_pretty(&rom)?),
            }
        }
        Some(RomsAction::Find {
            crc,
            md5,
            sha1,
            igdb_id,
            moby_id,
            ss_id,
            ra_id,
            launchbox_id,
            hasheous_id,
            tgdb_id,
            flashpoint_id,
            hltb_id,
        }) => {
            let hash_ep = GetRomByHash {
                crc_hash: crc.clone(),
                md5_hash: md5.clone(),
                sha1_hash: sha1.clone(),
            };
            let has_hash = crc.is_some() || md5.is_some() || sha1.is_some();
            let has_meta = igdb_id.is_some()
                || moby_id.is_some()
                || ss_id.is_some()
                || ra_id.is_some()
                || launchbox_id.is_some()
                || hasheous_id.is_some()
                || tgdb_id.is_some()
                || flashpoint_id.is_some()
                || hltb_id.is_some();
            if has_hash == has_meta {
                anyhow::bail!("Specify either hash flags (--crc/--md5/--sha1) or metadata id flags (--igdb-id, ...), not both.");
            }
            let v = if has_hash {
                client.call(&hash_ep).await?
            } else {
                client
                    .call(&GetRomByMetadataProvider {
                        igdb_id,
                        moby_id,
                        ss_id,
                        ra_id,
                        launchbox_id,
                        hasheous_id,
                        tgdb_id,
                        flashpoint_id,
                        hltb_id,
                    })
                    .await?
            };
            println!("{}", serde_json::to_string_pretty(&v)?);
        }
        Some(RomsAction::Filters) => {
            let v = client.call(&GetRomFilters).await?;
            println!("{}", serde_json::to_string_pretty(&v)?);
        }
        Some(RomsAction::Delete {
            rom_ids,
            delete_from_fs,
            yes,
        }) => {
            if !yes {
                let ok = Confirm::new()
                    .with_prompt(format!(
                        "Delete {} ROM(s) from the database (and {} from disk)?",
                        rom_ids.len(),
                        delete_from_fs.len()
                    ))
                    .interact()?;
                if !ok {
                    return Ok(());
                }
            }
            let v = client
                .call(&DeleteRoms {
                    roms: rom_ids,
                    delete_from_fs,
                })
                .await?;
            println!("{}", serde_json::to_string_pretty(&v)?);
        }
        Some(RomsAction::Props {
            id,
            is_main_sibling,
            backlogged,
            now_playing,
            hidden,
            rating,
            difficulty,
            completion,
            status,
            update_last_played,
            remove_last_played,
        }) => {
            if update_last_played && remove_last_played {
                anyhow::bail!(
                    "--update-last-played and --remove-last-played are mutually exclusive."
                );
            }
            let mut body = json!({});
            let obj = body.as_object_mut().unwrap();
            if let Some(b) = parse_opt_bool("is_main_sibling", &is_main_sibling)? {
                obj.insert("is_main_sibling".into(), json!(b));
            }
            if let Some(b) = parse_opt_bool("backlogged", &backlogged)? {
                obj.insert("backlogged".into(), json!(b));
            }
            if let Some(b) = parse_opt_bool("now_playing", &now_playing)? {
                obj.insert("now_playing".into(), json!(b));
            }
            if let Some(b) = parse_opt_bool("hidden", &hidden)? {
                obj.insert("hidden".into(), json!(b));
            }
            if let Some(r) = rating {
                obj.insert("rating".into(), json!(r));
            }
            if let Some(d) = difficulty {
                obj.insert("difficulty".into(), json!(d));
            }
            if let Some(c) = completion {
                obj.insert("completion".into(), json!(c));
            }
            if let Some(ref s) = status {
                if !s.is_empty() {
                    obj.insert("status".into(), json!(s));
                }
            }
            let v = client
                .call(&PutRomUserProps {
                    rom_id: id,
                    body,
                    update_last_played,
                    remove_last_played,
                })
                .await?;
            println!("{}", serde_json::to_string_pretty(&v)?);
        }
        Some(RomsAction::NotesList {
            rom_id,
            public_only,
            search,
            tags,
        }) => {
            let v = client
                .call(&GetRomNotes {
                    rom_id,
                    public_only: parse_opt_bool("public_only", &public_only)?,
                    search,
                    tags,
                })
                .await?;
            println!("{}", serde_json::to_string_pretty(&v)?);
        }
        Some(RomsAction::NotesAdd { rom_id, json: body }) => {
            let parsed: serde_json::Value = serde_json::from_str(&body)?;
            let v = client
                .call(&PostRomNote {
                    rom_id,
                    body: parsed,
                })
                .await?;
            println!("{}", serde_json::to_string_pretty(&v)?);
        }
        Some(RomsAction::NotesUpdate {
            rom_id,
            note_id,
            json: body,
        }) => {
            let parsed: serde_json::Value = serde_json::from_str(&body)?;
            let v = client
                .call(&PutRomNote {
                    rom_id,
                    note_id,
                    body: parsed,
                })
                .await?;
            println!("{}", serde_json::to_string_pretty(&v)?);
        }
        Some(RomsAction::NotesDelete { rom_id, note_id }) => {
            let v = client.call(&DeleteRomNote { rom_id, note_id }).await?;
            println!("{}", serde_json::to_string_pretty(&v)?);
        }
        Some(RomsAction::ManualsAdd { rom_id, file }) => {
            let v = client.upload_rom_manual(rom_id, &file).await?;
            println!("{}", serde_json::to_string_pretty(&v)?);
        }
        Some(RomsAction::CoverSearch {
            rom_id,
            query,
            search_by,
        }) => {
            let cover = client
                .call(&GetSearchCover {
                    search_term: query.clone(),
                })
                .await?;
            let roms = client
                .call(&GetSearchRoms {
                    rom_id,
                    search_term: Some(query),
                    search_by: Some(search_by),
                })
                .await?;
            let out = json!({ "cover": cover, "roms": roms });
            println!("{}", serde_json::to_string_pretty(&out)?);
        }
        Some(RomsAction::Upload {
            file,
            platform,
            scan,
            wait,
            wait_timeout_secs,
        }) => {
            let resolved_platform_id = match services::resolve_platform_id(
                client,
                Some(platform.trim()),
            )
            .await?
            {
                Some(id) => id,
                None => {
                    return Err(anyhow!(
                        "`--platform` must not be empty (use a slug or name from `romm-cli platforms list`)"
                    ));
                }
            };

            if !file.exists() {
                anyhow::bail!("File or directory does not exist: {:?}", file);
            }

            let mut files = Vec::new();
            if file.is_dir() {
                let mut entries = tokio::fs::read_dir(&file).await?;
                while let Some(entry) = entries.next_entry().await? {
                    let path = entry.path();
                    if path.is_file() {
                        files.push(path);
                    }
                }
                files.sort();
            } else {
                files.push(file);
            }

            if files.is_empty() {
                println!("No files found to upload.");
                return Ok(());
            }

            if files.len() > 1 {
                println!("Found {} files to upload.", files.len());
            }

            let mp = indicatif::MultiProgress::new();
            let mut successes = 0u32;
            for path in files {
                let pb = mp.add(ProgressBar::new(0));
                pb.set_style(make_progress_style());
                match upload_one(client, resolved_platform_id, path.clone(), pb).await {
                    Ok(()) => successes += 1,
                    Err(e) => eprintln!("Error uploading {:?}: {}", path, e),
                }
            }

            if scan {
                if successes == 0 {
                    eprintln!("Skipping library scan: no uploads completed successfully.");
                } else {
                    let options = ScanLibraryOptions {
                        wait,
                        wait_timeout: Duration::from_secs(wait_timeout_secs.unwrap_or(3600)),
                        cache_invalidate: if wait {
                            ScanCacheInvalidate::Platform(resolved_platform_id)
                        } else {
                            ScanCacheInvalidate::None
                        },
                        task_kwargs: None,
                    };
                    run_scan_library_flow(client, options, format, None).await?;
                }
            }
        }
    }

    Ok(())
}

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

    use crate::commands::{Cli, Commands};

    #[test]
    fn parse_roms_list_with_platform_filter() {
        let cli = Cli::parse_from(["romm-cli", "roms", "--platform", "3ds", "--limit", "10"]);
        let Commands::Roms(cmd) = cli.command else {
            panic!("expected roms command");
        };
        assert!(cmd.action.is_none());
        assert_eq!(cmd.list.platform, vec!["3ds".to_string()]);
        assert_eq!(cmd.list.limit, Some(10));
    }

    #[test]
    fn parse_roms_get_rejects_list_only_filter() {
        let parsed = Cli::try_parse_from(["romm-cli", "roms", "get", "1", "--platform", "3ds"]);
        assert!(parsed.is_err(), "expected clap parse failure");
    }

    #[test]
    fn parse_roms_list_rejects_platform_id_flag() {
        let parsed = Cli::try_parse_from(["romm-cli", "roms", "--platform-id", "3"]);
        assert!(parsed.is_err(), "expected clap parse failure");
    }

    #[test]
    fn parse_roms_upload_requires_platform() {
        let parsed = Cli::try_parse_from(["romm-cli", "roms", "upload", "foo.bin"]);
        assert!(
            parsed.is_err(),
            "expected clap parse failure without --platform"
        );
    }

    #[test]
    fn parse_roms_upload_with_platform_and_file() {
        let cli = Cli::parse_from(["romm-cli", "roms", "upload", "--platform", "3ds", "foo.bin"]);
        let Commands::Roms(cmd) = cli.command else {
            panic!("expected roms command");
        };
        let Some(RomsAction::Upload { platform, file, .. }) = cmd.action else {
            panic!("expected roms upload");
        };
        assert_eq!(platform, "3ds");
        assert_eq!(file, PathBuf::from("foo.bin"));
    }
}