romm-cli 0.22.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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! HTTP client wrapper around the ROMM API.
//!
//! `RommClient` owns a configured `reqwest::Client` plus base URL and
//! authentication settings. Frontends (CLI, TUI, or a future GUI) depend
//! on this type instead of talking to `reqwest` directly.

use anyhow::{anyhow, Result};
use base64::{engine::general_purpose, Engine as _};
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use reqwest::{Client as HttpClient, Method};
use serde_json::Value;
use std::path::Path;
use std::time::Instant;
use tokio::io::AsyncWriteExt as _;

use crate::config::{normalize_romm_origin, AuthConfig, Config};
use crate::endpoints::Endpoint;

/// Default `User-Agent` for every request. The stock `reqwest` UA is sometimes blocked at the HTTP
/// layer (403, etc.) by reverse proxies; override with env `ROMM_USER_AGENT` if needed.
fn http_user_agent() -> String {
    match std::env::var("ROMM_USER_AGENT") {
        Ok(s) if !s.trim().is_empty() => s,
        _ => format!(
            "Mozilla/5.0 (compatible; romm-cli/{}; +https://github.com/patricksmill/romm-cli)",
            env!("CARGO_PKG_VERSION")
        ),
    }
}

/// Map a successful HTTP response body to JSON [`Value`].
///
/// Empty or whitespace-only bodies become [`Value::Null`] (e.g. HTTP 204).
/// Non-JSON UTF-8 bodies are wrapped as `{"_non_json_body": "..."}`.
fn decode_json_response_body(bytes: &[u8]) -> Value {
    if bytes.is_empty() || bytes.iter().all(|b| b.is_ascii_whitespace()) {
        return Value::Null;
    }
    serde_json::from_slice(bytes).unwrap_or_else(|_| {
        serde_json::json!({
            "_non_json_body": String::from_utf8_lossy(bytes).to_string()
        })
    })
}

fn version_from_heartbeat_json(v: &Value) -> Option<String> {
    v.get("SYSTEM")?.get("VERSION")?.as_str().map(String::from)
}

/// High-level HTTP client for the ROMM API.
///
/// This type hides the details of `reqwest` and authentication headers
/// behind a small, easy-to-mock interface that all frontends can share.
#[derive(Clone)]
pub struct RommClient {
    http: HttpClient,
    base_url: String,
    auth: Option<AuthConfig>,
    verbose: bool,
}

/// Same as [`crate::config::normalize_romm_origin`]: browser-style origin for RomM (no `/api` suffix).
pub fn api_root_url(base_url: &str) -> String {
    normalize_romm_origin(base_url)
}

fn alternate_http_scheme_root(root: &str) -> Option<String> {
    root.strip_prefix("http://")
        .map(|rest| format!("https://{}", rest))
        .or_else(|| {
            root.strip_prefix("https://")
                .map(|rest| format!("http://{}", rest))
        })
}

/// Origin used to fetch `/openapi.json` (same as the RomM website). Normally equals
/// [`normalize_romm_origin`] applied to `API_BASE_URL`.
///
/// Set `ROMM_OPENAPI_BASE_URL` only when that origin differs (wrong host in `API_BASE_URL`, split
/// DNS, etc.).
pub fn resolve_openapi_root(api_base_url: &str) -> String {
    if let Ok(s) = std::env::var("ROMM_OPENAPI_BASE_URL") {
        let t = s.trim();
        if !t.is_empty() {
            return normalize_romm_origin(t);
        }
    }
    normalize_romm_origin(api_base_url)
}

