torc 0.20.7

Workflow management system
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! Utilities for automatic RO-Crate entity generation.
//!
//! This module provides helper functions for creating RO-Crate entities for workflow files
//! when `enable_ro_crate` is set on a workflow.

use crate::client::apis::configuration::Configuration;
use crate::client::apis::default_api;
use crate::models::{FileModel, JobModel, RoCrateEntityModel};
use chrono::{DateTime, Utc};
use log::{debug, warn};
use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::{BufReader, Read as IoRead};
use std::path::Path;

/// Compute the SHA256 hash of a file.
///
/// Returns the hash as a lowercase hexadecimal string, or None if the file
/// cannot be read.
pub fn compute_file_sha256(path: &str) -> Option<String> {
    let file = match File::open(path) {
        Ok(f) => f,
        Err(e) => {
            debug!("Cannot open file for SHA256 computation '{}': {}", path, e);
            return None;
        }
    };

    let mut reader = BufReader::new(file);
    let mut hasher = Sha256::new();
    let mut buffer = [0u8; 8192];

    loop {
        match reader.read(&mut buffer) {
            Ok(0) => break,
            Ok(n) => hasher.update(&buffer[..n]),
            Err(e) => {
                debug!("Error reading file for SHA256 '{}': {}", path, e);
                return None;
            }
        }
    }

    Some(format!("{:x}", hasher.finalize()))
}

/// Build an RO-Crate File entity for a workflow file.
///
/// Creates a JSON-LD entity with:
/// - `@id`: file path
/// - `@type`: "File"
/// - `name`: basename from path
/// - `encodingFormat`: MIME type via `mime_guess`
/// - `contentSize`: file size (when available)
/// - `sha256`: SHA256 hash (when available)
/// - `dateModified`: ISO8601 from st_mtime
/// - `torc:run_id`: workflow run that recorded this entity
pub fn build_file_entity(
    workflow_id: i64,
    run_id: i64,
    file: &FileModel,
    content_size: Option<u64>,
    sha256: Option<String>,
) -> RoCrateEntityModel {
    let file_path = &file.path;
    let basename = Path::new(file_path)
        .file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| file_path.clone());

    // Infer MIME type from file extension
    let mime_type = mime_guess::from_path(file_path)
        .first()
        .map(|m| m.to_string())
        .unwrap_or_else(|| "application/octet-stream".to_string());

    // Build metadata JSON object
    let mut metadata = serde_json::json!({
        "@id": file_path,
        "@type": "File",
        "name": basename,
        "encodingFormat": mime_type,
        "torc:run_id": run_id
    });

    // Add content size if available
    if let Some(size) = content_size {
        metadata["contentSize"] = serde_json::json!(size);
    }

    // Add SHA256 hash if available
    if let Some(hash) = sha256 {
        metadata["sha256"] = serde_json::json!(hash);
    }

    // Add date modified from st_mtime if available
    if let Some(st_mtime) = file.st_mtime {
        let datetime = DateTime::<Utc>::from_timestamp(st_mtime as i64, 0).unwrap_or_else(Utc::now);
        metadata["dateModified"] = serde_json::json!(datetime.to_rfc3339());
    }

    RoCrateEntityModel {
        id: None,
        workflow_id,
        file_id: file.id,
        entity_id: file_path.clone(),
        entity_type: "File".to_string(),
        metadata: metadata.to_string(),
    }
}

