raps-reality 4.15.0

Reality Capture client for RAPS
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
850
851
852
853
// SPDX-License-Identifier: Apache-2.0
#![allow(clippy::uninlined_format_args)]
// Copyright 2024-2025 Dmytro Yemelianov

//! Reality Capture API module
//!
//! Handles photogrammetry processing to create 3D models from photos.

// API response structs may contain fields we don't use - this is expected for external API contracts
#![allow(dead_code)]

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;
use tokio::fs::File;
use tokio::io::AsyncReadExt;

use raps_kernel::auth::AuthClient;
use raps_kernel::config::Config;
use raps_kernel::http::{self, HttpClientConfig};

/// Photoscene information
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Photoscene {
    #[serde(rename = "photosceneid")]
    pub photoscene_id: String,
    pub name: Option<String>,
    #[serde(rename = "scenetype")]
    pub scene_type: Option<String>,
    #[serde(rename = "convertformat")]
    pub convert_format: Option<String>,
    pub status: Option<String>,
    pub progress: Option<String>,
    #[serde(rename = "progressmsg")]
    pub progress_msg: Option<String>,
}

/// List photoscenes response
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ListPhotoscenesResponse {
    #[serde(default, alias = "photoscenes")]
    pub photoscenes: PhotoscenesList,
}

#[derive(Debug, Default, Deserialize)]
pub struct PhotoscenesList {
    #[serde(default)]
    pub photoscene: Vec<Photoscene>,
}

/// Photoscene creation response
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CreatePhotosceneResponse {
    #[serde(alias = "photoscene")]
    pub photoscene: Photoscene,
}

/// Upload response
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct UploadResponse {
    pub files: Option<UploadFiles>,
    pub usage: Option<String>,
    pub resource: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct UploadFiles {
    pub file: Option<Vec<UploadedFile>>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UploadedFile {
    pub filename: String,
    pub fileid: String,
    /// File size as returned by the API (string format)
    pub filesize: Option<String>,
    pub msg: Option<String>,
}

impl UploadedFile {
    /// Parse filesize string into bytes. Returns None if absent or unparsable.
    pub fn filesize_bytes(&self) -> Option<u64> {
        self.filesize.as_deref().and_then(|s| s.parse().ok())
    }
}

/// API-level error returned with HTTP 200 (documented Reality Capture API quirk)
#[derive(Debug, Deserialize)]
pub struct RcApiError {
    pub code: Option<String>,
    #[serde(alias = "message")]
    pub msg: Option<String>,
}

/// Progress response
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ProgressResponse {
    #[serde(alias = "photoscene")]
    pub photoscene: Option<PhotosceneProgress>,
    #[serde(alias = "error")]
    pub error: Option<RcApiError>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PhotosceneProgress {
    #[serde(rename = "photosceneid")]
    pub photoscene_id: String,
    pub progress: String,
    #[serde(rename = "progressmsg")]
    pub progress_msg: Option<String>,
    pub status: Option<String>,
}

/// Result response
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct ResultResponse {
    #[serde(alias = "photoscene")]
    pub photoscene: Option<PhotosceneResult>,
    #[serde(alias = "error")]
    pub error: Option<RcApiError>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PhotosceneResult {
    #[serde(rename = "photosceneid")]
    pub photoscene_id: String,
    pub progress: String,
    #[serde(rename = "progressmsg")]
    pub progress_msg: Option<String>,
    #[serde(rename = "scenelink")]
    pub scene_link: Option<String>,
    /// File size as returned by the API (string format)
    #[serde(rename = "filesize")]
    pub file_size: Option<String>,
}

impl PhotosceneResult {
    /// Parse file_size string into bytes. Returns None if absent or unparsable.
    pub fn filesize_bytes(&self) -> Option<u64> {
        self.file_size.as_deref().and_then(|s| s.parse().ok())
    }
}

/// Supported output formats
#[derive(Debug, Clone, Copy)]
pub enum OutputFormat {
    Rcm,   // Autodesk ReCap format
    Rcs,   // ReCap scan
    Obj,   // Wavefront OBJ
    Fbx,   // Autodesk FBX
    Ortho, // Orthophoto
}

impl std::fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OutputFormat::Rcm => write!(f, "rcm"),
            OutputFormat::Rcs => write!(f, "rcs"),
            OutputFormat::Obj => write!(f, "obj"),
            OutputFormat::Fbx => write!(f, "fbx"),
            OutputFormat::Ortho => write!(f, "ortho"),
        }
    }
}

impl OutputFormat {
    pub fn all() -> Vec<Self> {
        vec![Self::Rcm, Self::Rcs, Self::Obj, Self::Fbx, Self::Ortho]
    }

    pub fn description(&self) -> &str {
        match self {
            OutputFormat::Rcm => "Autodesk ReCap format (point cloud)",
            OutputFormat::Rcs => "ReCap scan format",
            OutputFormat::Obj => "Wavefront OBJ (mesh)",
            OutputFormat::Fbx => "Autodesk FBX (mesh)",
            OutputFormat::Ortho => "Orthophoto (2D image)",
        }
    }
}

/// Scene type for photoscene
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SceneType {
    Aerial,
    Object,
}

impl std::fmt::Display for SceneType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SceneType::Aerial => write!(f, "aerial"),
            SceneType::Object => write!(f, "object"),
        }
    }
}