/// URLs to try for the OpenAPI JSON document (scheme fallback and alternate paths).
///
/// `api_root` is an origin such as `https://example.com` (see [`resolve_openapi_root`]).
pub fn openapi_spec_urls(api_root: &str) -> Vec<String> {
    let root = api_root.trim_end_matches('/').to_string();
    let mut roots = vec![root.clone()];
    if let Some(alt) = alternate_http_scheme_root(&root) {
        if alt != root {
            roots.push(alt);
        }
    }

    let mut urls = Vec::new();
    for r in roots {
        let b = r.trim_end_matches('/');
        urls.push(format!("{b}/openapi.json"));
        urls.push(format!("{b}/api/openapi.json"));
    }
    urls
}

impl RommClient {
    /// Construct a new client from the high-level [`Config`].
    ///
    /// `verbose` enables stderr request logging (method, path, query key names, status, timing).
    /// This is typically done once in `main` and the resulting `RommClient` is shared
    /// (by reference or cloning) with the chosen frontend.
    pub fn new(config: &Config, verbose: bool) -> Result<Self> {
        let http = HttpClient::builder()
            .user_agent(http_user_agent())
            .build()?;
        Ok(Self {
            http,
            base_url: config.base_url.clone(),
            auth: config.auth.clone(),
            verbose,
        })
    }

    pub fn verbose(&self) -> bool {
        self.verbose
    }

    /// Build the HTTP headers for the current authentication mode.
    ///
    /// This helper centralises all auth logic so that the rest of the
    /// code never needs to worry about `Basic` vs `Bearer` vs API key.
    fn build_headers(&self) -> Result<HeaderMap> {
        let mut headers = HeaderMap::new();

        if let Some(auth) = &self.auth {
            match auth {
                AuthConfig::Basic { username, password } => {
                    let creds = format!("{username}:{password}");
                    let encoded = general_purpose::STANDARD.encode(creds.as_bytes());
                    let value = format!("Basic {encoded}");
                    headers.insert(
                        AUTHORIZATION,
                        HeaderValue::from_str(&value)
                            .map_err(|_| anyhow!("invalid basic auth header value"))?,
                    );
                }
                AuthConfig::Bearer { token } => {
                    let value = format!("Bearer {token}");
                    headers.insert(
                        AUTHORIZATION,
                        HeaderValue::from_str(&value)
                            .map_err(|_| anyhow!("invalid bearer auth header value"))?,
                    );
                }
                AuthConfig::ApiKey { header, key } => {
                    let name = reqwest::header::HeaderName::from_bytes(header.as_bytes()).map_err(
                        |_| anyhow!("invalid API_KEY_HEADER, must be a valid HTTP header name"),
                    )?;
                    headers.insert(
                        name,
                        HeaderValue::from_str(key)
                            .map_err(|_| anyhow!("invalid API_KEY header value"))?,
                    );
                }
            }
        }

        Ok(headers)
    }

    /// Call a typed endpoint using the low-level `request_json` primitive.
    pub async fn call<E>(&self, ep: &E) -> anyhow::Result<E::Output>
    where
        E: Endpoint,
        E::Output: serde::de::DeserializeOwned,
    {
        let method = ep.method();
        let path = ep.path();
        let query = ep.query();
        let body = ep.body();

        let value = self.request_json(method, &path, &query, body).await?;
        let output = serde_json::from_value(value)
            .map_err(|e| anyhow!("failed to decode response for {} {}: {}", method, path, e))?;

        Ok(output)
    }