/// Build an RO-Crate File entity with provenance linking to a CreateAction.
///
/// For output files, includes `wasGeneratedBy` linking to the job's CreateAction entity.
pub fn build_file_entity_with_provenance(
    workflow_id: i64,
    run_id: i64,
    file: &FileModel,
    content_size: Option<u64>,
    sha256: Option<String>,
    job_id: i64,
    attempt_id: i64,
) -> RoCrateEntityModel {
    let file_path = &file.path;
    let basename = Path::new(file_path)
        .file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| file_path.clone());

    // Infer MIME type from file extension
    let mime_type = mime_guess::from_path(file_path)
        .first()
        .map(|m| m.to_string())
        .unwrap_or_else(|| "application/octet-stream".to_string());

    // Create action reference for provenance
    let create_action_id = format!("#job-{}-attempt-{}", job_id, attempt_id);

    // Build metadata JSON object with provenance
    let mut metadata = serde_json::json!({
        "@id": file_path,
        "@type": "File",
        "name": basename,
        "encodingFormat": mime_type,
        "wasGeneratedBy": { "@id": create_action_id },
        "torc:run_id": run_id
    });

    // Add content size if available
    if let Some(size) = content_size {
        metadata["contentSize"] = serde_json::json!(size);
    }

    // Add SHA256 hash if available
    if let Some(hash) = sha256 {
        metadata["sha256"] = serde_json::json!(hash);
    }

    // Add date modified from st_mtime if available
    if let Some(st_mtime) = file.st_mtime {
        let datetime = DateTime::<Utc>::from_timestamp(st_mtime as i64, 0).unwrap_or_else(Utc::now);
        metadata["dateModified"] = serde_json::json!(datetime.to_rfc3339());
    }

    RoCrateEntityModel {
        id: None,
        workflow_id,
        file_id: file.id,
        entity_id: file_path.clone(),
        entity_type: "File".to_string(),
        metadata: metadata.to_string(),
    }
}

/// Build a CreateAction entity for job provenance.
///
/// Creates a JSON-LD entity representing the job execution:
/// - `@id`: `#job-{job_id}-attempt-{attempt_id}`
/// - `@type`: "CreateAction"
/// - `name`: job name
/// - `instrument`: reference to workflow
/// - `result`: references to output file entities
pub fn build_create_action_entity(
    workflow_id: i64,
    run_id: i64,
    job: &JobModel,
    attempt_id: i64,
    output_file_paths: &[String],
) -> RoCrateEntityModel {
    let action_id = format!("#job-{}-attempt-{}", job.id.unwrap_or(0), attempt_id);

    // Build result references to output files
    let results: Vec<serde_json::Value> = output_file_paths
        .iter()
        .map(|path| serde_json::json!({ "@id": path }))
        .collect();

    let metadata = serde_json::json!({
        "@id": action_id,
        "@type": "CreateAction",
        "name": job.name,
        "instrument": { "@id": format!("#workflow-{}", workflow_id) },
        "result": results,
        "torc:run_id": run_id
    });

    RoCrateEntityModel {
        id: None,
        workflow_id,
        file_id: None,
        entity_id: action_id,
        entity_type: "CreateAction".to_string(),
        metadata: metadata.to_string(),
    }
}

/// Find an existing RO-Crate entity for a file.
///
/// Returns the entity if one with the given file_id already exists, None otherwise.
pub fn find_entity_for_file(
    config: &Configuration,
    workflow_id: i64,
    file_id: i64,
) -> Option<RoCrateEntityModel> {
    match default_api::list_ro_crate_entities(config, workflow_id, None, None) {
        Ok(response) => {
            if let Some(entities) = response.items {
                entities.into_iter().find(|e| e.file_id == Some(file_id))
            } else {
                None
            }
        }
        Err(e) => {
            warn!("Failed to check for existing RO-Crate entities: {}", e);
            None
        }
    }
}

/// Check if an RO-Crate entity already exists for a file.
///
/// Returns true if an entity with the given file_id already exists.
pub fn entity_exists_for_file(config: &Configuration, workflow_id: i64, file_id: i64) -> bool {
    find_entity_for_file(config, workflow_id, file_id).is_some()
}

