quelch 0.9.2

Ingest data from Jira, Confluence, and more directly into Azure AI Search
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
/// Interactive prompt sections for `quelch init`.
///
/// Each `*_section` function drives one section of the wizard and returns
/// the corresponding config struct. Credential testing is best-effort:
/// if a test fails the user is warned but not blocked.
use crate::config::*;

use super::discover;
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Azure section
// ---------------------------------------------------------------------------

/// Prompt for Azure subscription, resource group, and region.
pub async fn azure_section() -> anyhow::Result<AzureConfig> {
    println!("\n=== Azure resources ===");
    println!("Discovering Azure subscriptions...");

    let subs = discover::list_subscriptions().await.unwrap_or_default();

    let subscription_id = if !subs.is_empty() {
        let names: Vec<_> = subs
            .iter()
            .map(|s| {
                if s.is_default {
                    format!("{} ({}) [default]", s.name, s.id)
                } else {
                    format!("{} ({})", s.name, s.id)
                }
            })
            .collect();
        let default_idx = subs.iter().position(|s| s.is_default).unwrap_or(0);
        let chosen = dialoguer::Select::new()
            .with_prompt("Subscription")
            .items(&names)
            .default(default_idx)
            .interact()?;
        subs[chosen].id.clone()
    } else {
        println!("  (az not available or no subscriptions found — enter manually)");
        dialoguer::Input::new()
            .with_prompt("Subscription ID")
            .interact_text()?
    };

    let resource_group: String = dialoguer::Input::new()
        .with_prompt("Resource group name")
        .with_initial_text("rg-quelch-prod")
        .interact_text()?;

    let region: String = dialoguer::Input::new()
        .with_prompt("Azure region")
        .with_initial_text("swedencentral")
        .interact_text()?;

    let naming_prefix: String = dialoguer::Input::new()
        .with_prompt("Resource naming prefix")
        .with_initial_text("quelch")
        .interact_text()?;

    let naming_env: String = dialoguer::Input::new()
        .with_prompt("Environment tag (e.g. prod, staging)")
        .with_initial_text("prod")
        .interact_text()?;

    Ok(AzureConfig {
        subscription_id,
        resource_group,
        region,
        naming: NamingConfig {
            prefix: Some(naming_prefix),
            environment: Some(naming_env),
        },
        skip_role_assignments: false,
    })
}

// ---------------------------------------------------------------------------
// OpenAI section
// ---------------------------------------------------------------------------

/// Prompt for Azure OpenAI endpoint and embedding deployment.
pub async fn openai_section(
    azure: &AzureConfig,
    _subscription_id: &str,
) -> anyhow::Result<OpenAiConfig> {
    println!("\n=== Azure OpenAI ===");
    println!(
        "Looking for Azure OpenAI accounts in '{}'...",
        azure.resource_group
    );

    let discovered = discover::find_openai_account(&azure.subscription_id, &azure.resource_group)
        .await
        .ok()
        .flatten();

    let default_endpoint = discovered
        .as_ref()
        .map(|a| a.endpoint.clone())
        .unwrap_or_else(|| "https://YOUR-OPENAI.openai.azure.com".to_string());

    let endpoint: String = dialoguer::Input::new()
        .with_prompt("Azure OpenAI endpoint")
        .with_initial_text(&default_endpoint)
        .interact_text()?;

    let deployment_name: String = dialoguer::Input::new()
        .with_prompt("Embedding deployment name")
        .with_initial_text("text-embedding-3-large")
        .interact_text()?;

    let dimensions_str: String = dialoguer::Input::new()
        .with_prompt("Embedding dimensions")
        .with_initial_text("3072")
        .interact_text()?;
    let embedding_dimensions: u32 = dimensions_str
        .parse()
        .map_err(|_| anyhow::anyhow!("embedding dimensions must be a number"))?;

    Ok(OpenAiConfig {
        endpoint,
        embedding_deployment: deployment_name,
        embedding_dimensions,
    })
}

// ---------------------------------------------------------------------------
// Sources section
// ---------------------------------------------------------------------------