    /// Low-level helper that issues an HTTP request and returns raw JSON.
    ///
    /// Higher-level helpers (such as typed `Endpoint` implementations)
    /// should prefer [`RommClient::call`] instead of using this directly.
    pub async fn request_json(
        &self,
        method: &str,
        path: &str,
        query: &[(String, String)],
        body: Option<Value>,
    ) -> Result<Value> {
        let url = format!(
            "{}/{}",
            self.base_url.trim_end_matches('/'),
            path.trim_start_matches('/')
        );
        let headers = self.build_headers()?;

        let http_method = Method::from_bytes(method.as_bytes())
            .map_err(|_| anyhow!("invalid HTTP method: {method}"))?;

        // Ensure query params serialize as key=value pairs (reqwest/serde_urlencoded
        // expect sequences of (key, value); using &[(&str, &str)] guarantees correct encoding).
        let query_refs: Vec<(&str, &str)> = query
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        let mut req = self
            .http
            .request(http_method, &url)
            .headers(headers)
            .query(&query_refs);

        if let Some(body) = body {
            req = req.json(&body);
        }

        let t0 = Instant::now();
        let resp = req
            .send()
            .await
            .map_err(|e| anyhow!("request error: {e}"))?;

        let status = resp.status();
        if self.verbose {
            let keys: Vec<&str> = query.iter().map(|(k, _)| k.as_str()).collect();
            tracing::info!(
                "[romm-cli] {} {} query_keys={:?} -> {} ({}ms)",
                method,
                path,
                keys,
                status.as_u16(),
                t0.elapsed().as_millis()
            );
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(anyhow!(
                "ROMM API error: {} {} - {}",
                status.as_u16(),
                status.canonical_reason().unwrap_or(""),
                body
            ));
        }

        let bytes = resp
            .bytes()
            .await
            .map_err(|e| anyhow!("read response body: {e}"))?;

        Ok(decode_json_response_body(&bytes))
    }

    pub async fn request_json_unauthenticated(
        &self,
        method: &str,
        path: &str,
        query: &[(String, String)],
        body: Option<Value>,
    ) -> Result<Value> {
        let url = format!(
            "{}/{}",
            self.base_url.trim_end_matches('/'),
            path.trim_start_matches('/')
        );
        let headers = HeaderMap::new();

        let http_method = Method::from_bytes(method.as_bytes())
            .map_err(|_| anyhow!("invalid HTTP method: {method}"))?;

        // Ensure query params serialize as key=value pairs (reqwest/serde_urlencoded
        // expect sequences of (key, value); using &[(&str, &str)] guarantees correct encoding).
        let query_refs: Vec<(&str, &str)> = query
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        let mut req = self
            .http
            .request(http_method, &url)
            .headers(headers)
            .query(&query_refs);

        if let Some(body) = body {
            req = req.json(&body);
        }

        let t0 = Instant::now();
        let resp = req
            .send()
            .await
            .map_err(|e| anyhow!("request error: {e}"))?;

        let status = resp.status();
        if self.verbose {
            let keys: Vec<&str> = query.iter().map(|(k, _)| k.as_str()).collect();
            tracing::info!(
                "[romm-cli] {} {} query_keys={:?} -> {} ({}ms)",
                method,
                path,
                keys,
                status.as_u16(),
                t0.elapsed().as_millis()
            );
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(anyhow!(
                "ROMM API error: {} {} - {}",
                status.as_u16(),
                status.canonical_reason().unwrap_or(""),
                body
            ));
        }

        let bytes = resp
            .bytes()
            .await
            .map_err(|e| anyhow!("read response body: {e}"))?;

        Ok(decode_json_response_body(&bytes))
    }

    /// RomM application version from `GET /api/heartbeat` (`SYSTEM.VERSION`), if the endpoint succeeds.
    pub async fn rom_server_version_from_heartbeat(&self) -> Option<String> {
        let v = self
            .request_json_unauthenticated("GET", "/api/heartbeat", &[], None)
            .await
            .ok()?;
        version_from_heartbeat_json(&v)
    }

    /// GET the OpenAPI spec from the server. Tries [`openapi_spec_urls`] in order (HTTP/HTTPS and
    /// `/openapi.json` vs `/api/openapi.json`). Uses [`resolve_openapi_root`] for the origin.
    pub async fn fetch_openapi_json(&self) -> Result<String> {
        let root = resolve_openapi_root(&self.base_url);
        let urls = openapi_spec_urls(&root);
        let mut failures = Vec::new();
        for url in &urls {
            match self.fetch_openapi_json_once(url).await {
                Ok(body) => return Ok(body),
                Err(e) => failures.push(format!("{url}: {e:#}")),
            }
        }
        Err(anyhow!(
            "could not download OpenAPI ({} attempt(s)): {}",
            failures.len(),
            failures.join(" | ")
        ))
    }