/// Reality Capture API client
#[derive(Clone)]
pub struct RealityCaptureClient {
    config: Config,
    auth: AuthClient,
    http_client: reqwest::Client,
}

impl RealityCaptureClient {
    /// Create a new Reality Capture client
    pub fn new(config: Config, auth: AuthClient) -> Self {
        Self::new_with_http_config(config, auth, HttpClientConfig::default())
    }

    /// Create a new Reality Capture client with custom HTTP config
    pub fn new_with_http_config(
        config: Config,
        auth: AuthClient,
        http_config: HttpClientConfig,
    ) -> Self {
        // Create HTTP client with configured timeouts
        let http_client = http_config
            .create_client()
            .unwrap_or_else(|_| reqwest::Client::new()); // Fallback to default if config fails

        Self {
            config,
            auth,
            http_client,
        }
    }

    /// Create a new photoscene
    pub async fn create_photoscene(
        &self,
        name: &str,
        scene_type: SceneType,
        format: OutputFormat,
    ) -> Result<Photoscene> {
        let token = self.auth.get_token().await?;
        let url = format!("{}/photoscene", self.config.reality_capture_url());

        let params = [
            ("scenename", name),
            ("scenetype", &scene_type.to_string()),
            ("format", &format.to_string()),
        ];

        let response = http::send_with_retry(&self.config.http_config, || {
            self.http_client
                .post(&url)
                .bearer_auth(&token)
                .form(&params)
        })
        .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to create photoscene ({status}): {error_text}");
        }

        let create_response: CreatePhotosceneResponse = response
            .json()
            .await
            .context("Failed to parse photoscene response")?;