/// Create or replace an RO-Crate entity for a file.
///
/// If an entity already exists for this file, it is updated with fresh metadata
/// (hash, size, timestamps, run_id). Otherwise a new entity is created.
///
/// This is a non-blocking operation - warnings are logged but errors don't fail
/// the calling operation.
pub fn create_ro_crate_entity_for_file(
    config: &Configuration,
    workflow_id: i64,
    run_id: i64,
    file: &FileModel,
    content_size: Option<u64>,
) {
    let file_id = match file.id {
        Some(id) => id,
        None => {
            warn!("Cannot create RO-Crate entity: file has no ID");
            return;
        }
    };

    // Compute SHA256 hash
    let sha256 = compute_file_sha256(&file.path);

    // Build the entity
    let entity = build_file_entity(workflow_id, run_id, file, content_size, sha256);

    // Check if entity already exists - if so, update it
    if let Some(existing) = find_entity_for_file(config, workflow_id, file_id) {
        let entity_id = match existing.id {
            Some(id) => id,
            None => {
                warn!("Existing entity has no ID, cannot update");
                return;
            }
        };

        let updated_entity = RoCrateEntityModel {
            id: Some(entity_id),
            ..entity
        };

        match default_api::update_ro_crate_entity(config, entity_id, updated_entity) {
            Ok(_) => {
                debug!(
                    "Updated RO-Crate entity for file '{}' (entity_id={})",
                    file.path, entity_id
                );
            }
            Err(e) => {
                warn!(
                    "Failed to update RO-Crate entity for file '{}': {}",
                    file.path, e
                );
            }
        }
        return;
    }

    match default_api::create_ro_crate_entity(config, entity) {
        Ok(created) => {
            debug!(
                "Created RO-Crate entity for file '{}' (entity_id={})",
                file.path,
                created.id.unwrap_or(0)
            );
        }
        Err(e) => {
            warn!(
                "Failed to create RO-Crate entity for file '{}': {}",
                file.path, e
            );
        }
    }
}

/// Create an RO-Crate entity for an output file with provenance.
///
/// Creates the File entity and links it to the job's CreateAction. If an entity
/// already exists for this file (e.g., created during initialization), updates it
/// to add the `wasGeneratedBy` provenance field.
///
/// This is a non-blocking operation - warnings are logged but errors don't fail
/// the calling operation.
pub fn create_ro_crate_entity_for_output_file(
    config: &Configuration,
    workflow_id: i64,
    run_id: i64,
    file: &FileModel,
    content_size: Option<u64>,
    job_id: i64,
    attempt_id: i64,
) {
    let file_id = match file.id {
        Some(id) => id,
        None => {
            warn!("Cannot create RO-Crate entity: file has no ID");
            return;
        }
    };

    // Compute SHA256 hash
    let sha256 = compute_file_sha256(&file.path);

    // Build the entity with provenance
    let entity = build_file_entity_with_provenance(
        workflow_id,
        run_id,
        file,
        content_size,
        sha256,
        job_id,
        attempt_id,
    );

    // Check if entity already exists - if so, replace it
    if let Some(existing) = find_entity_for_file(config, workflow_id, file_id) {
        let entity_id = match existing.id {
            Some(id) => id,
            None => {
                warn!("Existing entity has no ID, cannot update");
                return;
            }
        };

        let updated_entity = RoCrateEntityModel {
            id: Some(entity_id),
            ..entity
        };

        match default_api::update_ro_crate_entity(config, entity_id, updated_entity) {
            Ok(_) => {
                debug!(
                    "Updated RO-Crate entity for output file '{}' with provenance (entity_id={})",
                    file.path, entity_id
                );
            }
            Err(e) => {
                warn!(
                    "Failed to update RO-Crate entity for output file '{}': {}",
                    file.path, e
                );
            }
        }
        return;
    }

    // No existing entity - create a new one

    match default_api::create_ro_crate_entity(config, entity) {
        Ok(created) => {
            debug!(
                "Created RO-Crate entity for output file '{}' (entity_id={})",
                file.path,
                created.id.unwrap_or(0)
            );
        }
        Err(e) => {
            warn!(
                "Failed to create RO-Crate entity for output file '{}': {}",
                file.path, e
            );
        }
    }
}