    async fn fetch_openapi_json_once(&self, url: &str) -> Result<String> {
        let headers = self.build_headers()?;

        let t0 = Instant::now();
        let resp = self
            .http
            .get(url)
            .headers(headers)
            .send()
            .await
            .map_err(|e| anyhow!("request failed: {e}"))?;

        let status = resp.status();
        if self.verbose {
            tracing::info!(
                "[romm-cli] GET {} -> {} ({}ms)",
                url,
                status.as_u16(),
                t0.elapsed().as_millis()
            );
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(anyhow!(
                "HTTP {} {} - {}",
                status.as_u16(),
                status.canonical_reason().unwrap_or(""),
                body.chars().take(500).collect::<String>()
            ));
        }

        resp.text()
            .await
            .map_err(|e| anyhow!("read OpenAPI body: {e}"))
    }

    /// Download ROM(s) as a zip file to `save_path`, calling `on_progress(received, total)`.
    /// Uses GET /api/roms/download?rom_ids={id}&filename=... per RomM OpenAPI.
    ///
    /// If `save_path` already exists on disk (e.g. from a previous interrupted
    /// download), the client sends an HTTP `Range` header to resume from the
    /// existing byte offset. The server may reply with `206 Partial Content`
    /// (resume works) or `200 OK` (server doesn't support ranges — restart
    /// from scratch).
    pub async fn download_rom<F>(
        &self,
        rom_id: u64,
        save_path: &Path,
        mut on_progress: F,
    ) -> Result<()>
    where
        F: FnMut(u64, u64) + Send,
    {
        let path = "/api/roms/download";
        let url = format!(
            "{}/{}",
            self.base_url.trim_end_matches('/'),
            path.trim_start_matches('/')
        );
        let mut headers = self.build_headers()?;

        let filename = save_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("download.zip");

        // Check for an existing partial file to resume from.
        let existing_len = tokio::fs::metadata(save_path)
            .await
            .map(|m| m.len())
            .unwrap_or(0);

        if existing_len > 0 {
            let range = format!("bytes={existing_len}-");
            if let Ok(v) = reqwest::header::HeaderValue::from_str(&range) {
                headers.insert(reqwest::header::RANGE, v);
            }
        }

        let t0 = Instant::now();
        let mut resp = self
            .http
            .get(&url)
            .headers(headers)
            .query(&[
                ("rom_ids", rom_id.to_string()),
                ("filename", filename.to_string()),
            ])
            .send()
            .await
            .map_err(|e| anyhow!("download request error: {e}"))?;

        let status = resp.status();
        if self.verbose {
            tracing::info!(
                "[romm-cli] GET /api/roms/download rom_id={} filename={:?} -> {} ({}ms)",
                rom_id,
                filename,
                status.as_u16(),
                t0.elapsed().as_millis()
            );
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(anyhow!(
                "ROMM API error: {} {} - {}",
                status.as_u16(),
                status.canonical_reason().unwrap_or(""),
                body
            ));
        }

        // Determine whether the server honoured our Range header.
        let (mut received, total, mut file) = if status == reqwest::StatusCode::PARTIAL_CONTENT {
            // 206 — resume: content_length is the *remaining* bytes.
            let remaining = resp.content_length().unwrap_or(0);
            let total = existing_len + remaining;
            let file = tokio::fs::OpenOptions::new()
                .append(true)
                .open(save_path)
                .await
                .map_err(|e| anyhow!("open file for append {:?}: {e}", save_path))?;
            (existing_len, total, file)
        } else {
            // 200 — server doesn't support ranges; start from scratch.
            let total = resp.content_length().unwrap_or(0);
            let file = tokio::fs::File::create(save_path)
                .await
                .map_err(|e| anyhow!("create file {:?}: {e}", save_path))?;
            (0u64, total, file)
        };

        while let Some(chunk) = resp.chunk().await.map_err(|e| anyhow!("read chunk: {e}"))? {
            file.write_all(&chunk)
                .await
                .map_err(|e| anyhow!("write chunk {:?}: {e}", save_path))?;
            received += chunk.len() as u64;
            on_progress(received, total);
        }

        Ok(())
    }