        Ok(create_response.photoscene)
    }

    /// Upload photos to a photoscene
    pub async fn upload_photos(
        &self,
        photoscene_id: &str,
        photo_paths: &[&Path],
    ) -> Result<Vec<UploadedFile>> {
        let token = self.auth.get_token().await?;
        let url = format!("{}/file", self.config.reality_capture_url());

        // Read all files into memory so the retry closure can rebuild the multipart form
        let mut file_parts: Vec<(String, Vec<u8>)> = Vec::new();
        for path in photo_paths {
            let mut file = File::open(path)
                .await
                .context(format!("Failed to open file: {}", path.display()))?;

            let mut buffer = Vec::new();
            file.read_to_end(&mut buffer)
                .await
                .context("Failed to read file")?;

            let filename = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("photo.jpg")
                .to_string();

            file_parts.push((filename, buffer));
        }

        let photoscene_id_owned = photoscene_id.to_string();
        let response = http::send_with_retry(&self.config.http_config, || {
            let mut form = reqwest::multipart::Form::new()
                .text("photosceneid", photoscene_id_owned.clone())
                .text("type", "image");

            for (i, (filename, buffer)) in file_parts.iter().enumerate() {
                let part = reqwest::multipart::Part::bytes(buffer.clone())
                    .file_name(filename.clone())
                    .mime_str(mime_type_from_extension(filename))
                    .expect("valid MIME type");

                form = form.part(format!("file[{}]", i), part);
            }

            self.http_client
                .post(&url)
                .bearer_auth(&token)
                .multipart(form)
        })
        .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to upload photos ({status}): {error_text}");
        }

        let upload_response: UploadResponse = response
            .json()
            .await
            .context("Failed to parse upload response")?;

        let files = upload_response
            .files
            .and_then(|f| f.file)
            .unwrap_or_default();

        Ok(files)
    }

    /// Start processing a photoscene
    pub async fn start_processing(&self, photoscene_id: &str) -> Result<()> {
        let token = self.auth.get_token().await?;
        let url = format!(
            "{}/photoscene/{}",
            self.config.reality_capture_url(),
            photoscene_id
        );

        let response = http::send_with_retry(&self.config.http_config, || {
            self.http_client.post(&url).bearer_auth(&token)
        })
        .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to start processing ({status}): {error_text}");
        }

        Ok(())
    }

    /// Get photoscene progress
    pub async fn get_progress(&self, photoscene_id: &str) -> Result<PhotosceneProgress> {
        let token = self.auth.get_token().await?;
        let url = format!(
            "{}/photoscene/{}/progress",
            self.config.reality_capture_url(),
            photoscene_id
        );

        let response = http::send_with_retry(&self.config.http_config, || {
            self.http_client.get(&url).bearer_auth(&token)
        })
        .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get progress ({status}): {error_text}");
        }

        let progress_response: ProgressResponse = response
            .json()
            .await
            .context("Failed to parse progress response")?;

        if let Some(err) = progress_response.error {
            let code = err.code.unwrap_or_default();
            let msg = err.msg.unwrap_or_default();
            anyhow::bail!("Reality Capture API error ({code}): {msg}");
        }

        progress_response
            .photoscene
            .ok_or_else(|| anyhow::anyhow!("Progress response missing Photoscene data"))
    }

    /// Get photoscene result (download link)
    pub async fn get_result(
        &self,
        photoscene_id: &str,
        format: OutputFormat,
    ) -> Result<PhotosceneResult> {
        let token = self.auth.get_token().await?;
        let url = format!(
            "{}/photoscene/{}?format={}",
            self.config.reality_capture_url(),
            photoscene_id,
            format
        );

        let response = http::send_with_retry(&self.config.http_config, || {
            self.http_client.get(&url).bearer_auth(&token)
        })
        .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get result ({status}): {error_text}");
        }

        let result_response: ResultResponse = response
            .json()
            .await
            .context("Failed to parse result response")?;

        if let Some(err) = result_response.error {
            let code = err.code.unwrap_or_default();
            let msg = err.msg.unwrap_or_default();
            anyhow::bail!("Reality Capture API error ({code}): {msg}");
        }

        result_response
            .photoscene
            .ok_or_else(|| anyhow::anyhow!("Result response missing Photoscene data"))
    }

    /// Delete a photoscene
    pub async fn delete_photoscene(&self, photoscene_id: &str) -> Result<()> {
        let token = self.auth.get_token().await?;
        let url = format!(
            "{}/photoscene/{}",
            self.config.reality_capture_url(),
            photoscene_id
        );

        let response = http::send_with_retry(&self.config.http_config, || {
            self.http_client.delete(&url).bearer_auth(&token)
        })
        .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to delete photoscene ({status}): {error_text}");
        }

        Ok(())
    }

    /// List all photoscenes
    pub async fn list_photoscenes(&self) -> Result<Vec<Photoscene>> {
        let token = self.auth.get_token().await?;
        let url = format!("{}/photoscene", self.config.reality_capture_url());

        let response = http::send_with_retry(&self.config.http_config, || {
            self.http_client.get(&url).bearer_auth(&token)
        })
        .await?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list photoscenes ({status}): {error_text}");
        }

        let list_response: ListPhotoscenesResponse = response
            .json()
            .await
            .context("Failed to parse photoscenes response")?;

        Ok(list_response.photoscenes.photoscene)
    }

    /// Get available output formats
    pub fn available_formats(&self) -> Vec<OutputFormat> {
        OutputFormat::all()
    }
}