/// Prompt to add one or more Jira/Confluence sources.
pub async fn sources_section() -> anyhow::Result<Vec<SourceConfig>> {
    println!("\n=== Source connections ===");
    let mut sources = Vec::new();

    loop {
        let add = dialoguer::Select::new()
            .with_prompt("Add a source?")
            .items(&["Jira", "Confluence", "Done (no more sources)"])
            .default(0)
            .interact()?;

        match add {
            0 => sources.push(SourceConfig::Jira(prompt_jira_source()?)),
            1 => sources.push(SourceConfig::Confluence(prompt_confluence_source()?)),
            _ => break,
        }
    }

    Ok(sources)
}

/// Prompt for a Jira source and return a built `JiraSourceConfig`.
pub fn prompt_jira_source() -> anyhow::Result<JiraSourceConfig> {
    println!("  --- Jira source ---");
    let name: String = dialoguer::Input::new()
        .with_prompt("  Source name (unique identifier)")
        .with_initial_text("jira-cloud")
        .interact_text()?;

    let url: String = dialoguer::Input::new()
        .with_prompt("  Jira URL")
        .with_initial_text("https://your-org.atlassian.net")
        .interact_text()?;

    let is_cloud = dialoguer::Confirm::new()
        .with_prompt("  Is this Atlassian Cloud (yes) or Data Center (no)?")
        .default(true)
        .interact()?;

    let auth = if is_cloud {
        let email: String = dialoguer::Input::new()
            .with_prompt("  Atlassian account email")
            .interact_text()?;
        let api_token: String = dialoguer::Password::new()
            .with_prompt(
                "  API token (https://id.atlassian.com/manage-profile/security/api-tokens)",
            )
            .interact()?;
        AuthConfig::Cloud { email, api_token }
    } else {
        let pat: String = dialoguer::Password::new()
            .with_prompt("  Personal Access Token")
            .interact()?;
        AuthConfig::DataCenter { pat }
    };

    let projects_str: String = dialoguer::Input::new()
        .with_prompt("  Project keys (comma-separated, e.g. PROJ,ENG)")
        .interact_text()?;
    let projects: Vec<String> = projects_str
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    Ok(build_jira_source(name, url, auth, projects))
}

/// Build a `JiraSourceConfig` from discrete values.
///
/// Separated from the prompt so it can be unit-tested independently.
pub fn build_jira_source(
    name: String,
    url: String,
    auth: AuthConfig,
    projects: Vec<String>,
) -> JiraSourceConfig {
    JiraSourceConfig {
        name,
        url,
        auth,
        projects,
        container: None,
        companion_containers: CompanionContainersConfig::default(),
        fields: HashMap::new(),
    }
}

/// Prompt for a Confluence source and return a built `ConfluenceSourceConfig`.
pub fn prompt_confluence_source() -> anyhow::Result<ConfluenceSourceConfig> {
    println!("  --- Confluence source ---");
    let name: String = dialoguer::Input::new()
        .with_prompt("  Source name (unique identifier)")
        .with_initial_text("confluence-cloud")
        .interact_text()?;

    let url: String = dialoguer::Input::new()
        .with_prompt("  Confluence URL")
        .with_initial_text("https://your-org.atlassian.net/wiki")
        .interact_text()?;

    let is_cloud = dialoguer::Confirm::new()
        .with_prompt("  Is this Atlassian Cloud (yes) or Data Center (no)?")
        .default(true)
        .interact()?;

    let auth = if is_cloud {
        let email: String = dialoguer::Input::new()
            .with_prompt("  Atlassian account email")
            .interact_text()?;
        let api_token: String = dialoguer::Password::new()
            .with_prompt("  API token")
            .interact()?;
        AuthConfig::Cloud { email, api_token }
    } else {
        let pat: String = dialoguer::Password::new()
            .with_prompt("  Personal Access Token")
            .interact()?;
        AuthConfig::DataCenter { pat }
    };

    let spaces_str: String = dialoguer::Input::new()
        .with_prompt("  Space keys (comma-separated, e.g. ENG,DOCS)")
        .interact_text()?;
    let spaces: Vec<String> = spaces_str
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    Ok(build_confluence_source(name, url, auth, spaces))
}

