1use crate::qpu_dispatcher::{self, QpuDispatchResult};
4use crate::qpu_oracle::{self, QpuChatCommandResult};
5use qualia_core_db::qubo_compiler::{compile_quins_to_qubo, rehydrate_solution, QuboMatrix};
6use qualia_core_db::NQuin;
7
8pub const MAX_REHYDRATED: usize = 64;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum QuantumTaskKind {
12 QuboRouting,
13 DftGroundState,
14 DefeasibleResolution,
15}
16
17pub struct QuantumPipelineResult {
18 pub task: QuantumTaskKind,
19 pub dispatch: QpuDispatchResult,
20 pub rehydrated: Vec<NQuin>,
21 pub summary: String,
22}
23
24pub fn detect_task_from_prompt(prompt: &str) -> Option<QuantumTaskKind> {
26 let lower = prompt.to_lowercase();
27 if lower.contains("[qpu:qubo]") {
28 return Some(QuantumTaskKind::QuboRouting);
29 }
30 if lower.contains("[qpu:dft]") {
31 return Some(QuantumTaskKind::DftGroundState);
32 }
33 if lower.contains("[qpu:defeasible]") {
34 return Some(QuantumTaskKind::DefeasibleResolution);
35 }
36 if prompt.contains(r"$$") {
37 if prompt.contains(r"\min") || prompt.contains("QUBO") {
38 return Some(QuantumTaskKind::QuboRouting);
39 }
40 if prompt.contains(r"\hat{H}")
41 || prompt.contains(r"\Psi")
42 || prompt.contains(r"\hat{h}")
43 || prompt.contains("ground state")
44 {
45 return Some(QuantumTaskKind::DftGroundState);
46 }
47 }
48 None
49}
50
51pub fn execute_quantum_pipeline(
53 task: QuantumTaskKind,
54 quins: &[NQuin],
55 latex_hint: Option<&str>,
56) -> Result<QuantumPipelineResult, String> {
57 if !qpu_oracle::is_qpu_feature_unlocked() {
58 return Err("QPU Oracle not unlocked. Type [enable_QPU] in Chat first.".into());
59 }
60
61 let settings = qpu_oracle::get_qpu_settings();
62 let shots = settings.max_shots_per_task;
63
64 match task {
65 QuantumTaskKind::QuboRouting => {
66 let mut matrix = QuboMatrix::default();
67 compile_quins_to_qubo(quins, &mut matrix)
68 .map_err(|e| format!("QUBO compile blocked: {e:?}"))?;
69 if matrix.num_vars == 0 {
70 build_demo_qubo(&mut matrix, latex_hint);
71 }
72 let dispatch = qpu_dispatcher::dispatch_qubo(&matrix, shots)?;
73 let mut out = [NQuin {
74 subject: 0,
75 predicate: 0,
76 object: 0,
77 context: 0,
78 metadata: 0,
79 parity: 0,
80 }; MAX_REHYDRATED];
81 let n = rehydrate_solution(&mut matrix, &dispatch.assignment, &mut out);
82 let summary = format!(
83 "⚛️ **QUBO routing complete** ({})\n\n\
84 - Variables: {}\n\
85 - Ground energy: {:.4}\n\
86 - Remote QPU: {}\n\
87 - Re-hydrated assertions: {}\n\n\
88 Ephemeral index map wiped. No semantic context left the device.",
89 dispatch.backend, dispatch.num_vars, dispatch.energy, dispatch.used_remote, n
90 );
91 Ok(QuantumPipelineResult {
92 task,
93 dispatch,
94 rehydrated: out[..n].to_vec(),
95 summary,
96 })
97 }
98 QuantumTaskKind::DftGroundState => {
99 let params = extract_vqe_params(latex_hint.unwrap_or(""));
100 let dispatch = qpu_dispatcher::dispatch_vqe(¶ms, shots)?;
101 let summary = format!(
102 "⚛️ **DFT / VQE ground-state** ({})\n\n\
103 - Parameter vector dim: {}\n\
104 - Estimated energy: {:.4} eV\n\
105 - Remote QPU: {}\n\n\
106 Local Core 2 prepared the Hamiltonian; only parameter amplitudes egressed.",
107 dispatch.backend,
108 params.len(),
109 dispatch.energy,
110 dispatch.used_remote
111 );
112 Ok(QuantumPipelineResult {
113 task,
114 dispatch,
115 rehydrated: vec![],
116 summary,
117 })
118 }
119 QuantumTaskKind::DefeasibleResolution => {
120 let mut matrix = QuboMatrix::default();
121 compile_quins_to_qubo(quins, &mut matrix)
122 .map_err(|e| format!("Defeasible QUBO blocked: {e:?}"))?;
123 if matrix.num_vars == 0 {
124 build_defeasible_demo(&mut matrix);
125 }
126 let dispatch = qpu_dispatcher::dispatch_qubo(&matrix, shots)?;
127 let summary = format!(
128 "⚛️ **Defeasible resolution** via probabilistic QUBO ({})\n\
129 Energy: {:.4} | Remote: {}",
130 dispatch.backend, dispatch.energy, dispatch.used_remote
131 );
132 Ok(QuantumPipelineResult {
133 task,
134 dispatch,
135 rehydrated: vec![],
136 summary,
137 })
138 }
139 }
140}
141
142fn build_demo_qubo(matrix: &mut QuboMatrix, hint: Option<&str>) {
143 let _ = hint;
144 matrix.num_vars = 3;
145 matrix.linear[0] = -1.0;
146 matrix.linear[1] = -0.5;
147 matrix.linear[2] = -2.0;
148 let _ = matrix.emit_coupler(0, 1, 1.5);
149 let _ = matrix.emit_coupler(1, 2, 0.8);
150 matrix.index_map[0] = (0xA001, 0);
151 matrix.index_map[1] = (0xA002, 1);
152 matrix.index_map[2] = (0xA003, 2);
153 matrix.index_count = 3;
154}
155
156fn build_defeasible_demo(matrix: &mut QuboMatrix) {
157 matrix.num_vars = 2;
158 matrix.linear[0] = -1.0;
159 matrix.linear[1] = -1.0;
160 let _ = matrix.emit_coupler(0, 1, 3.0);
161 matrix.index_count = 2;
162 matrix.index_map[0] = (0xD001, 0);
163 matrix.index_map[1] = (0xD002, 1);
164}
165
166pub fn handle_engine_chat_command(text: &str) -> QpuChatCommandResult {
168 use crate::qpu_oracle::{handle_qpu_chat_command, QpuChatCommandResult};
169
170 let unlock = handle_qpu_chat_command(text);
171 if unlock.handled {
172 return unlock;
173 }
174
175 let task = detect_task_from_prompt(text);
176 if let Some(kind) = task {
177 if !qpu_oracle::is_qpu_feature_unlocked() {
178 return QpuChatCommandResult {
179 handled: true,
180 feature_unlocked: false,
181 response: "⚛️ Quantum task detected but QPU Oracle is locked. \
182 Type `[enable_QPU]` first, then configure API keys in Settings."
183 .to_string(),
184 };
185 }
186 let quins: Vec<NQuin> = vec![];
187 let latex = if text.contains(r"$$") {
188 Some(text)
189 } else {
190 None
191 };
192 match execute_quantum_pipeline(kind, &quins, latex) {
193 Ok(result) => QpuChatCommandResult {
194 handled: true,
195 feature_unlocked: true,
196 response: result.summary,
197 },
198 Err(e) => QpuChatCommandResult {
199 handled: true,
200 feature_unlocked: true,
201 response: format!("🔴 Quantum pipeline failed: {e}"),
202 },
203 }
204 } else {
205 QpuChatCommandResult {
206 handled: false,
207 response: String::new(),
208 feature_unlocked: qpu_oracle::is_qpu_feature_unlocked(),
209 }
210 }
211}
212
213fn extract_vqe_params(latex: &str) -> Vec<f64> {
214 let mut params = Vec::new();
215 for token in latex.split(|c: char| !c.is_ascii_digit() && c != '.' && c != '-') {
216 if let Ok(v) = token.parse::<f64>() {
217 if token.contains('.') || v.abs() > 0.0 {
218 params.push(v);
219 }
220 }
221 }
222 if params.is_empty() {
223 params.extend_from_slice(&[0.1, 0.2, -0.15, 0.05]);
224 }
225 params.truncate(16);
226 params
227}