/// Determine MIME type from a filename's extension
fn mime_type_from_extension(filename: &str) -> &'static str {
    let ext = filename
        .rsplit('.')
        .next()
        .unwrap_or("")
        .to_ascii_lowercase();
    match ext.as_str() {
        "jpg" | "jpeg" => "image/jpeg",
        "png" => "image/png",
        "tiff" | "tif" => "image/tiff",
        "bmp" => "image/bmp",
        "webp" => "image/webp",
        "gif" => "image/gif",
        _ => "application/octet-stream",
    }
}

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

    #[test]
    fn test_output_format_all() {
        let formats = OutputFormat::all();
        assert_eq!(formats.len(), 5);
    }

    #[test]
    fn test_output_format_display() {
        assert_eq!(OutputFormat::Rcm.to_string(), "rcm");
        assert_eq!(OutputFormat::Rcs.to_string(), "rcs");
        assert_eq!(OutputFormat::Obj.to_string(), "obj");
        assert_eq!(OutputFormat::Fbx.to_string(), "fbx");
        assert_eq!(OutputFormat::Ortho.to_string(), "ortho");
    }

    #[test]
    fn test_output_format_description() {
        assert!(!OutputFormat::Rcm.description().is_empty());
        assert!(OutputFormat::Rcm.description().contains("ReCap"));
        assert!(OutputFormat::Obj.description().contains("OBJ"));
    }

    #[test]
    fn test_scene_type_display() {
        assert_eq!(SceneType::Aerial.to_string(), "aerial");
        assert_eq!(SceneType::Object.to_string(), "object");
    }

    #[test]
    fn test_scene_type_serialization() {
        assert_eq!(
            serde_json::to_string(&SceneType::Aerial).unwrap(),
            "\"aerial\""
        );
        assert_eq!(
            serde_json::to_string(&SceneType::Object).unwrap(),
            "\"object\""
        );
    }

    #[test]
    fn test_photoscene_deserialization() {
        let json = r#"{
            "photosceneid": "scene-123",
            "name": "Test Scene",
            "scenetype": "object",
            "convertformat": "rcm",
            "status": "Created",
            "progress": "0"
        }"#;

        let scene: Photoscene = serde_json::from_str(json).unwrap();
        assert_eq!(scene.photoscene_id, "scene-123");
        assert_eq!(scene.name, Some("Test Scene".to_string()));
    }

    #[test]
    fn test_photoscene_progress_deserialization() {
        let json = r#"{
            "photosceneid": "scene-123",
            "progress": "50",
            "progressmsg": "Processing images"
        }"#;

        let progress: PhotosceneProgress = serde_json::from_str(json).unwrap();
        assert_eq!(progress.photoscene_id, "scene-123");
        assert_eq!(progress.progress, "50");
    }

    #[test]
    fn test_photoscene_result_deserialization() {
        let json = r#"{
            "photosceneid": "scene-123",
            "progress": "100",
            "progressmsg": "Complete",
            "filesize": "5242880",
            "scenelink": "https://example.com/download/scene.rcm"
        }"#;

        let result: PhotosceneResult = serde_json::from_str(json).unwrap();
        assert_eq!(result.photoscene_id, "scene-123");
        assert!(result.scene_link.is_some());
    }

    #[test]
    fn test_create_photoscene_response_deserialization() {
        let json = r#"{
            "Photoscene": {
                "photosceneid": "new-scene-456",
                "name": "New Scene"
            }
        }"#;

        let response: CreatePhotosceneResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.photoscene.photoscene_id, "new-scene-456");
    }

    #[test]
    fn test_list_photoscenes_response_deserialization() {
        let json = r#"{
            "Photoscenes": {
                "photoscene": [
                    {
                        "photosceneid": "scene-1",
                        "name": "Scene One",
                        "scenetype": "aerial",
                        "status": "Complete",
                        "progress": "100"
                    },
                    {
                        "photosceneid": "scene-2",
                        "name": "Scene Two",
                        "scenetype": "object",
                        "status": "Created",
                        "progress": "0"
                    }
                ]
            }
        }"#;

        let response: ListPhotoscenesResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.photoscenes.photoscene.len(), 2);
        assert_eq!(response.photoscenes.photoscene[0].photoscene_id, "scene-1");
        assert_eq!(response.photoscenes.photoscene[1].photoscene_id, "scene-2");
        assert_eq!(
            response.photoscenes.photoscene[0].name,
            Some("Scene One".to_string())
        );
    }

    #[test]
    fn test_list_photoscenes_response_empty() {
        let json = r#"{
            "Photoscenes": {
                "photoscene": []
            }
        }"#;

        let response: ListPhotoscenesResponse = serde_json::from_str(json).unwrap();
        assert!(response.photoscenes.photoscene.is_empty());
    }

    #[test]
    fn test_list_photoscenes_response_missing_photoscenes() {
        let json = r#"{}"#;

        let response: ListPhotoscenesResponse = serde_json::from_str(json).unwrap();
        assert!(response.photoscenes.photoscene.is_empty());
    }

    #[test]
    fn test_upload_response_deserialization() {
        let json = r#"{
            "Files": {
                "file": [
                    {
                        "filename": "photo1.jpg",
                        "fileid": "file-001",
                        "filesize": "2048000",
                        "msg": "File uploaded"
                    }
                ]
            },
            "Usage": "1",
            "Resource": "/file"
        }"#;

        let response: UploadResponse = serde_json::from_str(json).unwrap();
        assert!(response.files.is_some());
        let files = response.files.unwrap().file.unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].filename, "photo1.jpg");
        assert_eq!(files[0].fileid, "file-001");
    }

    #[test]
    fn test_progress_response_deserialization() {
        let json = r#"{
            "Photoscene": {
                "photosceneid": "scene-789",
                "progress": "75",
                "progressmsg": "Processing images",
                "status": "InProgress"
            }
        }"#;

        let response: ProgressResponse = serde_json::from_str(json).unwrap();
        let ps = response.photoscene.unwrap();
        assert_eq!(ps.photoscene_id, "scene-789");
        assert_eq!(ps.progress, "75");
        assert_eq!(ps.progress_msg, Some("Processing images".to_string()));
    }

    #[test]
    fn test_progress_response_with_error() {
        let json = r#"{
            "Usage": "0.51",
            "Resource": "/photoscene/xyz/progress",
            "Error": {
                "code": "ERR-001",
                "msg": "Scene not found"
            }
        }"#;

        let response: ProgressResponse = serde_json::from_str(json).unwrap();
        assert!(response.photoscene.is_none());
        assert!(response.error.is_some());
        let err = response.error.unwrap();
        assert_eq!(err.code.unwrap(), "ERR-001");
        assert_eq!(err.msg.unwrap(), "Scene not found");
    }

    #[test]
    fn test_mime_type_from_extension() {
        assert_eq!(mime_type_from_extension("photo.jpg"), "image/jpeg");
        assert_eq!(mime_type_from_extension("photo.jpeg"), "image/jpeg");
        assert_eq!(mime_type_from_extension("photo.png"), "image/png");
        assert_eq!(mime_type_from_extension("photo.tiff"), "image/tiff");
        assert_eq!(mime_type_from_extension("photo.tif"), "image/tiff");
        assert_eq!(mime_type_from_extension("photo.bmp"), "image/bmp");
        assert_eq!(mime_type_from_extension("photo.webp"), "image/webp");
        assert_eq!(mime_type_from_extension("photo.gif"), "image/gif");
    }

    #[test]
    fn test_mime_fallback() {
        assert_eq!(
            mime_type_from_extension("photo.raw"),
            "application/octet-stream"
        );
        assert_eq!(
            mime_type_from_extension("photo.xyz"),
            "application/octet-stream"
        );
        assert_eq!(
            mime_type_from_extension("photo.RAW"),
            "application/octet-stream"
        );
    }

    #[test]
    fn test_mime_case_insensitive() {
        assert_eq!(mime_type_from_extension("photo.PNG"), "image/png");
        assert_eq!(mime_type_from_extension("photo.JPEG"), "image/jpeg");
        assert_eq!(mime_type_from_extension("photo.Tiff"), "image/tiff");
    }

    #[test]
    fn test_photoscene_result_filesize_bytes() {
        let result = PhotosceneResult {
            photoscene_id: "scene-1".to_string(),
            progress: "100".to_string(),
            progress_msg: None,
            scene_link: None,
            file_size: Some("5242880".to_string()),
        };
        assert_eq!(result.filesize_bytes(), Some(5_242_880));
    }

    #[test]
    fn test_photoscene_result_filesize_bytes_none() {
        let result = PhotosceneResult {
            photoscene_id: "scene-1".to_string(),
            progress: "100".to_string(),
            progress_msg: None,
            scene_link: None,
            file_size: None,
        };
        assert_eq!(result.filesize_bytes(), None);
    }

    #[test]
    fn test_photoscene_result_filesize_bytes_unparsable() {
        let result = PhotosceneResult {
            photoscene_id: "scene-1".to_string(),
            progress: "100".to_string(),
            progress_msg: None,
            scene_link: None,
            file_size: Some("not-a-number".to_string()),
        };
        assert_eq!(result.filesize_bytes(), None);
    }

    #[test]
    fn test_uploaded_file_filesize_bytes() {
        let file = UploadedFile {
            filename: "photo.jpg".to_string(),
            fileid: "file-1".to_string(),
            filesize: Some("2048000".to_string()),
            msg: None,
        };
        assert_eq!(file.filesize_bytes(), Some(2_048_000));
    }
}

/// Integration tests using raps-mock
#[cfg(test)]
mod integration_tests {
    use super::*;
    use raps_kernel::auth::AuthClient;
    use raps_kernel::config::Config;

    fn create_mock_reality_client(mock_url: &str) -> RealityCaptureClient {
        let config = Config {
            client_id: "test-client-id".to_string(),
            client_secret: "test-client-secret".to_string(),
            base_url: mock_url.to_string(),
            callback_url: "http://localhost:8080/callback".to_string(),
            da_nickname: None,
            http_config: HttpClientConfig::default(),
        };
        let auth = AuthClient::new(config.clone());
        RealityCaptureClient::new(config, auth)
    }

    #[tokio::test]
    async fn test_client_creation() {
        let server = raps_mock::TestServer::start_default().await.unwrap();
        let client = create_mock_reality_client(&server.url);
        assert!(client.auth.config().base_url.starts_with("http://"));
    }

    #[tokio::test]
    async fn test_list_photoscenes() {
        let server = raps_mock::TestServer::start_default().await.unwrap();
        let client = create_mock_reality_client(&server.url);
        let result = client.list_photoscenes().await;
        let _ = result;
    }
}