/// Build a `ConfluenceSourceConfig` from discrete values.
pub fn build_confluence_source(
    name: String,
    url: String,
    auth: AuthConfig,
    spaces: Vec<String>,
) -> ConfluenceSourceConfig {
    ConfluenceSourceConfig {
        name,
        url,
        auth,
        spaces,
        container: None,
        companion_containers: CompanionContainersConfig::default(),
    }
}

// ---------------------------------------------------------------------------
// Deployments section
// ---------------------------------------------------------------------------

/// Prompt for deployment shape selection.
pub async fn deployments_section(
    sources: &[SourceConfig],
) -> anyhow::Result<Vec<DeploymentConfig>> {
    println!("\n=== Deployments ===");

    let shapes = [
        "All in Azure (ingest + MCP both as Azure Container Apps)",
        "Ingest on-prem + MCP in Azure",
        "Custom (configure each deployment manually)",
    ];

    let chosen = dialoguer::Select::new()
        .with_prompt("Deployment shape")
        .items(&shapes)
        .default(0)
        .interact()?;

    match chosen {
        0 => Ok(all_azure_deployments(sources)),
        1 => Ok(split_deployments(sources)),
        _ => {
            println!("  Custom deployment setup is not yet supported by the wizard.");
            println!("  Using all-Azure defaults — edit quelch.yaml afterwards.");
            Ok(all_azure_deployments(sources))
        }
    }
}

fn all_azure_deployments(sources: &[SourceConfig]) -> Vec<DeploymentConfig> {
    let source_refs: Vec<DeploymentSource> = sources
        .iter()
        .map(|s| DeploymentSource {
            source: s.name().to_string(),
            projects: None,
            spaces: None,
        })
        .collect();

    let expose = auto_expose_list(sources);

    vec![
        DeploymentConfig {
            name: "ingest".to_string(),
            role: DeploymentRole::Ingest,
            target: DeploymentTarget::Azure,
            sources: Some(source_refs),
            expose: None,
            azure: Some(DeploymentAzureConfig {
                container_app: ContainerAppSpec {
                    cpu: Some(0.5),
                    memory: Some("1.0Gi".to_string()),
                    min_replicas: None,
                    max_replicas: None,
                },
            }),
            auth: None,
        },
        DeploymentConfig {
            name: "mcp".to_string(),
            role: DeploymentRole::Mcp,
            target: DeploymentTarget::Azure,
            sources: None,
            expose: Some(expose),
            azure: Some(DeploymentAzureConfig {
                container_app: ContainerAppSpec {
                    cpu: Some(1.0),
                    memory: Some("2.0Gi".to_string()),
                    min_replicas: Some(0),
                    max_replicas: None,
                },
            }),
            auth: Some(DeploymentAuthConfig {
                mode: McpAuthMode::ApiKey,
            }),
        },
    ]
}

fn split_deployments(sources: &[SourceConfig]) -> Vec<DeploymentConfig> {
    let source_refs: Vec<DeploymentSource> = sources
        .iter()
        .map(|s| DeploymentSource {
            source: s.name().to_string(),
            projects: None,
            spaces: None,
        })
        .collect();

    let expose = auto_expose_list(sources);

    vec![
        DeploymentConfig {
            name: "ingest-onprem".to_string(),
            role: DeploymentRole::Ingest,
            target: DeploymentTarget::Onprem,
            sources: Some(source_refs),
            expose: None,
            azure: None,
            auth: None,
        },
        DeploymentConfig {
            name: "mcp".to_string(),
            role: DeploymentRole::Mcp,
            target: DeploymentTarget::Azure,
            sources: None,
            expose: Some(expose),
            azure: Some(DeploymentAzureConfig {
                container_app: ContainerAppSpec {
                    cpu: Some(1.0),
                    memory: Some("2.0Gi".to_string()),
                    min_replicas: Some(0),
                    max_replicas: None,
                },
            }),
            auth: Some(DeploymentAuthConfig {
                mode: McpAuthMode::ApiKey,
            }),
        },
    ]
}