    /// Upload a ROM file using the RomM chunked upload API.
    pub async fn upload_rom<F>(
        &self,
        platform_id: u64,
        file_path: &Path,
        mut on_progress: F,
    ) -> Result<()>
    where
        F: FnMut(u64, u64) + Send,
    {
        let filename = file_path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| anyhow!("Invalid filename for upload"))?;

        let metadata = tokio::fs::metadata(file_path)
            .await
            .map_err(|e| anyhow!("Failed to read file metadata {:?}: {}", file_path, e))?;
        let total_size = metadata.len();

        // 2MB chunk size
        let chunk_size: u64 = 2 * 1024 * 1024;
        // Use integer division ceiling
        let total_chunks = if total_size == 0 {
            1
        } else {
            total_size.div_ceil(chunk_size)
        };

        let mut start_headers = self.build_headers()?;
        start_headers.insert(
            reqwest::header::HeaderName::from_static("x-upload-platform"),
            reqwest::header::HeaderValue::from_str(&platform_id.to_string())?,
        );
        start_headers.insert(
            reqwest::header::HeaderName::from_static("x-upload-filename"),
            reqwest::header::HeaderValue::from_str(filename)?,
        );
        start_headers.insert(
            reqwest::header::HeaderName::from_static("x-upload-total-size"),
            reqwest::header::HeaderValue::from_str(&total_size.to_string())?,
        );
        start_headers.insert(
            reqwest::header::HeaderName::from_static("x-upload-total-chunks"),
            reqwest::header::HeaderValue::from_str(&total_chunks.to_string())?,
        );

        let start_url = format!(
            "{}/api/roms/upload/start",
            self.base_url.trim_end_matches('/')
        );

        let t0 = Instant::now();
        let resp = self
            .http
            .post(&start_url)
            .headers(start_headers)
            .send()
            .await
            .map_err(|e| anyhow!("upload start request error: {}", e))?;