/// Create a CreateAction entity for a job.
///
/// This is a non-blocking operation - warnings are logged but errors don't fail
/// the calling operation.
pub fn create_create_action_entity(
    config: &Configuration,
    workflow_id: i64,
    run_id: i64,
    job: &JobModel,
    attempt_id: i64,
    output_file_paths: &[String],
) {
    let entity =
        build_create_action_entity(workflow_id, run_id, job, attempt_id, output_file_paths);

    match default_api::create_ro_crate_entity(config, entity) {
        Ok(created) => {
            debug!(
                "Created RO-Crate CreateAction entity for job '{}' (entity_id={})",
                job.name,
                created.id.unwrap_or(0)
            );
        }
        Err(e) => {
            warn!(
                "Failed to create RO-Crate CreateAction entity for job '{}': {}",
                job.name, e
            );
        }
    }
}

/// Create RO-Crate entities for input files of a workflow.
///
/// Called during workflow initialization when `enable_ro_crate` is true.
/// Input files are identified as files with `st_mtime` set (they exist before the workflow runs).
pub fn create_entities_for_input_files(
    config: &Configuration,
    workflow_id: i64,
    run_id: i64,
    files: &[FileModel],
) {
    for file in files {
        // Input files have st_mtime set (they exist before workflow runs)
        if file.st_mtime.is_some() {
            // Get file size if the file exists
            let content_size = std::fs::metadata(&file.path).ok().map(|m| m.len());

            create_ro_crate_entity_for_file(config, workflow_id, run_id, file, content_size);
        }
    }
}

/// Binary info for creating SoftwareApplication RO-Crate entities.
struct BinaryInfo {
    name: &'static str,
    path: String,
    version: String,
    sha256: Option<String>,
    file_size: Option<u64>,
}

/// Detect a binary: resolve its path, version, hash, and size.
/// Returns None if the binary is not found.
///
/// Looks for the binary in the same directory as the current executable first,
/// then falls back to searching PATH.
fn detect_binary(name: &'static str) -> Option<BinaryInfo> {
    // First, look in the same directory as the current executable
    let path = std::env::current_exe()
        .ok()
        .and_then(|exe| exe.parent().map(|dir| dir.join(name)))
        .filter(|p| p.is_file())
        .or_else(|| {
            // Fall back to searching PATH
            std::env::var_os("PATH").and_then(|paths| {
                std::env::split_paths(&paths)
                    .map(|dir| dir.join(name))
                    .find(|p| p.is_file())
            })
        });

    let path = match path {
        Some(p) => p,
        None => {
            debug!("Binary '{}' not found", name);
            return None;
        }
    };

    let path_str = path.display().to_string();

    // Get version by running --version
    let version = match std::process::Command::new(&path).arg("--version").output() {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            // Parse version: typically "name X.Y.Z" or just "X.Y.Z"
            stdout.lines().next().unwrap_or("").trim().to_string()
        }
        Err(e) => {
            debug!("Could not get version for '{}': {}", name, e);
            "unknown".to_string()
        }
    };

    let sha256 = compute_file_sha256(&path_str);
    let file_size = std::fs::metadata(&path).ok().map(|m| m.len());

    Some(BinaryInfo {
        name,
        path: path_str,
        version,
        sha256,
        file_size,
    })
}

/// Build a SoftwareApplication RO-Crate entity for a binary.
fn build_software_entity(workflow_id: i64, run_id: i64, info: &BinaryInfo) -> RoCrateEntityModel {
    let entity_id = format!("#software-{}-run-{}", info.name, run_id);

    let mut metadata = serde_json::json!({
        "@id": entity_id,
        "@type": "SoftwareApplication",
        "name": info.name,
        "version": info.version,
        "url": info.path,
        "torc:run_id": run_id,
    });

    if let Some(size) = info.file_size {
        metadata["contentSize"] = serde_json::json!(size);
    }

    if let Some(ref hash) = info.sha256 {
        metadata["sha256"] = serde_json::json!(hash);
    }

    RoCrateEntityModel {
        id: None,
        workflow_id,
        file_id: None,
        entity_id,
        entity_type: "SoftwareApplication".to_string(),
        metadata: metadata.to_string(),
    }
}

