Skip to main content

qualia_client_core/api/
system.rs

1//! QPU, hardware, engine, daemon, tax, vault, ingest, solid pod, image
2
3#![allow(non_snake_case)]
4
5use super::*;
6
7use crate::engine::ingestion;
8use crate::engine::q42_compiler;
9use crate::state::*;
10use futures_util::StreamExt;
11use qualia_core_db::ilp_dispatcher::{DispatchResult, HttpIlpTransport, IlpDispatcher};
12use qualia_core_db::rpc::{route_tax_payment, TaxRecipientSuite};
13use serde::Serialize;
14use std::io::Write;
15use std::path::{Path, PathBuf};
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::sync::Arc;
18use sysinfo::System;
19
20pub use crate::setup::{SetupProfile, SetupState};
21
22/// Gets setup-state.
23pub fn get_setup_state() -> Result<SetupState, String> {
24    crate::setup::get_setup_state()
25}
26
27/// Completes a setup step.
28pub fn complete_setup_step(step: String) -> Result<SetupState, String> {
29    crate::setup::complete_setup_step(step)
30}
31
32/// Updates the setup profile.
33pub fn update_setup_profile(profile: SetupProfile) -> Result<SetupState, String> {
34    crate::setup::update_setup_profile(profile)
35}
36
37/// Finishes setup.
38pub fn finish_setup() -> Result<SetupState, String> {
39    crate::setup::finish_setup()
40}
41
42// ── Person / apparatus identity plane (person ≠ machine ≠ OS account) ─────────
43
44/// Gets identity-plane.
45pub fn get_identity_plane() -> Result<crate::identity_plane::IdentityPlaneSnapshot, String> {
46    crate::identity_plane::get_identity_plane()
47}
48
49/// Lists apparatus devices.
50pub fn list_apparatus_devices() -> Result<Vec<crate::identity_plane::DeviceRecordPublic>, String> {
51    crate::identity_plane::list_devices()
52}
53
54/// Exports a person public bundle.
55pub fn export_person_public() -> Result<crate::identity_plane::PersonPublic, String> {
56    crate::identity_plane::export_person_public()
57}
58
59/// Recovery-grade bundle to install the same person principal on another machine.
60pub fn export_person_transfer_bundle() -> Result<crate::identity_plane::PersonTransferBundle, String>
61{
62    crate::identity_plane::export_person_transfer_bundle()
63}
64
65/// Imports a person transfer bundle.
66pub fn import_person_transfer_bundle(
67    bundle: crate::identity_plane::PersonTransferBundle,
68) -> Result<crate::identity_plane::IdentityPlaneSnapshot, String> {
69    crate::identity_plane::import_person_transfer_bundle(bundle)
70}
71
72/// Registers a remote apparatus device.
73pub fn register_remote_apparatus_device(
74    device: crate::identity_plane::DeviceRecordPublic,
75) -> Result<crate::identity_plane::IdentityPlaneSnapshot, String> {
76    crate::identity_plane::register_remote_device(device)
77}
78
79/// Resolves job device placement.
80pub fn resolve_job_device_placement(
81    target_device_id: Option<String>,
82) -> Result<crate::identity_plane::JobPlacement, String> {
83    crate::identity_plane::resolve_job_placement(target_device_id.as_deref())
84}
85
86/// Sets local-control-base-url.
87pub fn set_local_control_base_url(
88    url: String,
89) -> Result<crate::identity_plane::IdentityPlaneSnapshot, String> {
90    crate::identity_plane::set_local_control_base_url(url)
91}
92
93/// Lists the remote job outbox.
94pub fn list_remote_job_outbox() -> Result<Vec<crate::identity_plane::RemoteOutboxEntry>, String> {
95    crate::identity_plane::list_remote_outbox()
96}
97
98/// Retries a remote job outbox entry.
99pub fn retry_remote_job_outbox() -> Result<usize, String> {
100    crate::identity_plane::fleet_jobs::retry_remote_outbox()
101}
102
103/// Mint a real WebID-TLS self-signed cert bound to the local person DID (SAN URI).
104pub fn mint_person_webid_tls_cert() -> Result<serde_json::Value, String> {
105    let person = crate::identity_plane::PersonPrincipal::load_or_create(None)?;
106    let (cert_pem, key_pem) = qualia_core_db::key_vault::generate_webid_tls_cert_for_seed(
107        &person.ed25519_secret,
108        &person.person_id,
109    )?;
110    // Persist under app meta for operators (key material is person-secret grade).
111    let dir = crate::state::app_meta_dir().join("certs");
112    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
113    std::fs::write(dir.join("person-webid.crt.pem"), &cert_pem).map_err(|e| e.to_string())?;
114    std::fs::write(dir.join("person-webid.key.pem"), &key_pem).map_err(|e| e.to_string())?;
115    Ok(serde_json::json!({
116        "person_id": person.person_id,
117        "cert_pem": cert_pem,
118        "key_pem_path": dir.join("person-webid.key.pem").display().to_string(),
119        "cert_path": dir.join("person-webid.crt.pem").display().to_string(),
120        "note": "Self-signed WebID-TLS style cert; DID is in SAN URI. Treat key as recovery material."
121    }))
122}
123
124/// Accepts a fleet job envelope.
125pub fn accept_fleet_job_envelope(
126    envelope: crate::identity_plane::FleetJobEnvelope,
127) -> Result<serde_json::Value, String> {
128    let job = crate::identity_plane::accept_fleet_job_envelope(envelope)?;
129    serde_json::to_value(job).map_err(|e| e.to_string())
130}
131
132pub use crate::qpu_oracle::{QpuChatCommandResult, QpuOracleSettings, QpuOracleSettingsInput};
133
134/// Gets qpu-settings.
135pub fn get_qpu_settings() -> QpuOracleSettings {
136    crate::qpu_oracle::get_qpu_settings()
137}
138
139/// `true` when qpu-feature-unlocked.
140pub fn is_qpu_feature_unlocked() -> bool {
141    crate::qpu_oracle::is_qpu_feature_unlocked()
142}
143
144/// Saves qpu-settings.
145pub fn save_qpu_settings(input: QpuOracleSettingsInput) -> Result<QpuOracleSettings, String> {
146    crate::qpu_oracle::save_qpu_settings(input)
147}
148
149/// Handles qpu-chat-command.
150pub fn handle_qpu_chat_command(text: String) -> QpuChatCommandResult {
151    crate::qpu_oracle::handle_qpu_chat_command(&text)
152}
153
154/// Handles engine-chat-command.
155pub fn handle_engine_chat_command(text: String) -> QpuChatCommandResult {
156    crate::qpu_pipeline::handle_engine_chat_command(&text)
157}
158
159/// Profiles energy circumstance.
160pub fn profile_energy_circumstance() -> String {
161    let mut sys = System::new_all();
162    sys.refresh_all();
163    let total_mem = sys.total_memory() / 1024 / 1024;
164    let used_mem = sys.used_memory() / 1024 / 1024;
165    format!(
166        "Energy: AC_POWER\nTotal RAM: {} MB\nUsed RAM: {} MB\nSwarm Auth: GRANTED",
167        total_mem, used_mem
168    )
169}
170
171/// Checks ollama-status.
172pub fn check_ollama_status() -> bool {
173    std::process::Command::new("ollama")
174        .arg("-v")
175        .output()
176        .map(|o| o.status.success())
177        .unwrap_or(false)
178}
179
180#[derive(Serialize)]
181pub struct HardwareStatus {
182    pub ram_total_gb: f64,
183    pub ram_used_gb: f64,
184    pub vram_estimated_gb: f64,
185}
186
187/// Gets hardware-status.
188pub fn get_hardware_status() -> HardwareStatus {
189    let mut sys = System::new_all();
190    sys.refresh_all();
191    let vram_available_gb = {
192        #[cfg(target_os = "windows")]
193        {
194            qualia_core_db::directml_bridge::probe_best_adapter_memory()
195                .map(|memory| {
196                    let free = memory.available_local_bytes();
197                    let fallback = memory.dedicated_vram_bytes;
198                    let bytes = if free > 0 { free } else { fallback };
199                    bytes as f64 / 1024.0 / 1024.0 / 1024.0
200                })
201                .unwrap_or(0.0)
202        }
203        #[cfg(not(target_os = "windows"))]
204        {
205            0.0
206        }
207    };
208    HardwareStatus {
209        ram_total_gb: sys.total_memory() as f64 / 1024.0 / 1024.0 / 1024.0,
210        ram_used_gb: sys.used_memory() as f64 / 1024.0 / 1024.0 / 1024.0,
211        vram_estimated_gb: vram_available_gb,
212    }
213}
214
215/// Orchestrator + LLM arena signals for the Flutter Vault HUD.
216#[derive(Debug, Clone, Serialize)]
217pub struct EngineTelemetryFields {
218    pub thermal_state: String,
219    pub llm_memory_bytes: u64,
220    pub memory_floor_mb: u32,
221    pub model_lifecycle: String,
222    pub kv_cache_used_mb: u32,
223    pub vram_used_mb: u32,
224    pub vram_total_mb: u32,
225    pub npu_used_mb: u32,
226    pub npu_total_mb: u32,
227}
228
229/// Gets engine-telemetry-fields.
230pub fn get_engine_telemetry_fields() -> EngineTelemetryFields {
231    let (vram_used_mb, vram_total_mb) = probe_vram_usage_mb();
232    let (npu_used_mb, npu_total_mb) = probe_npu_usage_mb();
233    EngineTelemetryFields {
234        thermal_state: crate::model_lifecycle::get_thermal_state_label().to_string(),
235        llm_memory_bytes: crate::model_lifecycle::get_llm_memory_bytes(),
236        memory_floor_mb: crate::model_lifecycle::MEMORY_FLOOR_MB,
237        model_lifecycle: crate::model_lifecycle::lifecycle_label(
238            crate::model_lifecycle::get_model_lifecycle_state(),
239        )
240        .to_string(),
241        kv_cache_used_mb: crate::model_lifecycle::get_kv_cache_used_mb(),
242        vram_used_mb,
243        vram_total_mb,
244        npu_used_mb,
245        npu_total_mb,
246    }
247}
248
249fn probe_vram_usage_mb() -> (u32, u32) {
250    #[cfg(target_os = "windows")]
251    {
252        if let Ok(memory) = qualia_core_db::directml_bridge::probe_best_adapter_memory() {
253            let used = memory.local_usage_bytes / (1024 * 1024);
254            let total = memory.local_budget_bytes / (1024 * 1024);
255            return (used as u32, total as u32);
256        }
257    }
258    (0, 0)
259}
260
261fn probe_npu_usage_mb() -> (u32, u32) {
262    #[cfg(target_os = "windows")]
263    {
264        if let Ok(memory) = qualia_core_db::directml_bridge::probe_npu_adapter_memory() {
265            let used = memory.shared_usage_bytes / (1024 * 1024); // NPUs often use shared memory
266            let total = memory.shared_budget_bytes / (1024 * 1024);
267            return (used as u32, total as u32);
268        }
269    }
270    (0, 0)
271}
272
273/// Downloads and vectorizes.
274pub async fn download_and_vectorize(
275    url: String,
276    filename: String,
277    item_id: String,
278) -> Result<String, String> {
279    let state = crate::state::APP_STATE.get().unwrap();
280    let storage_path = state.config.lock().unwrap().storage_path.clone();
281    let handles = state.download_handles.clone();
282    let active_dl = state.active_downloads.clone();
283
284    let index_dir = PathBuf::from(&storage_path).join("Index");
285    std::fs::create_dir_all(&index_dir).map_err(|e| e.to_string())?;
286    let dest_path = index_dir.join(&filename);
287
288    let cancelled = Arc::new(AtomicBool::new(false));
289    handles
290        .lock()
291        .unwrap()
292        .insert(item_id.clone(), cancelled.clone());
293
294    let response = reqwest::get(&url).await.map_err(|e| {
295        handles.lock().unwrap().remove(&item_id);
296        active_dl.lock().unwrap().remove(&item_id);
297        e.to_string()
298    })?;
299    let total_bytes = response.content_length().unwrap_or(0);
300    let mut dest = std::fs::File::create(&dest_path).map_err(|e| e.to_string())?;
301    let mut stream = response.bytes_stream();
302    let mut downloaded: u64 = 0;
303    let mut last_report = std::time::Instant::now();
304    let mut last_downloaded: u64 = 0;
305
306    while let Some(chunk) = stream.next().await {
307        if cancelled.load(Ordering::Relaxed) {
308            let _ = std::fs::remove_file(&dest_path);
309            let payload = ProgressPayload {
310                id: item_id.clone(),
311                progress: 0.0,
312                downloaded_bytes: downloaded,
313                total_bytes,
314                speed_kbps: 0.0,
315                status: "cancelled".to_string(),
316            };
317            let _ = state.download_events.send(payload.clone());
318            handles.lock().unwrap().remove(&item_id);
319            active_dl.lock().unwrap().remove(&item_id);
320            return Err("Cancelled".to_string());
321        }
322        let chunk = chunk.map_err(|e| e.to_string())?;
323        dest.write_all(&chunk).map_err(|e| e.to_string())?;
324        downloaded += chunk.len() as u64;
325
326        let now = std::time::Instant::now();
327        if now.duration_since(last_report).as_millis() >= 200 {
328            let elapsed = now.duration_since(last_report).as_secs_f64().max(0.001);
329            let speed_kbps = ((downloaded - last_downloaded) as f64 / 1024.0) / elapsed;
330            let progress = if total_bytes > 0 {
331                (downloaded as f64 / total_bytes as f64) * 100.0
332            } else {
333                0.0
334            };
335            let payload = ProgressPayload {
336                id: item_id.clone(),
337                progress,
338                downloaded_bytes: downloaded,
339                total_bytes,
340                speed_kbps,
341                status: "downloading".to_string(),
342            };
343            let _ = state.download_events.send(payload.clone());
344            active_dl.lock().unwrap().insert(item_id.clone(), payload);
345            last_report = now;
346            last_downloaded = downloaded;
347        }
348    }
349
350    let processing_payload = ProgressPayload {
351        id: item_id.clone(),
352        progress: 100.0,
353        downloaded_bytes: downloaded,
354        total_bytes,
355        speed_kbps: 0.0,
356        status: "processing".to_string(),
357    };
358    let _ = state.download_events.send(processing_payload.clone());
359    active_dl
360        .lock()
361        .unwrap()
362        .insert(item_id.clone(), processing_payload);
363
364    let _quin_count = crate::resource_import::ingest_local_rdf(
365        &dest_path,
366        &item_id,
367        Path::new(&storage_path),
368        None,
369    )
370    .map_err(|e| e.to_string())?;
371
372    let _ = std::fs::remove_file(&dest_path);
373
374    let done_payload = ProgressPayload {
375        id: item_id.clone(),
376        progress: 100.0,
377        downloaded_bytes: downloaded,
378        total_bytes,
379        speed_kbps: 0.0,
380        status: "complete".to_string(),
381    };
382    let _ = state.download_events.send(done_payload.clone());
383    handles.lock().unwrap().remove(&item_id);
384    active_dl.lock().unwrap().remove(&item_id);
385    Ok("Download and vectorization complete".to_string())
386}
387
388/// Downloads a model.
389pub async fn download_model(
390    url: String,
391    filename: String,
392    model_id: String,
393) -> Result<String, String> {
394    let state = crate::state::APP_STATE.get().unwrap();
395    let storage_path = state.config.lock().unwrap().storage_path.clone();
396    let handles = state.download_handles.clone();
397    let active_dl = state.active_downloads.clone();
398
399    let models_dir = PathBuf::from(&storage_path).join("Models");
400    std::fs::create_dir_all(&models_dir).map_err(|e| e.to_string())?;
401    let dest_path = models_dir.join(&filename);
402
403    let cancelled = Arc::new(AtomicBool::new(false));
404    handles
405        .lock()
406        .unwrap()
407        .insert(model_id.clone(), cancelled.clone());
408
409    let response = reqwest::get(&url)
410        .await
411        .and_then(reqwest::Response::error_for_status)
412        .map_err(|e| {
413            handles.lock().unwrap().remove(&model_id);
414            active_dl.lock().unwrap().remove(&model_id);
415            e.to_string()
416        })?;
417    let total_bytes = response.content_length().unwrap_or(0);
418    let mut dest = std::fs::File::create(&dest_path).map_err(|e| {
419        handles.lock().unwrap().remove(&model_id);
420        active_dl.lock().unwrap().remove(&model_id);
421        format!("create {}: {e}", dest_path.display())
422    })?;
423    let mut stream = response.bytes_stream();
424    let mut downloaded: u64 = 0;
425    let mut last_report = std::time::Instant::now();
426    let mut last_downloaded: u64 = 0;
427
428    while let Some(chunk) = stream.next().await {
429        if cancelled.load(Ordering::Relaxed) {
430            let _ = std::fs::remove_file(&dest_path);
431            let payload = ProgressPayload {
432                id: model_id.clone(),
433                progress: 0.0,
434                downloaded_bytes: downloaded,
435                total_bytes,
436                speed_kbps: 0.0,
437                status: "cancelled".to_string(),
438            };
439            let _ = state.download_events.send(payload.clone());
440            handles.lock().unwrap().remove(&model_id);
441            active_dl.lock().unwrap().remove(&model_id);
442            return Err("Cancelled".to_string());
443        }
444        let chunk = match chunk {
445            Ok(chunk) => chunk,
446            Err(error) => {
447                drop(dest);
448                let _ = std::fs::remove_file(&dest_path);
449                handles.lock().unwrap().remove(&model_id);
450                active_dl.lock().unwrap().remove(&model_id);
451                return Err(format!("download stream failed: {error}"));
452            }
453        };
454        if let Err(error) = dest.write_all(&chunk) {
455            drop(dest);
456            let _ = std::fs::remove_file(&dest_path);
457            handles.lock().unwrap().remove(&model_id);
458            active_dl.lock().unwrap().remove(&model_id);
459            return Err(format!("write {}: {error}", dest_path.display()));
460        }
461        downloaded += chunk.len() as u64;
462
463        let now = std::time::Instant::now();
464        if now.duration_since(last_report).as_millis() >= 200 {
465            let elapsed = now.duration_since(last_report).as_secs_f64().max(0.001);
466            let speed_kbps = ((downloaded - last_downloaded) as f64 / 1024.0) / elapsed;
467            let progress = if total_bytes > 0 {
468                (downloaded as f64 / total_bytes as f64) * 100.0
469            } else {
470                0.0
471            };
472            let payload = ProgressPayload {
473                id: model_id.clone(),
474                progress,
475                downloaded_bytes: downloaded,
476                total_bytes,
477                speed_kbps,
478                status: "downloading".to_string(),
479            };
480            let _ = state.download_events.send(payload.clone());
481            active_dl.lock().unwrap().insert(model_id.clone(), payload);
482            last_report = now;
483            last_downloaded = downloaded;
484        }
485    }
486
487    let done_payload = ProgressPayload {
488        id: model_id.clone(),
489        progress: 100.0,
490        downloaded_bytes: downloaded,
491        total_bytes,
492        speed_kbps: 0.0,
493        status: "complete".to_string(),
494    };
495    let _ = state.download_events.send(done_payload.clone());
496    handles.lock().unwrap().remove(&model_id);
497    active_dl.lock().unwrap().remove(&model_id);
498    Ok(dest_path.to_string_lossy().to_string())
499}
500
501/// Cancels a download.
502pub fn cancel_download(id: String) -> Result<(), String> {
503    let state = crate::state::APP_STATE.get().unwrap();
504    if let Some(flag) = state.download_handles.lock().unwrap().get(&id) {
505        flag.store(true, Ordering::Relaxed);
506    }
507    Ok(())
508}
509
510/// Starts the daemon.
511pub fn start_daemon() -> String {
512    "Daemon Started".to_string()
513}
514
515/// Daemon status.
516pub fn daemon_status() -> String {
517    let state = crate::state::APP_STATE.get().unwrap();
518    if *state.daemon_running.lock().unwrap() {
519        "running".to_string()
520    } else {
521        "stopped".to_string()
522    }
523}
524
525/// Gets tax-suite.
526pub fn get_tax_suite() -> TaxRecipientSuite {
527    let state = crate::state::APP_STATE.get().unwrap();
528    state.tax_suite.lock().unwrap().clone()
529}
530
531/// Saves tax-suite.
532pub fn save_tax_suite(suite: TaxRecipientSuite) -> Result<(), String> {
533    let state = crate::state::APP_STATE.get().unwrap();
534    suite.validate()?;
535    let data_dir = state.config.lock().unwrap().storage_path.clone();
536    let path = suite_file_path(&data_dir);
537    if let Some(p) = path.parent() {
538        std::fs::create_dir_all(p).map_err(|e| e.to_string())?;
539    }
540    let json = serde_json::to_string_pretty(&suite).map_err(|e| e.to_string())?;
541    std::fs::write(&path, json).map_err(|e| e.to_string())?;
542    *state.tax_suite.lock().unwrap() = suite;
543    Ok(())
544}
545
546/// Dispatches a tax payment.
547pub fn dispatch_tax_payment(gross_amount_micro_cents: u64) -> Result<DispatchResult, String> {
548    let state = crate::state::APP_STATE.get().unwrap();
549    let suite = state.tax_suite.lock().unwrap().clone();
550    let plan = route_tax_payment(gross_amount_micro_cents, &suite)?;
551    let disp = IlpDispatcher::new(HttpIlpTransport {
552        connector_url: "http://localhost:7770".to_string(),
553    });
554    Ok(disp.dispatch(&plan))
555}
556
557/// Accepts a vault handshake.
558pub fn accept_vault_handshake(did_key: String, _payload: String) -> Result<String, String> {
559    println!("[VC-8] Vault handshake from: {}", did_key);
560    Ok("HANDSHAKE_SUCCESS".to_string())
561}
562
563/// Receives a vault job.
564pub fn receive_vault_job(
565    job_id: String,
566    task_type: String,
567    _data_blob_cbor_ld: Vec<u8>,
568) -> Result<String, String> {
569    println!("[VC-12] Offload job {} type {}", job_id, task_type);
570    if task_type == "LLM_INFERENCE" && check_ollama_status() {
571        Ok("INFERENCE_QUEUED".to_string())
572    } else {
573        Err("UNSUPPORTED_TASK_OR_NO_CAPACITY".to_string())
574    }
575}
576
577/// Ingests a PDF.
578pub async fn ingest_pdf(file_name: String) -> Result<ingestion::IngestionResult, String> {
579    let result = ingestion::process_pdf(&file_name)?;
580    q42_compiler::compile_to_q42(&file_name, &result.bookmarks)?;
581    Ok(result)
582}
583
584/// Ingests literature.
585pub async fn ingest_literature(file_path: String) -> Result<String, String> {
586    let state = crate::state::APP_STATE.get().unwrap();
587    let storage_path = state.config.lock().unwrap().storage_path.clone();
588    let lib_dir = PathBuf::from(&storage_path).join("SemanticLibrary");
589    if !lib_dir.exists() {
590        std::fs::create_dir_all(&lib_dir).map_err(|e| e.to_string())?;
591    }
592
593    let source_path = std::path::Path::new(&file_path);
594    let filename = source_path.file_name().unwrap_or_default();
595    let dest_path = lib_dir.join(filename);
596    std::fs::copy(&source_path, &dest_path).map_err(|e| e.to_string())?;
597
598    let text = pdf_extract::extract_text(&dest_path).map_err(|e| e.to_string())?;
599    let preview = if text.len() > 100 {
600        &text[0..100]
601    } else {
602        &text
603    };
604
605    Ok(format!(
606        "Successfully ingested literature: {}. Generated ontology nodes from preview: '{}...'",
607        filename.to_string_lossy(),
608        preview.replace("\n", " ")
609    ))
610}
611
612/// Upserts a CMLD definition.
613pub async fn upsert_cmld_definition(term: String, context_did: String) -> Result<String, String> {
614    Ok(format!(
615        "Successfully mapped '{}' to Context: {}",
616        term, context_did
617    ))
618}
619
620/// Ingests an ontology.
621pub async fn ingest_ontology(file_name: String) -> Result<serde_json::Value, String> {
622    let state = crate::state::APP_STATE.get().unwrap();
623    let storage_path = state.config.lock().unwrap().storage_path.clone();
624    let index_dir = PathBuf::from(&storage_path).join("Index");
625    // Desktop file pickers yield an absolute local path, while existing CLI
626    // callers pass a filename already staged in Index/. Support both without
627    // introducing a network fetch or widening the importer beyond local files.
628    let requested_path = PathBuf::from(&file_name);
629    let source_path = if requested_path.is_file() {
630        requested_path
631    } else {
632        index_dir.join(&file_name)
633    };
634
635    if !source_path.is_file() {
636        return Err(format!(
637            "Ontology source not found in Index/: {}",
638            source_path.display()
639        ));
640    }
641
642    let ontology_id = source_path
643        .file_stem()
644        .and_then(|s| s.to_str())
645        .unwrap_or(&file_name)
646        .to_string();
647
648    let cancelled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
649    state
650        .download_handles
651        .lock()
652        .unwrap()
653        .insert(ontology_id.clone(), cancelled);
654    let progress = crate::resource_import::ImportProgressCtx {
655        id: ontology_id.clone(),
656        handles: state.download_handles.clone(),
657        active_downloads: state.active_downloads.clone(),
658        download_events: state.download_events.clone(),
659    };
660    let quin_count = crate::resource_import::ingest_local_rdf_with_progress(
661        &source_path,
662        &ontology_id,
663        Path::new(&storage_path),
664        None,
665        Some(&progress),
666    )
667    .map_err(|e| e.to_string())?;
668    progress.clear();
669
670    let q42_path = index_dir.join(format!("{ontology_id}.q42"));
671
672    Ok(serde_json::json!({
673        "status": "success",
674        "file": file_name,
675        "ontology_id": ontology_id,
676        "q42_path": q42_path.to_string_lossy(),
677        "quin_count": quin_count,
678    }))
679}
680
681/// Imports a catalog ontology.
682pub async fn import_catalog_ontology(id: String) -> Result<serde_json::Value, String> {
683    let state = crate::state::APP_STATE.get().unwrap();
684    let storage_path = state.config.lock().unwrap().storage_path.clone();
685    let catalog = load_workspace_catalog();
686
687    let cancelled = Arc::new(AtomicBool::new(false));
688    state
689        .download_handles
690        .lock()
691        .unwrap()
692        .insert(id.clone(), cancelled.clone());
693
694    let progress = crate::resource_import::ImportProgressCtx {
695        id: id.clone(),
696        handles: state.download_handles.clone(),
697        active_downloads: state.active_downloads.clone(),
698        download_events: state.download_events.clone(),
699    };
700
701    let result = crate::resource_import::import_catalog_ontology_with_options(
702        &catalog,
703        &id,
704        Path::new(&storage_path),
705        Some(&progress),
706        true,
707    )
708    .await
709    .map_err(|e| {
710        state.download_handles.lock().unwrap().remove(&id);
711        state.active_downloads.lock().unwrap().remove(&id);
712        e.to_string()
713    })?;
714
715    qualia_core_db::daemon_graph::init_daemon_graph(&storage_path);
716
717    serde_json::to_value(result).map_err(|e| e.to_string())
718}
719
720/// Exports to Solid.
721pub async fn export_to_solid(
722    input_q42_path: String,
723    output_dir_path: String,
724) -> Result<String, String> {
725    qualia_core_db::solid_ldp::SolidExporter::export_to_solid_pod(&input_q42_path, &output_dir_path)
726        .map(|_| format!("Exported to {}", output_dir_path))
727        .map_err(|e| e.to_string())
728}
729
730/// Consumer: fetch a Solid LDP resource and return status + Turtle body + Quin count.
731pub async fn fetch_from_solid_pod(
732    url: String,
733    bearer_token: Option<String>,
734) -> Result<serde_json::Value, String> {
735    let r = qualia_solid_bridge::fetch_resource(&url, bearer_token.as_deref())
736        .await
737        .map_err(|e| e.to_string())?;
738    Ok(serde_json::json!({
739        "url": r.url,
740        "status": r.status,
741        "content_type": r.content_type,
742        "quin_count": r.quin_count,
743        "body": r.body,
744    }))
745}
746
747/// Consumer: PUT a local Turtle/file to a Solid resource URL (sync-to-pod).
748pub async fn put_to_solid_pod(
749    url: String,
750    body: Vec<u8>,
751    content_type: Option<String>,
752    bearer_token: Option<String>,
753) -> Result<serde_json::Value, String> {
754    let ct = content_type.unwrap_or_else(|| "text/turtle".into());
755    let status = qualia_solid_bridge::put_resource(&url, &body, &ct, bearer_token.as_deref())
756        .await
757        .map_err(|e| e.to_string())?;
758    Ok(serde_json::json!({ "ok": true, "status": status, "url": url }))
759}
760
761/// Sync: if `body_or_path` is a path to an existing file, upload it; else treat as Turtle body.
762pub async fn sync_to_solid_pod(
763    pod_url: String,
764    body_or_path: Option<String>,
765    bearer_token: Option<String>,
766) -> Result<String, String> {
767    let (bytes, ct) = if let Some(ref p) = body_or_path {
768        let path = std::path::Path::new(p);
769        if path.is_file() {
770            let b = std::fs::read(path).map_err(|e| e.to_string())?;
771            let ct = if p.ends_with(".json") || p.ends_with(".jsonld") {
772                "application/ld+json"
773            } else {
774                "text/turtle"
775            };
776            (b, ct.to_string())
777        } else {
778            (p.as_bytes().to_vec(), "text/turtle".into())
779        }
780    } else {
781        // Minimal deposit marker when UI only passes a URL
782        let body = format!(
783            "@prefix dcterms: <http://purl.org/dc/terms/> .\n<> dcterms:description \"Qualia sync {}\" .\n",
784            chrono::Utc::now().to_rfc3339()
785        );
786        (body.into_bytes(), "text/turtle".into())
787    };
788    let status = qualia_solid_bridge::put_resource(&pod_url, &bytes, &ct, bearer_token.as_deref())
789        .await
790        .map_err(|e| e.to_string())?;
791    Ok(format!(
792        "Synced to Solid Pod {pod_url} (HTTP {status}, {} bytes)",
793        bytes.len()
794    ))
795}
796
797/// Ingests an image.
798pub async fn ingest_image(file_path: String) -> Result<serde_json::Value, String> {
799    ingest_image_typed(file_path, "Generic Asset".to_string()).await
800}
801
802/// Ingests a typed image.
803pub async fn ingest_image_typed(
804    file_path: String,
805    typology: String,
806) -> Result<serde_json::Value, String> {
807    let state = crate::state::APP_STATE.get().unwrap();
808    let storage = state.config.lock().unwrap().storage_path.clone();
809    let active = load_active_model_record_from_disk();
810    let result = crate::vision_ingest::ingest_image_with_active_record(
811        Path::new(&storage),
812        active,
813        Path::new(&file_path),
814        &typology,
815    )
816    .map_err(|e| e.to_string())?;
817    serde_json::to_value(result).map_err(|e| e.to_string())
818}
819
820/// Ingests an image (async).
821pub async fn ingest_image_async(file_path: String, typology: String) -> Result<(), String> {
822    let state = crate::state::APP_STATE.get().unwrap();
823    let storage = state.config.lock().unwrap().storage_path.clone();
824    let active = load_active_model_record_from_disk();
825    tokio::spawn(async move {
826        let _ = crate::vision_ingest::ingest_image_with_active_record(
827            Path::new(&storage),
828            active,
829            Path::new(&file_path),
830            &typology,
831        );
832    });
833    Ok(())
834}