        let status = resp.status();
        if self.verbose {
            tracing::info!(
                "[romm-cli] POST /api/roms/upload/start -> {} ({}ms)",
                status.as_u16(),
                t0.elapsed().as_millis()
            );
        }

        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(anyhow!(
                "ROMM API error: {} {} - {}",
                status.as_u16(),
                status.canonical_reason().unwrap_or(""),
                body
            ));
        }

        let start_resp: Value = resp
            .json()
            .await
            .map_err(|e| anyhow!("failed to parse start upload response: {}", e))?;
        let upload_id = start_resp
            .get("upload_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow!("Missing upload_id in start response: {}", start_resp))?
            .to_string();

        use tokio::io::AsyncReadExt;
        let mut file = tokio::fs::File::open(file_path).await?;
        let mut uploaded_bytes = 0;
        let mut buffer = vec![0u8; chunk_size as usize];

        for chunk_index in 0..total_chunks {
            let mut chunk_bytes = 0;
            let mut chunk_data = Vec::new();

            while chunk_bytes < chunk_size as usize {
                let n = file.read(&mut buffer[..]).await?;
                if n == 0 {
                    break;
                }
                chunk_data.extend_from_slice(&buffer[..n]);
                chunk_bytes += n;
            }

            let mut chunk_headers = self.build_headers()?;
            chunk_headers.insert(
                reqwest::header::HeaderName::from_static("x-chunk-index"),
                reqwest::header::HeaderValue::from_str(&chunk_index.to_string())?,
            );

            let chunk_url = format!(
                "{}/api/roms/upload/{}",
                self.base_url.trim_end_matches('/'),
                upload_id
            );

            let _t_chunk = Instant::now();
            let chunk_resp = self
                .http
                .put(&chunk_url)
                .headers(chunk_headers)
                .body(chunk_data.clone())
                .send()
                .await
                .map_err(|e| anyhow!("chunk upload request error: {}", e))?;

            if !chunk_resp.status().is_success() {
                let body = chunk_resp.text().await.unwrap_or_default();
                // Attempt to cancel
                let cancel_url = format!(
                    "{}/api/roms/upload/{}/cancel",
                    self.base_url.trim_end_matches('/'),
                    upload_id
                );
                let _ = self
                    .http
                    .post(&cancel_url)
                    .headers(self.build_headers()?)
                    .send()
                    .await;

                return Err(anyhow!("Failed to upload chunk {}: {}", chunk_index, body));
            }

            uploaded_bytes += chunk_data.len() as u64;
            on_progress(uploaded_bytes, total_size);
        }

        let complete_url = format!(
            "{}/api/roms/upload/{}/complete",
            self.base_url.trim_end_matches('/'),
            upload_id
        );
        let complete_resp = self
            .http
            .post(&complete_url)
            .headers(self.build_headers()?)
            .send()
            .await
            .map_err(|e| anyhow!("upload complete request error: {}", e))?;

        if !complete_resp.status().is_success() {
            let body = complete_resp.text().await.unwrap_or_default();
            return Err(anyhow!("Failed to complete upload: {}", body));
        }

        Ok(())
    }

    /// Trigger a server-side task by name (e.g. `"scan_library"`).
    ///
    /// Sends `POST /api/tasks/run/{task_name}` with an optional JSON body
    /// (`task_kwargs`). Returns the raw `TaskExecutionResponse` JSON.
    pub async fn run_task(&self, task_name: &str, kwargs: Option<Value>) -> Result<Value> {
        let path = format!("/api/tasks/run/{}", task_name);
        self.request_json("POST", &path, &[], kwargs).await
    }

    /// Poll the status of a running task.
    ///
    /// Sends `GET /api/tasks/{task_id}`. Returns the raw status JSON.
    pub async fn get_task_status(&self, task_id: &str) -> Result<Value> {
        let path = format!("/api/tasks/{}", task_id);
        self.request_json("GET", &path, &[], None).await
    }
}

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

    #[test]
    fn decode_json_empty_and_whitespace_to_null() {
        assert_eq!(decode_json_response_body(b""), Value::Null);
        assert_eq!(decode_json_response_body(b"  \n\t "), Value::Null);
    }

    #[test]
    fn decode_json_object_roundtrip() {
        let v = decode_json_response_body(br#"{"a":1}"#);
        assert_eq!(v["a"], 1);
    }

    #[test]
    fn decode_non_json_wrapped() {
        let v = decode_json_response_body(b"plain text");
        assert_eq!(v["_non_json_body"], "plain text");
    }

    #[test]
    fn api_root_url_strips_trailing_api() {
        assert_eq!(
            super::api_root_url("http://localhost:8080/api"),
            "http://localhost:8080"
        );
        assert_eq!(
            super::api_root_url("http://localhost:8080/api/"),
            "http://localhost:8080"
        );
        assert_eq!(
            super::api_root_url("http://localhost:8080"),
            "http://localhost:8080"
        );
    }

    #[test]
    fn openapi_spec_urls_try_primary_scheme_then_alt() {
        let urls = super::openapi_spec_urls("http://example.test");
        assert_eq!(urls[0], "http://example.test/openapi.json");
        assert_eq!(urls[1], "http://example.test/api/openapi.json");
        assert!(
            urls.iter()
                .any(|u| u == "https://example.test/openapi.json"),
            "{urls:?}"
        );
    }
}