/// Derive a default expose list from sources.
fn auto_expose_list(sources: &[SourceConfig]) -> Vec<String> {
    let mut expose = Vec::new();
    for s in sources {
        match s {
            SourceConfig::Jira(_) => {
                if !expose.contains(&"jira_issues".to_string()) {
                    expose.push("jira_issues".to_string());
                }
            }
            SourceConfig::Confluence(_) => {
                if !expose.contains(&"confluence_pages".to_string()) {
                    expose.push("confluence_pages".to_string());
                }
            }
        }
    }
    expose
}

// ---------------------------------------------------------------------------
// MCP section
// ---------------------------------------------------------------------------

/// Prompt for MCP data source configuration.
pub async fn mcp_section(deployments: &[DeploymentConfig]) -> anyhow::Result<McpConfig> {
    // Derive data_sources from the MCP deployment's expose list (auto-derived).
    let expose: Vec<&str> = deployments
        .iter()
        .filter(|d| d.role == DeploymentRole::Mcp)
        .flat_map(|d| d.expose.as_deref().unwrap_or(&[]))
        .map(String::as_str)
        .collect();

    let mut data_sources = HashMap::new();
    for ds_name in expose {
        let (kind, container) = match ds_name {
            "jira_issues" => ("jira_issue", "jira-issues"),
            "confluence_pages" => ("confluence_page", "confluence-pages"),
            other => (other, other),
        };
        data_sources.insert(
            ds_name.to_string(),
            McpDataSourceSpec {
                kind: kind.to_string(),
                backed_by: vec![BackedBy {
                    container: container.to_string(),
                }],
            },
        );
    }

    Ok(McpConfig {
        data_sources,
        ..McpConfig::default()
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn build_jira_source_creates_correct_config() {
        let cfg = build_jira_source(
            "my-jira".to_string(),
            "https://example.atlassian.net".to_string(),
            AuthConfig::Cloud {
                email: "user@example.com".to_string(),
                api_token: "tok".to_string(),
            },
            vec!["PROJ".to_string(), "ENG".to_string()],
        );

        assert_eq!(cfg.name, "my-jira");
        assert_eq!(cfg.url, "https://example.atlassian.net");
        assert_eq!(cfg.projects, vec!["PROJ", "ENG"]);
        assert!(matches!(cfg.auth, AuthConfig::Cloud { .. }));
    }

    #[test]
    fn build_confluence_source_creates_correct_config() {
        let cfg = build_confluence_source(
            "my-confluence".to_string(),
            "https://example.atlassian.net/wiki".to_string(),
            AuthConfig::DataCenter {
                pat: "my-pat".to_string(),
            },
            vec!["ENG".to_string()],
        );

        assert_eq!(cfg.name, "my-confluence");
        assert!(matches!(cfg.auth, AuthConfig::DataCenter { .. }));
        assert_eq!(cfg.spaces, vec!["ENG"]);
    }

    #[test]
    fn auto_expose_list_derives_from_sources() {
        let sources = vec![
            SourceConfig::Jira(build_jira_source(
                "j".to_string(),
                "https://x.atlassian.net".to_string(),
                AuthConfig::Cloud {
                    email: "u@example.com".to_string(),
                    api_token: "t".to_string(),
                },
                vec!["X".to_string()],
            )),
            SourceConfig::Confluence(build_confluence_source(
                "c".to_string(),
                "https://x.atlassian.net/wiki".to_string(),
                AuthConfig::Cloud {
                    email: "u@example.com".to_string(),
                    api_token: "t".to_string(),
                },
                vec!["ENG".to_string()],
            )),
        ];
        let expose = auto_expose_list(&sources);
        assert!(expose.contains(&"jira_issues".to_string()));
        assert!(expose.contains(&"confluence_pages".to_string()));
    }

    #[test]
    fn all_azure_deployments_produces_two_deployments() {
        let sources = vec![SourceConfig::Jira(build_jira_source(
            "j".to_string(),
            "https://x.atlassian.net".to_string(),
            AuthConfig::Cloud {
                email: "u@example.com".to_string(),
                api_token: "t".to_string(),
            },
            vec!["X".to_string()],
        ))];
        let deps = all_azure_deployments(&sources);
        assert_eq!(deps.len(), 2);
        assert!(deps.iter().any(|d| d.role == DeploymentRole::Ingest));
        assert!(deps.iter().any(|d| d.role == DeploymentRole::Mcp));
    }
}