1use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::path::Path;
9
10const CONFIG_FILE: &str = "qpu_config.json";
11
12struct ProviderInfo {
15 id: &'static str,
16 name: &'static str,
17 problem_types: &'static str,
18 required: &'static [&'static str],
19 optional: &'static [&'static str],
20 docs: &'static str,
21}
22
23const PROVIDERS: &[ProviderInfo] = &[
24 ProviderInfo {
25 id: "ibm",
26 name: "IBM Quantum",
27 problem_types: "gate-model, vqe, qaoa",
28 required: &["api_key"],
29 optional: &["hub", "group", "project", "instance", "endpoint"],
30 docs: "https://quantum.ibm.com — get token from Account Settings",
31 },
32 ProviderInfo {
33 id: "dwave",
34 name: "D-Wave Leap",
35 problem_types: "annealing (QUBO)",
36 required: &["api_key"],
37 optional: &["endpoint", "solver"],
38 docs: "https://cloud.dwavesys.com/leap — get token from Dashboard > API Token",
39 },
40 ProviderInfo {
41 id: "ionq",
42 name: "IonQ",
43 problem_types: "gate-model",
44 required: &["api_key"],
45 optional: &["backend", "endpoint"],
46 docs: "https://cloud.ionq.com — get key from API Keys section",
47 },
48 ProviderInfo {
49 id: "rigetti",
50 name: "Rigetti QCS",
51 problem_types: "gate-model, vqe, qaoa",
52 required: &["api_key", "user_id"],
53 optional: &["qpu_id", "endpoint"],
54 docs: "https://qcs.rigetti.com — get credentials from QCS Settings",
55 },
56 ProviderInfo {
57 id: "azure",
58 name: "Azure Quantum",
59 problem_types: "gate-model, annealing, vqe, qaoa",
60 required: &["subscription_id", "resource_group", "workspace", "location"],
61 optional: &["api_key", "endpoint"],
62 docs: "https://portal.azure.com — create Azure Quantum workspace",
63 },
64 ProviderInfo {
65 id: "braket",
66 name: "AWS Braket",
67 problem_types: "gate-model, annealing",
68 required: &["access_key_id", "secret_access_key", "region"],
69 optional: &["s3_bucket", "endpoint"],
70 docs: "https://aws.amazon.com/braket — use IAM credentials with AmazonBraketFullAccess",
71 },
72 ProviderInfo {
73 id: "google",
74 name: "Google Quantum AI",
75 problem_types: "gate-model",
76 required: &["project_id", "processor_id"],
77 optional: &["service_account_key_path", "endpoint"],
78 docs:
79 "https://quantumai.google — requires Cloud project with Quantum Computing Service API",
80 },
81 ProviderInfo {
82 id: "quantinuum",
83 name: "Quantinuum",
84 problem_types: "gate-model",
85 required: &["api_key"],
86 optional: &["machine", "endpoint"],
87 docs: "https://um.qapi.quantinuum.com — get credentials from Quantinuum account portal",
88 },
89];
90
91fn find_provider(id: &str) -> Option<&'static ProviderInfo> {
92 PROVIDERS.iter().find(|p| p.id == id)
93}
94
95#[derive(Debug, Clone, Default, Serialize, Deserialize)]
98pub struct ProviderConfig {
99 pub api_key: Option<String>,
101 pub endpoint: Option<String>,
102 pub hub: Option<String>,
104 pub group: Option<String>,
105 pub project: Option<String>,
106 pub instance: Option<String>,
107 pub subscription_id: Option<String>,
109 pub resource_group: Option<String>,
110 pub workspace: Option<String>,
111 pub location: Option<String>,
112 pub access_key_id: Option<String>,
114 pub secret_access_key: Option<String>,
115 pub region: Option<String>,
116 pub s3_bucket: Option<String>,
117 pub project_id: Option<String>,
119 pub processor_id: Option<String>,
120 pub service_account_key_path: Option<String>,
121 pub user_id: Option<String>,
123 pub qpu_id: Option<String>,
124 pub backend: Option<String>,
126 pub machine: Option<String>,
128}
129
130#[derive(Debug, Default, Serialize, Deserialize)]
131pub struct QpuConfigStore {
132 pub providers: HashMap<String, ProviderConfig>,
133}
134
135fn config_path(data_dir: &str) -> std::path::PathBuf {
138 Path::new(data_dir).join(CONFIG_FILE)
139}
140
141pub fn load_config(data_dir: &str) -> QpuConfigStore {
143 let path = config_path(data_dir);
144 if !path.exists() {
145 return QpuConfigStore::default();
146 }
147 match std::fs::read_to_string(&path) {
148 Ok(s) => serde_json::from_str(&s).unwrap_or_default(),
149 Err(_) => QpuConfigStore::default(),
150 }
151}
152
153fn save_config(data_dir: &str, store: &QpuConfigStore) {
154 let path = config_path(data_dir);
155 if let Some(parent) = path.parent() {
156 let _ = std::fs::create_dir_all(parent);
157 }
158 match serde_json::to_string_pretty(store) {
159 Ok(s) => {
160 if let Err(e) = std::fs::write(&path, &s) {
161 eprintln!("QPU config write error: {e}");
162 } else {
163 println!("Config saved to: {}", path.display());
164 println!(
165 "Note: API keys are stored in plaintext — restrict file permissions if needed."
166 );
167 }
168 }
169 Err(e) => eprintln!("QPU config serialize error: {e}"),
170 }
171}
172
173fn mask(s: &str) -> String {
176 if s.len() <= 8 {
177 return "*".repeat(s.len());
178 }
179 format!("{}...{}", &s[..4], &s[s.len() - 4..])
180}
181
182fn display_opt(v: &Option<String>, sensitive: bool) -> String {
183 match v {
184 None => "(not set)".into(),
185 Some(s) if s.is_empty() => "(empty)".into(),
186 Some(s) if sensitive => mask(s),
187 Some(s) => s.clone(),
188 }
189}
190
191pub fn run_list_providers() {
195 println!("================================================================");
196 println!(
197 " QualiaDB QPU — Supported Providers ({} total)",
198 PROVIDERS.len()
199 );
200 println!("================================================================");
201 for p in PROVIDERS {
202 println!("\n [{id}] {name}", id = p.id, name = p.name);
203 println!(" Problem types : {}", p.problem_types);
204 println!(" Required : {}", p.required.join(", "));
205 if !p.optional.is_empty() {
206 println!(" Optional : {}", p.optional.join(", "));
207 }
208 println!(" Docs : {}", p.docs);
209 }
210 println!("\n================================================================");
211 println!("Configure with:");
212 println!(" qualia-cli --enable-qpu qpu configure <provider-id> --api-key <key> [...]");
213 println!("================================================================");
214}
215
216#[allow(clippy::too_many_arguments)]
217pub fn run_configure(
219 data_dir: &str,
220 provider: &str,
221 api_key: Option<&str>,
222 endpoint: Option<&str>,
223 hub: Option<&str>,
224 group: Option<&str>,
225 project: Option<&str>,
226 instance: Option<&str>,
227 subscription_id: Option<&str>,
228 resource_group: Option<&str>,
229 workspace: Option<&str>,
230 location: Option<&str>,
231 access_key_id: Option<&str>,
232 secret_access_key: Option<&str>,
233 region: Option<&str>,
234 s3_bucket: Option<&str>,
235 project_id: Option<&str>,
236 processor_id: Option<&str>,
237 service_account_key_path: Option<&str>,
238 user_id: Option<&str>,
239 qpu_id: Option<&str>,
240 backend: Option<&str>,
241 machine: Option<&str>,
242) {
243 let Some(info) = find_provider(provider) else {
244 eprintln!(
245 "Unknown provider '{}'. Run `qpu list-providers` to see valid IDs.",
246 provider
247 );
248 return;
249 };
250
251 let mut store = load_config(data_dir);
252 let cfg = store.providers.entry(provider.to_string()).or_default();
253
254 macro_rules! apply {
256 ($field:ident, $val:expr) => {
257 if let Some(v) = $val {
258 cfg.$field = Some(v.to_string());
259 }
260 };
261 }
262
263 apply!(api_key, api_key);
264 apply!(endpoint, endpoint);
265 apply!(hub, hub);
266 apply!(group, group);
267 apply!(project, project);
268 apply!(instance, instance);
269 apply!(subscription_id, subscription_id);
270 apply!(resource_group, resource_group);
271 apply!(workspace, workspace);
272 apply!(location, location);
273 apply!(access_key_id, access_key_id);
274 apply!(secret_access_key, secret_access_key);
275 apply!(region, region);
276 apply!(s3_bucket, s3_bucket);
277 apply!(project_id, project_id);
278 apply!(processor_id, processor_id);
279 apply!(service_account_key_path, service_account_key_path);
280 apply!(user_id, user_id);
281 apply!(qpu_id, qpu_id);
282 apply!(backend, backend);
283 apply!(machine, machine);
284
285 let missing: Vec<&str> = info
287 .required
288 .iter()
289 .copied()
290 .filter(|&field| match field {
291 "api_key" => cfg.api_key.is_none(),
292 "subscription_id" => cfg.subscription_id.is_none(),
293 "resource_group" => cfg.resource_group.is_none(),
294 "workspace" => cfg.workspace.is_none(),
295 "location" => cfg.location.is_none(),
296 "access_key_id" => cfg.access_key_id.is_none(),
297 "secret_access_key" => cfg.secret_access_key.is_none(),
298 "region" => cfg.region.is_none(),
299 "project_id" => cfg.project_id.is_none(),
300 "processor_id" => cfg.processor_id.is_none(),
301 "user_id" => cfg.user_id.is_none(),
302 _ => false,
303 })
304 .collect();
305
306 println!("================================================================");
307 println!(" QPU Configure — {}", info.name);
308 println!("================================================================");
309
310 save_config(data_dir, &store);
311
312 if !missing.is_empty() {
313 println!("\nWarning: the following required fields are still not set:");
314 for f in &missing {
315 println!(" --{}", f.replace('_', "-"));
316 }
317 println!(
318 "Run `qpu test-connection {}` after supplying all required fields.",
319 provider
320 );
321 } else {
322 println!("All required fields set for {}.", info.name);
323 println!(
324 "Run `qualia-cli --enable-qpu qpu test-connection {}` to validate.",
325 provider
326 );
327 }
328}
329
330pub fn run_show(data_dir: &str, provider: Option<&str>) {
332 let store = load_config(data_dir);
333
334 let entries: Vec<(&str, &ProviderConfig)> = match provider {
335 Some(id) => {
336 if let Some(cfg) = store.providers.get(id) {
337 vec![(id, cfg)]
338 } else {
339 println!("Provider '{}' has no stored configuration.", id);
340 return;
341 }
342 }
343 None => store
344 .providers
345 .iter()
346 .map(|(k, v)| (k.as_str(), v))
347 .collect(),
348 };
349
350 if entries.is_empty() {
351 println!("No QPU providers configured.");
352 println!("Run: qualia-cli --enable-qpu qpu list-providers");
353 return;
354 }
355
356 println!("================================================================");
357 println!(" QPU Configuration (API keys masked)");
358 println!("================================================================");
359
360 for (id, cfg) in &entries {
361 let name = find_provider(id).map(|p| p.name).unwrap_or(id);
362 println!("\n [{id}] {name}");
363 println!(
364 " api_key : {}",
365 display_opt(&cfg.api_key, true)
366 );
367 println!(
368 " endpoint : {}",
369 display_opt(&cfg.endpoint, false)
370 );
371 if cfg.hub.is_some()
373 || cfg.group.is_some()
374 || cfg.project.is_some()
375 || cfg.instance.is_some()
376 {
377 println!(
378 " hub / group / project: {} / {} / {}",
379 display_opt(&cfg.hub, false),
380 display_opt(&cfg.group, false),
381 display_opt(&cfg.project, false)
382 );
383 println!(
384 " instance : {}",
385 display_opt(&cfg.instance, false)
386 );
387 }
388 if cfg.subscription_id.is_some() {
390 println!(
391 " subscription_id : {}",
392 display_opt(&cfg.subscription_id, true)
393 );
394 println!(
395 " resource_group : {}",
396 display_opt(&cfg.resource_group, false)
397 );
398 println!(
399 " workspace : {}",
400 display_opt(&cfg.workspace, false)
401 );
402 println!(
403 " location : {}",
404 display_opt(&cfg.location, false)
405 );
406 }
407 if cfg.access_key_id.is_some() {
409 println!(
410 " access_key_id : {}",
411 display_opt(&cfg.access_key_id, true)
412 );
413 println!(
414 " secret_access_key : {}",
415 display_opt(&cfg.secret_access_key, true)
416 );
417 println!(
418 " region : {}",
419 display_opt(&cfg.region, false)
420 );
421 println!(
422 " s3_bucket : {}",
423 display_opt(&cfg.s3_bucket, false)
424 );
425 }
426 if cfg.project_id.is_some() {
428 println!(
429 " project_id : {}",
430 display_opt(&cfg.project_id, false)
431 );
432 println!(
433 " processor_id : {}",
434 display_opt(&cfg.processor_id, false)
435 );
436 println!(
437 " service_account_key : {}",
438 display_opt(&cfg.service_account_key_path, false)
439 );
440 }
441 if cfg.user_id.is_some() || cfg.qpu_id.is_some() {
443 println!(
444 " user_id : {}",
445 display_opt(&cfg.user_id, false)
446 );
447 println!(
448 " qpu_id : {}",
449 display_opt(&cfg.qpu_id, false)
450 );
451 }
452 if cfg.backend.is_some() {
454 println!(
455 " backend : {}",
456 display_opt(&cfg.backend, false)
457 );
458 }
459 if cfg.machine.is_some() {
461 println!(
462 " machine : {}",
463 display_opt(&cfg.machine, false)
464 );
465 }
466 }
467 println!("\n================================================================");
468}
469
470pub fn run_clear(data_dir: &str, provider: &str) {
472 if find_provider(provider).is_none() {
473 eprintln!(
474 "Unknown provider '{}'. Run `qpu list-providers` to see valid IDs.",
475 provider
476 );
477 return;
478 }
479 let mut store = load_config(data_dir);
480 if store.providers.remove(provider).is_some() {
481 save_config(data_dir, &store);
482 println!("Cleared credentials for '{}'.", provider);
483 } else {
484 println!(
485 "No stored credentials for '{}' — nothing to clear.",
486 provider
487 );
488 }
489}
490
491pub fn run_test_connection(data_dir: &str, provider: &str) {
493 let Some(info) = find_provider(provider) else {
494 eprintln!(
495 "Unknown provider '{}'. Run `qpu list-providers` to see valid IDs.",
496 provider
497 );
498 return;
499 };
500
501 let store = load_config(data_dir);
502 let Some(cfg) = store.providers.get(provider) else {
503 eprintln!(
504 "No credentials stored for '{}'. Run `qpu configure {}` first.",
505 provider, provider
506 );
507 return;
508 };
509
510 println!("================================================================");
511 println!(" QPU Test Connection — {}", info.name);
512 println!("================================================================");
513
514 let missing: Vec<&str> = info
516 .required
517 .iter()
518 .copied()
519 .filter(|&field| match field {
520 "api_key" => cfg.api_key.is_none(),
521 "subscription_id" => cfg.subscription_id.is_none(),
522 "resource_group" => cfg.resource_group.is_none(),
523 "workspace" => cfg.workspace.is_none(),
524 "location" => cfg.location.is_none(),
525 "access_key_id" => cfg.access_key_id.is_none(),
526 "secret_access_key" => cfg.secret_access_key.is_none(),
527 "region" => cfg.region.is_none(),
528 "project_id" => cfg.project_id.is_none(),
529 "processor_id" => cfg.processor_id.is_none(),
530 "user_id" => cfg.user_id.is_none(),
531 _ => false,
532 })
533 .collect();
534
535 if !missing.is_empty() {
536 eprintln!("Missing required fields: {}", missing.join(", "));
537 eprintln!(
538 "Run: qualia-cli --enable-qpu qpu configure {} [--field value ...]",
539 provider
540 );
541 return;
542 }
543
544 let endpoint = match provider {
546 "ibm" => "https://auth.quantum-computing.ibm.com/api",
547 "dwave" => cfg
548 .endpoint
549 .as_deref()
550 .unwrap_or("https://cloud.dwavesys.com/sapi/v2"),
551 "ionq" => cfg
552 .endpoint
553 .as_deref()
554 .unwrap_or("https://api.ionq.co/v0.3"),
555 "rigetti" => cfg
556 .endpoint
557 .as_deref()
558 .unwrap_or("https://api.qcs.rigetti.com"),
559 "azure" => "https://eastus.quantum.azure.com",
560 "braket" => "https://braket.{region}.amazonaws.com (via AWS SDK)",
561 "google" => "https://quantum.googleapis.com",
562 "quantinuum" => cfg
563 .endpoint
564 .as_deref()
565 .unwrap_or("https://um.qapi.quantinuum.com"),
566 _ => "(unknown)",
567 };
568
569 println!(" Provider : {}", info.name);
570 println!(" Endpoint : {}", endpoint);
571 println!(" Auth type : {}", auth_type_for(provider));
572 println!();
573 println!(" Credentials : present (format not yet validated by local check)");
574 println!(" Status : Configuration looks complete — live connectivity");
575 println!(" test requires network access and valid credentials.");
576 println!();
577 println!(" To submit a test job:");
578 println!(
579 " qualia-cli --enable-qpu qpu submit {} --problem-type annealing --qubits 4",
580 provider
581 );
582 println!("================================================================");
583}
584
585fn auth_type_for(provider: &str) -> &'static str {
586 match provider {
587 "ibm" => "IBM token (Authorization: Bearer <api_key>)",
588 "dwave" => "Leap token (X-Auth-Token: <api_key>)",
589 "ionq" => "IonQ API key (Authorization: apiKey <api_key>)",
590 "rigetti" => "QCS credentials (api_key + user_id)",
591 "azure" => "Azure AD service principal (subscription_id / workspace)",
592 "braket" => "AWS SigV4 (access_key_id + secret_access_key)",
593 "google" => "Google service account JSON / Application Default Credentials",
594 "quantinuum" => "Quantinuum bearer token (api_key)",
595 _ => "API key",
596 }
597}
598
599pub fn run_submit(data_dir: &str, provider: &str, problem_type: &str, qubits: u32, shots: u32) {
601 let Some(info) = find_provider(provider) else {
602 eprintln!(
603 "Unknown provider '{}'. Run `qpu list-providers` to see valid IDs.",
604 provider
605 );
606 return;
607 };
608
609 let store = load_config(data_dir);
610 if store.providers.get(provider).is_none() {
611 eprintln!(
612 "No credentials for '{}'. Run `qpu configure {}` first.",
613 provider, provider
614 );
615 return;
616 }
617
618 use qualia_core_db::solvers::qpu::{JobParameters, ProblemType, QpuJob};
619
620 let pt = match problem_type {
621 "annealing" => ProblemType::Annealing,
622 "gate-model" => ProblemType::GateModel,
623 "vqe" => ProblemType::Vqe,
624 "qaoa" => ProblemType::Qaoa,
625 other => {
626 eprintln!(
627 "Unknown problem type '{}'. Use: annealing | gate-model | vqe | qaoa",
628 other
629 );
630 return;
631 }
632 };
633
634 let job_id = format!(
635 "q-{}-{}",
636 provider,
637 std::time::SystemTime::now()
638 .duration_since(std::time::UNIX_EPOCH)
639 .map(|d| d.as_millis())
640 .unwrap_or(0)
641 );
642
643 let job = QpuJob::new(
644 job_id.clone(),
645 pt,
646 JobParameters {
647 num_qubits: qubits,
648 circuit_depth: 0,
649 shots,
650 hamiltonian: Some(r#"{"J":{},"h":{}}"#.into()),
651 circuit: None,
652 extra: serde_json::json!({"provider": provider, "cli_submit": true}),
653 },
654 );
655
656 println!("================================================================");
657 println!(" QPU Job Submission — {}", info.name);
658 println!("================================================================");
659 println!(" Job ID : {}", job_id);
660 println!(" Provider : {} ({})", info.name, provider);
661 println!(" Problem type : {}", problem_type);
662 println!(" Qubits : {}", qubits);
663 println!(" Shots : {}", shots);
664 println!();
665
666 use qualia_core_db::solvers::qpu::dispatcher::FallbackHandler;
669 let handler = FallbackHandler::new(true);
670 match handler.simulate_classically(&job) {
671 Ok(result) => {
672 println!(" Status : {:?}", result.status);
673 if let Some(data) = &result.result {
674 println!(" Energies : {:?}", data.energies);
675 println!(" Measurements : {} sample(s)", data.measurements.len());
676 println!(" Metadata : {}", data.metadata);
677 }
678 println!();
679 println!(" Note: This is a local classical simulation. To dispatch to the");
680 println!(" live {} endpoint, start the Qualia daemon:", info.name);
681 println!(" qualia-cli daemon --dev");
682 println!(" The daemon's QPU oracle handles live HTTP egress via");
683 println!(" qualia-client-core::qpu_dispatcher.");
684 }
685 Err(e) => eprintln!("Simulation error: {e}"),
686 }
687 println!("================================================================");
688}