/// Create RO-Crate SoftwareApplication entities for torc binaries.
///
/// Attempts to create entities for `torc` and (on Linux) `torc-slurm-job-runner`.
/// Binaries that are not found on the system are silently skipped.
/// The `torc-server` entity is created server-side (see `RoCrateApiImpl`).
///
/// This is called during workflow initialization regardless of `enable_ro_crate`.
/// The `run_id` is included in each entity to distinguish software records across runs.
pub fn create_software_entities(config: &Configuration, workflow_id: i64, run_id: i64) {
    let mut binary_names: Vec<&str> = vec!["torc"];

    // torc-slurm-job-runner is only available on Linux
    if cfg!(target_os = "linux") {
        binary_names.push("torc-slurm-job-runner");
    }

    // Check existing entities to avoid duplicates
    let existing_ids: std::collections::HashSet<String> =
        match default_api::list_ro_crate_entities(config, workflow_id, None, None) {
            Ok(response) => response
                .items
                .unwrap_or_default()
                .into_iter()
                .map(|e| e.entity_id)
                .collect(),
            Err(e) => {
                warn!(
                    "Failed to list existing RO-Crate entities for workflow {}: {}",
                    workflow_id, e
                );
                std::collections::HashSet::new()
            }
        };

    for name in binary_names {
        let entity_id = format!("#software-{}-run-{}", name, run_id);
        if existing_ids.contains(&entity_id) {
            debug!(
                "SoftwareApplication entity '{}' already exists, skipping",
                entity_id
            );
            continue;
        }

        if let Some(info) = detect_binary(name) {
            let entity = build_software_entity(workflow_id, run_id, &info);
            match default_api::create_ro_crate_entity(config, entity) {
                Ok(created) => {
                    debug!(
                        "Created SoftwareApplication entity for '{}' version='{}' (entity_id={})",
                        name,
                        info.version,
                        created.id.unwrap_or(0)
                    );
                }
                Err(e) => {
                    warn!(
                        "Failed to create SoftwareApplication entity for '{}': {}",
                        name, e
                    );
                }
            }
        }
    }
}

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

    #[test]
    fn test_build_file_entity_basic() {
        let file = FileModel {
            id: Some(1),
            workflow_id: 100,
            name: "output.csv".to_string(),
            path: "data/output.csv".to_string(),
            st_mtime: Some(1704067200.0), // 2024-01-01T00:00:00Z
        };

        let entity = build_file_entity(100, 1, &file, Some(1024), None);

        assert_eq!(entity.workflow_id, 100);
        assert_eq!(entity.file_id, Some(1));
        assert_eq!(entity.entity_id, "data/output.csv");
        assert_eq!(entity.entity_type, "File");

        let metadata: serde_json::Value = serde_json::from_str(&entity.metadata).unwrap();
        assert_eq!(metadata["@id"], "data/output.csv");
        assert_eq!(metadata["@type"], "File");
        assert_eq!(metadata["name"], "output.csv");
        assert_eq!(metadata["encodingFormat"], "text/csv");
        assert_eq!(metadata["contentSize"], 1024);
        assert_eq!(metadata["torc:run_id"], 1);
    }

    #[test]
    fn test_build_file_entity_with_provenance() {
        let file = FileModel {
            id: Some(2),
            workflow_id: 100,
            name: "result.json".to_string(),
            path: "output/result.json".to_string(),
            st_mtime: Some(1704067200.0),
        };

        let entity = build_file_entity_with_provenance(100, 1, &file, None, None, 42, 1);

        let metadata: serde_json::Value = serde_json::from_str(&entity.metadata).unwrap();
        assert_eq!(metadata["wasGeneratedBy"]["@id"], "#job-42-attempt-1");
        assert_eq!(metadata["torc:run_id"], 1);
    }

    #[test]
    fn test_build_create_action_entity() {
        let job = JobModel::new(
            100,
            "process_data".to_string(),
            "python process.py".to_string(),
        );
        let mut job_with_id = job;
        job_with_id.id = Some(42);

        let output_files = vec![
            "output/result1.json".to_string(),
            "output/result2.json".to_string(),
        ];

        let entity = build_create_action_entity(100, 1, &job_with_id, 1, &output_files);

        assert_eq!(entity.entity_id, "#job-42-attempt-1");
        assert_eq!(entity.entity_type, "CreateAction");

        let metadata: serde_json::Value = serde_json::from_str(&entity.metadata).unwrap();
        assert_eq!(metadata["@type"], "CreateAction");
        assert_eq!(metadata["name"], "process_data");
        assert_eq!(metadata["instrument"]["@id"], "#workflow-100");
        assert!(metadata["result"].is_array());
        assert_eq!(metadata["result"][0]["@id"], "output/result1.json");
        assert_eq!(metadata["torc:run_id"], 1);
    }

    #[test]
    fn test_mime_type_inference() {
        // Test that known file types get appropriate MIME types (not the default)
        let known_types = ["file.json", "file.csv", "file.txt", "file.py", "file.rs"];

        for path in known_types {
            let file = FileModel {
                id: Some(1),
                workflow_id: 1,
                name: path.to_string(),
                path: path.to_string(),
                st_mtime: None,
            };

            let entity = build_file_entity(1, 1, &file, None, None);
            let metadata: serde_json::Value = serde_json::from_str(&entity.metadata).unwrap();
            let mime = metadata["encodingFormat"].as_str().unwrap();

            // Known file types should not fall back to the default
            assert_ne!(
                mime, "application/octet-stream",
                "Expected known file type '{}' to have a specific MIME type, not the default",
                path
            );
        }

        // Test that unknown file types get the default
        let unknown_types = ["file", "file.xyz123"];

        for path in unknown_types {
            let file = FileModel {
                id: Some(1),
                workflow_id: 1,
                name: path.to_string(),
                path: path.to_string(),
                st_mtime: None,
            };

            let entity = build_file_entity(1, 1, &file, None, None);
            let metadata: serde_json::Value = serde_json::from_str(&entity.metadata).unwrap();
            let mime = metadata["encodingFormat"].as_str().unwrap();

            assert_eq!(
                mime, "application/octet-stream",
                "Expected unknown file type '{}' to have the default MIME type",
                path
            );
        }
    }

    #[test]
    fn test_serde_json_deserialize_ro_crate() {
        // Test that standard serde_json deserialization works
        let json =
            r#"{"workflow_id":1,"entity_id":"test.txt","entity_type":"File","metadata":"{}"}"#;
        let model: crate::models::RoCrateEntityModel = serde_json::from_str(json).unwrap();
        assert_eq!(model.workflow_id, 1);
        assert_eq!(model.entity_id, "test.txt");
        assert_eq!(model.entity_type, "File");
    }

    #[test]
    fn test_ro_crate_entity_model_roundtrip() {
        // Test serialization and deserialization roundtrip
        let model = crate::models::RoCrateEntityModel {
            id: None,
            workflow_id: 1,
            file_id: None,
            entity_id: "data/output.parquet".to_string(),
            entity_type: "File".to_string(),
            metadata: r#"{"name":"Test"}"#.to_string(),
        };

        // Serialize to JSON
        let json = serde_json::to_string(&model).unwrap();
        println!("Serialized JSON: {}", json);

        // Deserialize back
        let parsed: crate::models::RoCrateEntityModel = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.workflow_id, 1);
        assert_eq!(parsed.entity_id, "data/output.parquet");
        assert_eq!(parsed.entity_type, "File");
    }

    #[test]
    fn test_compute_file_sha256() {
        use std::io::Write;

        // Create a temporary file with known content
        let temp_dir = std::env::temp_dir();
        let temp_file = temp_dir.join("test_sha256.txt");
        let mut file = std::fs::File::create(&temp_file).unwrap();
        file.write_all(b"hello world").unwrap();
        drop(file);

        // Compute hash - "hello world" has a well-known SHA256
        let hash = compute_file_sha256(temp_file.to_str().unwrap());
        assert!(hash.is_some());
        // SHA256("hello world") = b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
        assert_eq!(
            hash.unwrap(),
            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
        );

        // Clean up
        std::fs::remove_file(&temp_file).unwrap();
    }

    #[test]
    fn test_compute_file_sha256_nonexistent() {
        let hash = compute_file_sha256("/nonexistent/path/to/file.txt");
        assert!(hash.is_none());
    }

    #[test]
    fn test_build_file_entity_with_sha256() {
        let file = FileModel {
            id: Some(1),
            workflow_id: 100,
            name: "output.csv".to_string(),
            path: "data/output.csv".to_string(),
            st_mtime: Some(1704067200.0),
        };

        let sha256 = Some("abc123def456".to_string());
        let entity = build_file_entity(100, 1, &file, Some(1024), sha256);

        let metadata: serde_json::Value = serde_json::from_str(&entity.metadata).unwrap();
        assert_eq!(metadata["sha256"], "abc123def456");
    }

    #[test]
    fn test_build_file_entity_with_provenance_and_sha256() {
        let file = FileModel {
            id: Some(2),
            workflow_id: 100,
            name: "result.json".to_string(),
            path: "output/result.json".to_string(),
            st_mtime: Some(1704067200.0),
        };

        let sha256 = Some("deadbeef".to_string());
        let entity = build_file_entity_with_provenance(100, 1, &file, None, sha256, 42, 1);

        let metadata: serde_json::Value = serde_json::from_str(&entity.metadata).unwrap();
        assert_eq!(metadata["sha256"], "deadbeef");
        assert_eq!(metadata["wasGeneratedBy"]["@id"], "#job-42-attempt-1");
    }

    #[test]
    fn test_build_software_entity() {
        let info = BinaryInfo {
            name: "torc",
            path: "/usr/local/bin/torc".to_string(),
            version: "torc 0.19.2".to_string(),
            sha256: Some("abc123".to_string()),
            file_size: Some(50_000_000),
        };

        let entity = build_software_entity(100, 3, &info);

        assert_eq!(entity.workflow_id, 100);
        assert_eq!(entity.file_id, None);
        assert_eq!(entity.entity_id, "#software-torc-run-3");
        assert_eq!(entity.entity_type, "SoftwareApplication");

        let metadata: serde_json::Value = serde_json::from_str(&entity.metadata).unwrap();
        assert_eq!(metadata["@id"], "#software-torc-run-3");
        assert_eq!(metadata["@type"], "SoftwareApplication");
        assert_eq!(metadata["name"], "torc");
        assert_eq!(metadata["version"], "torc 0.19.2");
        assert_eq!(metadata["url"], "/usr/local/bin/torc");
        assert_eq!(metadata["contentSize"], 50_000_000);
        assert_eq!(metadata["sha256"], "abc123");
        assert_eq!(metadata["torc:run_id"], 3);
    }

    #[test]
    fn test_build_software_entity_without_optional_fields() {
        let info = BinaryInfo {
            name: "torc-server",
            path: "/usr/local/bin/torc-server".to_string(),
            version: "unknown".to_string(),
            sha256: None,
            file_size: None,
        };

        let entity = build_software_entity(42, 1, &info);

        assert_eq!(entity.entity_id, "#software-torc-server-run-1");
        assert_eq!(entity.entity_type, "SoftwareApplication");

        let metadata: serde_json::Value = serde_json::from_str(&entity.metadata).unwrap();
        assert_eq!(metadata["name"], "torc-server");
        assert_eq!(metadata["torc:run_id"], 1);
        assert!(metadata.get("contentSize").is_none());
        assert!(metadata.get("sha256").is_none());
    }

    #[test]
    fn test_detect_binary_finds_current_exe() {
        // The current test binary should be findable
        let exe = std::env::current_exe().unwrap();
        let exe_name = exe.file_name().unwrap().to_str().unwrap();

        let info = detect_binary(Box::leak(exe_name.to_string().into_boxed_str()));
        // This may or may not succeed depending on the test runner name,
        // but it shouldn't panic
        if let Some(info) = info {
            assert!(!info.path.is_empty());
        }
    }
}