Skip to main content

greentic_component/wizard/
mod.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use anyhow::{Context, Result, anyhow, bail};
6use ciborium::Value as CborValue;
7use greentic_types::cbor::canonical;
8use greentic_types::i18n_text::I18nText;
9use greentic_types::schemas::component::v0_6_0::{ChoiceOption, ComponentQaSpec, QaMode, Question};
10use serde::Serialize;
11use serde_json::Map as JsonMap;
12use serde_json::Value as JsonValue;
13use serde_json::json;
14
15use crate::scaffold::config_schema::ConfigSchemaInput;
16use crate::scaffold::deps::{DependencyMode, DependencyTemplates, resolve_dependency_templates};
17use crate::scaffold::runtime_capabilities::RuntimeCapabilitiesInput;
18
19pub const PLAN_VERSION: u32 = 1;
20pub const TEMPLATE_VERSION: &str = "component-scaffold-v0.6.0";
21pub const GENERATOR_ID: &str = "greentic-component/wizard-provider";
22
23fn question(id: &str, label_key: &str, help_key: &str, required: bool) -> Question {
24    question_json(json!({
25        "id": id,
26        "label": I18nText::new(label_key, None),
27        "help": I18nText::new(help_key, None),
28        "error": null,
29        "kind": { "type": "text" },
30        "required": required,
31        "default": null
32    }))
33}
34
35fn question_bool(id: &str, label_key: &str, help_key: &str, required: bool) -> Question {
36    question_json(json!({
37        "id": id,
38        "label": I18nText::new(label_key, None),
39        "help": I18nText::new(help_key, None),
40        "error": null,
41        "kind": { "type": "bool" },
42        "required": required,
43        "default": null
44    }))
45}
46
47fn question_choice(
48    id: &str,
49    label_key: &str,
50    help_key: &str,
51    required: bool,
52    options: Vec<ChoiceOption>,
53) -> Question {
54    question_json(json!({
55        "id": id,
56        "label": I18nText::new(label_key, None),
57        "help": I18nText::new(help_key, None),
58        "error": null,
59        "kind": {
60            "type": "choice",
61            "options": options
62        },
63        "required": required,
64        "default": null
65    }))
66}
67
68fn question_json(value: JsonValue) -> Question {
69    serde_json::from_value(value).expect("question should deserialize")
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
73pub enum WizardMode {
74    Default,
75    Setup,
76    Update,
77    Remove,
78}
79
80#[derive(Debug, Clone)]
81pub struct AnswersPayload {
82    pub json: String,
83    pub cbor: Vec<u8>,
84}
85
86#[derive(Debug, Clone)]
87pub struct WizardRequest {
88    pub name: String,
89    pub abi_version: String,
90    pub mode: WizardMode,
91    pub target: PathBuf,
92    pub answers: Option<AnswersPayload>,
93    pub required_capabilities: Vec<String>,
94    pub provided_capabilities: Vec<String>,
95    pub user_operations: Vec<String>,
96    pub default_operation: Option<String>,
97    pub runtime_capabilities: RuntimeCapabilitiesInput,
98    pub config_schema: ConfigSchemaInput,
99}
100
101#[derive(Debug, Clone, Serialize)]
102pub struct ApplyResult {
103    pub plan: WizardPlanEnvelope,
104    pub warnings: Vec<String>,
105}
106
107#[derive(Debug, Clone, Serialize)]
108pub struct WizardPlanEnvelope {
109    pub plan_version: u32,
110    pub metadata: WizardPlanMetadata,
111    pub target_root: PathBuf,
112    pub plan: WizardPlan,
113}
114
115#[derive(Debug, Clone, Serialize)]
116pub struct WizardPlanMetadata {
117    pub generator: String,
118    pub template_version: String,
119    pub template_digest_blake3: String,
120    pub requested_abi_version: String,
121}
122
123// Compat shim: keep deterministic plan JSON stable without requiring newer
124// greentic-types exports during cargo package verification.
125#[derive(Debug, Clone, Serialize)]
126pub struct WizardPlan {
127    pub meta: WizardPlanMeta,
128    pub steps: Vec<WizardStep>,
129}
130
131#[derive(Debug, Clone, Serialize)]
132pub struct WizardPlanMeta {
133    pub id: String,
134    pub target: WizardTarget,
135    pub mode: WizardPlanMode,
136}
137
138#[derive(Debug, Clone, Serialize)]
139#[serde(rename_all = "snake_case")]
140pub enum WizardTarget {
141    Component,
142}
143
144#[derive(Debug, Clone, Serialize)]
145#[serde(rename_all = "snake_case")]
146pub enum WizardPlanMode {
147    Scaffold,
148}
149
150#[derive(Debug, Clone, Serialize)]
151#[serde(tag = "type", rename_all = "snake_case")]
152pub enum WizardStep {
153    EnsureDir { paths: Vec<String> },
154    WriteFiles { files: BTreeMap<String, String> },
155    RunCli { command: String },
156    Delegate { id: String },
157    BuildComponent { project_root: String },
158    TestComponent { project_root: String, full: bool },
159    Doctor { project_root: String },
160}
161
162pub fn spec_scaffold(mode: WizardMode) -> ComponentQaSpec {
163    let title = match mode {
164        WizardMode::Default => "wizard.component.default.title",
165        WizardMode::Setup => "wizard.component.setup.title",
166        WizardMode::Update => "wizard.component.update.title",
167        WizardMode::Remove => "wizard.component.remove.title",
168    };
169    ComponentQaSpec {
170        mode: qa_mode(mode),
171        title: I18nText::new(title, None),
172        description: Some(I18nText::new("wizard.component.description", None)),
173        questions: vec![
174            question(
175                "component.name",
176                "wizard.component.name.label",
177                "wizard.component.name.help",
178                true,
179            ),
180            question(
181                "component.path",
182                "wizard.component.path.label",
183                "wizard.component.path.help",
184                false,
185            ),
186            question_choice(
187                "component.kind",
188                "wizard.component.kind.label",
189                "wizard.component.kind.help",
190                false,
191                vec![
192                    ChoiceOption {
193                        value: "tool".to_string(),
194                        label: I18nText::new("wizard.component.kind.option.tool", None),
195                    },
196                    ChoiceOption {
197                        value: "source".to_string(),
198                        label: I18nText::new("wizard.component.kind.option.source", None),
199                    },
200                ],
201            ),
202            question_bool(
203                "component.features.enabled",
204                "wizard.component.features.enabled.label",
205                "wizard.component.features.enabled.help",
206                false,
207            ),
208        ],
209        defaults: BTreeMap::from([(
210            "component.features.enabled".to_string(),
211            CborValue::Bool(true),
212        )]),
213    }
214}
215
216pub fn apply_scaffold(request: WizardRequest, dry_run: bool) -> Result<ApplyResult> {
217    let warnings = abi_warnings(&request.abi_version);
218    let (prefill_answers_json, prefill_answers_cbor, mut mapping_warnings) =
219        normalize_answers(request.answers, request.mode)?;
220    let mut all_warnings = warnings;
221    all_warnings.append(&mut mapping_warnings);
222    let user_operations = if request.user_operations.is_empty() {
223        vec!["handle_message".to_string()]
224    } else {
225        request.user_operations.clone()
226    };
227    let default_operation = request
228        .default_operation
229        .clone()
230        .or_else(|| user_operations.first().cloned())
231        .unwrap_or_else(|| "handle_message".to_string());
232    let context = WizardContext {
233        name: request.name,
234        abi_version: request.abi_version.clone(),
235        prefill_mode: request.mode,
236        prefill_answers_cbor,
237        prefill_answers_json,
238        user_operations,
239        default_operation,
240        runtime_capabilities: request.runtime_capabilities,
241        config_schema: request.config_schema,
242        dependency_templates: resolve_dependency_templates(
243            DependencyMode::from_env(),
244            &request.target,
245        ),
246    };
247
248    let files = build_files(&context)?;
249    let plan = build_plan(request.target, &request.abi_version, files);
250    if !dry_run {
251        execute_plan(&plan)?;
252    }
253
254    Ok(ApplyResult {
255        plan,
256        warnings: all_warnings,
257    })
258}
259
260pub fn execute_plan(envelope: &WizardPlanEnvelope) -> Result<()> {
261    for step in &envelope.plan.steps {
262        match step {
263            WizardStep::EnsureDir { paths } => {
264                for path in paths {
265                    let dir = envelope.target_root.join(path);
266                    fs::create_dir_all(&dir).with_context(|| {
267                        format!("wizard: failed to create directory {}", dir.display())
268                    })?;
269                }
270            }
271            WizardStep::WriteFiles { files } => {
272                for (relative_path, content) in files {
273                    let target = envelope.target_root.join(relative_path);
274                    if let Some(parent) = target.parent() {
275                        fs::create_dir_all(parent).with_context(|| {
276                            format!("wizard: failed to create directory {}", parent.display())
277                        })?;
278                    }
279                    let bytes = decode_step_content(relative_path, content)?;
280                    fs::write(&target, bytes)
281                        .with_context(|| format!("wizard: failed to write {}", target.display()))?;
282                    #[cfg(unix)]
283                    if is_executable_heuristic(Path::new(relative_path)) {
284                        use std::os::unix::fs::PermissionsExt;
285                        let mut permissions = fs::metadata(&target)
286                            .with_context(|| {
287                                format!("wizard: failed to stat {}", target.display())
288                            })?
289                            .permissions();
290                        permissions.set_mode(0o755);
291                        fs::set_permissions(&target, permissions).with_context(|| {
292                            format!("wizard: failed to set executable bit {}", target.display())
293                        })?;
294                    }
295                }
296            }
297            WizardStep::RunCli { command, .. } => {
298                bail!("wizard: unsupported plan step run_cli ({command})")
299            }
300            WizardStep::Delegate { id, .. } => {
301                bail!("wizard: unsupported plan step delegate ({})", id.as_str())
302            }
303            WizardStep::BuildComponent { project_root } => {
304                bail!("wizard: unsupported plan step build_component ({project_root})")
305            }
306            WizardStep::TestComponent { project_root, .. } => {
307                bail!("wizard: unsupported plan step test_component ({project_root})")
308            }
309            WizardStep::Doctor { project_root } => {
310                bail!("wizard: unsupported plan step doctor ({project_root})")
311            }
312        }
313    }
314    Ok(())
315}
316
317fn is_executable_heuristic(path: &Path) -> bool {
318    matches!(
319        path.extension().and_then(|ext| ext.to_str()),
320        Some("sh" | "bash" | "zsh" | "ps1")
321    ) || path
322        .file_name()
323        .and_then(|name| name.to_str())
324        .map(|name| name == "Makefile")
325        .unwrap_or(false)
326}
327
328pub fn load_answers_payload(path: &Path) -> Result<AnswersPayload> {
329    let json = fs::read_to_string(path)
330        .with_context(|| format!("wizard: failed to open answers file {}", path.display()))?;
331    let value: JsonValue = serde_json::from_str(&json)
332        .with_context(|| format!("wizard: answers file {} is not valid JSON", path.display()))?;
333    let cbor = canonical::to_canonical_cbor_allow_floats(&value)
334        .map_err(|err| anyhow!("wizard: failed to encode answers as CBOR: {err}"))?;
335    Ok(AnswersPayload { json, cbor })
336}
337
338struct WizardContext {
339    name: String,
340    abi_version: String,
341    prefill_mode: WizardMode,
342    prefill_answers_cbor: Option<Vec<u8>>,
343    prefill_answers_json: Option<String>,
344    user_operations: Vec<String>,
345    default_operation: String,
346    runtime_capabilities: RuntimeCapabilitiesInput,
347    config_schema: ConfigSchemaInput,
348    dependency_templates: DependencyTemplates,
349}
350
351type NormalizedAnswers = (Option<String>, Option<Vec<u8>>, Vec<String>);
352
353fn normalize_answers(
354    answers: Option<AnswersPayload>,
355    mode: WizardMode,
356) -> Result<NormalizedAnswers> {
357    let warnings = Vec::new();
358    let Some(payload) = answers else {
359        return Ok((None, None, warnings));
360    };
361    let mut value: JsonValue = serde_json::from_str(&payload.json).with_context(|| {
362        "wizard: answers JSON payload should be valid after initial parse".to_string()
363    })?;
364    let JsonValue::Object(mut root) = value else {
365        return Ok((Some(payload.json), Some(payload.cbor), warnings));
366    };
367
368    let enabled = extract_bool(&root, &["component.features.enabled", "enabled"]);
369    if let Some(flag) = enabled {
370        root.insert("enabled".to_string(), JsonValue::Bool(flag));
371    } else if matches!(
372        mode,
373        WizardMode::Default | WizardMode::Setup | WizardMode::Update
374    ) {
375        root.insert("enabled".to_string(), JsonValue::Bool(true));
376    }
377
378    value = JsonValue::Object(root);
379    let json = serde_json::to_string_pretty(&value)?;
380    let cbor = canonical::to_canonical_cbor_allow_floats(&value)
381        .map_err(|err| anyhow!("wizard: failed to encode normalized answers as CBOR: {err}"))?;
382    Ok((Some(json), Some(cbor), warnings))
383}
384
385fn extract_bool(root: &JsonMap<String, JsonValue>, keys: &[&str]) -> Option<bool> {
386    for key in keys {
387        if let Some(value) = root.get(*key)
388            && let Some(flag) = value.as_bool()
389        {
390            return Some(flag);
391        }
392        if let Some(flag) = nested_bool(root, key) {
393            return Some(flag);
394        }
395    }
396    None
397}
398
399fn nested_bool(root: &JsonMap<String, JsonValue>, dotted: &str) -> Option<bool> {
400    nested_value(root, dotted).and_then(|value| value.as_bool())
401}
402
403fn nested_value<'a>(root: &'a JsonMap<String, JsonValue>, dotted: &str) -> Option<&'a JsonValue> {
404    let mut parts = dotted.split('.');
405    let first = parts.next()?;
406    let mut current = root.get(first)?;
407    for segment in parts {
408        let JsonValue::Object(map) = current else {
409            return None;
410        };
411        current = map.get(segment)?;
412    }
413    Some(current)
414}
415
416struct GeneratedFile {
417    path: PathBuf,
418    contents: Vec<u8>,
419}
420
421fn build_files(context: &WizardContext) -> Result<Vec<GeneratedFile>> {
422    let mut files = vec![
423        text_file("Cargo.toml", render_cargo_toml(context)),
424        text_file("rust-toolchain.toml", render_rust_toolchain_toml()),
425        text_file("README.md", render_readme(context)),
426        text_file("component.manifest.json", render_manifest_json(context)),
427        text_file(
428            "schemas/component.schema.json",
429            render_component_schema_json(context),
430        ),
431        text_file("Makefile", render_makefile()),
432        text_file("build.rs", render_build_rs()),
433        text_file("src/lib.rs", render_lib_rs(context)),
434        text_file("src/qa.rs", render_qa_rs()),
435        text_file("src/i18n.rs", render_i18n_rs()),
436        text_file("src/i18n_bundle.rs", render_i18n_bundle_rs()),
437        text_file("assets/i18n/en.json", render_i18n_bundle()),
438        text_file("assets/i18n/locales.json", render_i18n_locales_json()),
439        text_file("tools/i18n.sh", render_i18n_sh()),
440    ];
441
442    if let (Some(json), Some(cbor)) = (
443        context.prefill_answers_json.as_ref(),
444        context.prefill_answers_cbor.as_ref(),
445    ) {
446        let mode = match context.prefill_mode {
447            WizardMode::Default => "default",
448            WizardMode::Setup => "setup",
449            WizardMode::Update => "update",
450            WizardMode::Remove => "remove",
451        };
452        files.push(text_file(
453            &format!("examples/{mode}.answers.json"),
454            json.clone(),
455        ));
456        files.push(binary_file(
457            &format!("examples/{mode}.answers.cbor"),
458            cbor.clone(),
459        ));
460    }
461
462    Ok(files)
463}
464
465fn build_plan(target: PathBuf, abi_version: &str, files: Vec<GeneratedFile>) -> WizardPlanEnvelope {
466    let mut dirs = BTreeSet::new();
467    for file in &files {
468        if let Some(parent) = file.path.parent()
469            && !parent.as_os_str().is_empty()
470        {
471            dirs.insert(parent.to_path_buf());
472        }
473    }
474    let mut steps: Vec<WizardStep> = Vec::new();
475    if !dirs.is_empty() {
476        let paths = dirs
477            .into_iter()
478            .map(|path| path.to_string_lossy().into_owned())
479            .collect::<Vec<_>>();
480        steps.push(WizardStep::EnsureDir { paths });
481    }
482
483    let mut file_map = BTreeMap::new();
484    for file in &files {
485        let key = file.path.to_string_lossy().into_owned();
486        file_map.insert(key, encode_step_content(&file.path, &file.contents));
487    }
488    if !file_map.is_empty() {
489        steps.push(WizardStep::WriteFiles { files: file_map });
490    }
491
492    let plan = WizardPlan {
493        meta: WizardPlanMeta {
494            id: "greentic.component.scaffold".to_string(),
495            target: WizardTarget::Component,
496            mode: WizardPlanMode::Scaffold,
497        },
498        steps,
499    };
500    let metadata = WizardPlanMetadata {
501        generator: GENERATOR_ID.to_string(),
502        template_version: TEMPLATE_VERSION.to_string(),
503        template_digest_blake3: template_digest_hex(&files),
504        requested_abi_version: abi_version.to_string(),
505    };
506    WizardPlanEnvelope {
507        plan_version: PLAN_VERSION,
508        metadata,
509        target_root: target,
510        plan,
511    }
512}
513
514const STEP_BASE64_PREFIX: &str = "base64:";
515
516fn encode_step_content(path: &Path, bytes: &[u8]) -> String {
517    if path
518        .extension()
519        .and_then(|ext| ext.to_str())
520        .is_some_and(|ext| ext == "cbor")
521    {
522        format!(
523            "{STEP_BASE64_PREFIX}{}",
524            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
525        )
526    } else {
527        String::from_utf8(bytes.to_vec()).unwrap_or_default()
528    }
529}
530
531fn decode_step_content(relative_path: &str, content: &str) -> Result<Vec<u8>> {
532    if relative_path.ends_with(".cbor") && content.starts_with(STEP_BASE64_PREFIX) {
533        let raw = content.trim_start_matches(STEP_BASE64_PREFIX);
534        let decoded = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, raw)
535            .map_err(|err| anyhow!("wizard: invalid base64 content for {relative_path}: {err}"))?;
536        return Ok(decoded);
537    }
538    Ok(content.as_bytes().to_vec())
539}
540
541fn template_digest_hex(files: &[GeneratedFile]) -> String {
542    let mut hasher = blake3::Hasher::new();
543    for file in files {
544        hasher.update(file.path.to_string_lossy().as_bytes());
545        hasher.update(&[0]);
546        hasher.update(&file.contents);
547        hasher.update(&[0xff]);
548    }
549    hasher.finalize().to_hex().to_string()
550}
551
552fn abi_warnings(abi_version: &str) -> Vec<String> {
553    if abi_version == "0.6.0" {
554        Vec::new()
555    } else {
556        vec![format!(
557            "wizard: warning: only component@0.6.0 template is generated (requested {abi_version})"
558        )]
559    }
560}
561
562fn qa_mode(mode: WizardMode) -> QaMode {
563    match mode {
564        WizardMode::Default => QaMode::Default,
565        WizardMode::Setup => QaMode::Setup,
566        WizardMode::Update => QaMode::Update,
567        WizardMode::Remove => QaMode::Remove,
568    }
569}
570
571fn render_rust_toolchain_toml() -> String {
572    r#"[toolchain]
573channel = "1.91.0"
574components = ["clippy", "rustfmt"]
575targets = ["wasm32-wasip2", "x86_64-unknown-linux-gnu"]
576profile = "minimal"
577"#
578    .to_string()
579}
580
581fn text_file(path: &str, contents: String) -> GeneratedFile {
582    GeneratedFile {
583        path: PathBuf::from(path),
584        contents: contents.into_bytes(),
585    }
586}
587
588fn binary_file(path: &str, contents: Vec<u8>) -> GeneratedFile {
589    GeneratedFile {
590        path: PathBuf::from(path),
591        contents,
592    }
593}
594
595fn render_cargo_toml(context: &WizardContext) -> String {
596    format!(
597        r#"[package]
598name = "{name}"
599version = "0.1.0"
600edition = "2024"
601license = "MIT"
602rust-version = "1.91"
603description = "Greentic component {name}"
604build = "build.rs"
605
606[lib]
607crate-type = ["cdylib", "rlib"]
608
609[package.metadata.greentic]
610abi_version = "{abi_version}"
611
612[package.metadata.component]
613package = "greentic:component"
614
615[package.metadata.component.target]
616world = "greentic:component/component@0.6.0"
617
618[dependencies]
619greentic-types = {{ {greentic_types} }}
620greentic-interfaces-guest = {{ {greentic_interfaces_guest}, default-features = false, features = ["component-v0-6"] }}
621serde = {{ version = "1", features = ["derive"] }}
622serde_json = "1"
623
624[build-dependencies]
625greentic-types = {{ {greentic_types} }}
626serde_json = "1"
627"#,
628        name = context.name,
629        abi_version = context.abi_version,
630        greentic_types = context.dependency_templates.greentic_types,
631        greentic_interfaces_guest = context.dependency_templates.greentic_interfaces_guest
632    )
633}
634
635fn render_readme(context: &WizardContext) -> String {
636    format!(
637        r#"# {name}
638
639Generated by `greentic-component wizard` for component@0.6.0.
640
641## Next steps
642- Extend QA flows in `src/qa.rs` and i18n keys in `src/i18n.rs`.
643- Generate/update locales via `./tools/i18n.sh`.
644- Rebuild to embed translations: `cargo build`.
645
646## QA ops
647- `qa-spec`: emits setup/update/remove semantics and accepts `default|setup|install|update|upgrade|remove`.
648- `apply-answers`: returns base response shape `{{ ok, config?, warnings, errors }}`.
649- `i18n-keys`: returns i18n keys used by QA/setup messaging.
650
651## ABI version
652Requested ABI version: {abi_version}
653
654Note: the wizard currently emits a fixed 0.6.0 template.
655"#,
656        name = context.name,
657        abi_version = context.abi_version
658    )
659}
660
661fn render_makefile() -> String {
662    r#"SHELL := /bin/sh
663
664NAME := $(shell awk 'BEGIN{in_pkg=0} /^\[package\]/{in_pkg=1; next} /^\[/{in_pkg=0} in_pkg && /^name = / {gsub(/"/ , "", $$3); print $$3; exit}' Cargo.toml)
665NAME_UNDERSCORE := $(subst -,_,$(NAME))
666ABI_VERSION := $(shell awk 'BEGIN{in_meta=0} /^\[package.metadata.greentic\]/{in_meta=1; next} /^\[/{in_meta=0} in_meta && /^abi_version = / {gsub(/"/ , "", $$3); print $$3; exit}' Cargo.toml)
667ABI_VERSION_UNDERSCORE := $(subst .,_,$(ABI_VERSION))
668DIST_DIR := dist
669WASM_OUT := $(DIST_DIR)/$(NAME)__$(ABI_VERSION_UNDERSCORE).wasm
670GREENTIC_COMPONENT ?= greentic-component
671
672.PHONY: build test fmt clippy wasm doctor
673
674build:
675	cargo build
676
677test:
678	cargo test
679
680fmt:
681	cargo fmt
682
683clippy:
684	cargo clippy --all-targets --all-features -- -D warnings
685
686wasm:
687	if ! cargo component --version >/dev/null 2>&1; then \
688		echo "cargo-component is required to produce a valid component@0.6.0 wasm"; \
689		echo "install with: cargo install cargo-component --locked"; \
690		exit 1; \
691	fi
692	RUSTFLAGS= CARGO_ENCODED_RUSTFLAGS= $(GREENTIC_COMPONENT) build --manifest ./component.manifest.json
693	WASM_SRC=""; \
694	for cand in \
695		"$${CARGO_TARGET_DIR:-target}/wasm32-wasip2/release/$(NAME_UNDERSCORE).wasm" \
696		"$${CARGO_TARGET_DIR:-target}/wasm32-wasip2/release/$(NAME).wasm" \
697		"target/wasm32-wasip2/release/$(NAME_UNDERSCORE).wasm" \
698		"target/wasm32-wasip2/release/$(NAME).wasm"; do \
699		if [ -f "$$cand" ]; then WASM_SRC="$$cand"; break; fi; \
700	done; \
701	if [ -z "$$WASM_SRC" ]; then \
702		echo "unable to locate wasm32-wasip2 component build artifact for $(NAME)"; \
703		exit 1; \
704	fi; \
705	mkdir -p $(DIST_DIR); \
706	cp "$$WASM_SRC" $(WASM_OUT); \
707	$(GREENTIC_COMPONENT) hash ./component.manifest.json --wasm $(WASM_OUT)
708
709doctor:
710	$(GREENTIC_COMPONENT) doctor $(WASM_OUT) --manifest ./component.manifest.json
711"#
712    .to_string()
713}
714
715fn render_manifest_json(context: &WizardContext) -> String {
716    let name_snake = context.name.replace('-', "_");
717    let mut operations = context
718        .user_operations
719        .iter()
720        .map(|operation_name| {
721            json!({
722                "name": operation_name,
723                "input_schema": {
724                    "$schema": "https://json-schema.org/draft/2020-12/schema",
725                    "title": format!("{} {} input", context.name, operation_name),
726                    "type": "object",
727                    "required": ["input"],
728                    "properties": {
729                        "input": {
730                            "type": "string",
731                            "default": format!("Hello from {}!", context.name)
732                        }
733                    },
734                    "additionalProperties": false
735                },
736                "output_schema": {
737                    "$schema": "https://json-schema.org/draft/2020-12/schema",
738                    "title": format!("{} {} output", context.name, operation_name),
739                    "type": "object",
740                    "required": ["message"],
741                    "properties": {
742                        "message": { "type": "string" }
743                    },
744                    "additionalProperties": false
745                }
746            })
747        })
748        .collect::<Vec<_>>();
749    operations.extend([
750        json!({
751            "name": "qa-spec",
752            "input_schema": {
753                "$schema": "https://json-schema.org/draft/2020-12/schema",
754                "title": format!("{} qa-spec input", context.name),
755                "type": "object",
756                "properties": {
757                    "mode": {
758                        "type": "string",
759                        "enum": ["default", "setup", "install", "update", "upgrade", "remove"]
760                    }
761                },
762                "required": ["mode"],
763                "additionalProperties": false
764            },
765            "output_schema": {
766                "type": "object",
767                "properties": {
768                    "mode": {
769                        "type": "string",
770                        "enum": ["setup", "update", "remove"]
771                    },
772                    "title_i18n_key": { "type": "string" },
773                    "description_i18n_key": { "type": "string" },
774                    "fields": {
775                        "type": "array",
776                        "items": { "type": "object" }
777                    }
778                },
779                "required": ["mode", "fields"],
780                "additionalProperties": true
781            }
782        }),
783        json!({
784            "name": "apply-answers",
785            "input_schema": {
786                "$schema": "https://json-schema.org/draft/2020-12/schema",
787                "title": format!("{} apply-answers input", context.name),
788                "type": "object",
789                "properties": {
790                    "mode": { "type": "string" },
791                    "current_config": { "type": "object" },
792                    "answers": { "type": "object" }
793                },
794                "additionalProperties": true
795            },
796            "output_schema": {
797                "$schema": "https://json-schema.org/draft/2020-12/schema",
798                "title": format!("{} apply-answers output", context.name),
799                "type": "object",
800                "required": ["ok", "warnings", "errors"],
801                "properties": {
802                    "ok": { "type": "boolean" },
803                    "warnings": { "type": "array", "items": { "type": "string" } },
804                    "errors": { "type": "array", "items": { "type": "string" } },
805                    "config": { "type": "object" }
806                },
807                "additionalProperties": true
808            }
809        }),
810        json!({
811            "name": "i18n-keys",
812            "input_schema": {
813                "$schema": "https://json-schema.org/draft/2020-12/schema",
814                "title": format!("{} i18n-keys input", context.name),
815                "type": "object",
816                "additionalProperties": false
817            },
818            "output_schema": {
819                "$schema": "https://json-schema.org/draft/2020-12/schema",
820                "title": format!("{} i18n-keys output", context.name),
821                "type": "array",
822                "items": { "type": "string" }
823            }
824        }),
825    ]);
826
827    let mut manifest = json!({
828        "$schema": "https://greenticai.github.io/greentic-component/schemas/v1/component.manifest.schema.json",
829        "id": format!("com.example.{}", context.name),
830        "name": context.name,
831        "version": "0.1.0",
832        "world": "greentic:component/component@0.6.0",
833        "describe_export": "describe",
834        "operations": operations,
835        "default_operation": context.default_operation,
836        "config_schema": context.config_schema.manifest_schema(),
837        "supports": ["messaging"],
838        "profiles": {
839            "default": "stateless",
840            "supported": ["stateless"]
841        },
842        "secret_requirements": context.runtime_capabilities.manifest_secret_requirements(),
843        "capabilities": context.runtime_capabilities.manifest_capabilities(),
844        "limits": {
845            "memory_mb": 128,
846            "wall_time_ms": 1000
847        },
848        "artifacts": {
849            "component_wasm": format!("target/wasm32-wasip2/release/{name_snake}.wasm")
850        },
851        "hashes": {
852            "component_wasm": "blake3:0000000000000000000000000000000000000000000000000000000000000000"
853        },
854        "dev_flows": {
855            "default": {
856                "format": "flow-ir-json",
857                "graph": {
858                    "nodes": [
859                        { "id": "start", "type": "start" },
860                        { "id": "end", "type": "end" }
861                    ],
862                    "edges": [
863                        { "from": "start", "to": "end" }
864                    ]
865                }
866            }
867        }
868    });
869    if let Some(telemetry) = context.runtime_capabilities.manifest_telemetry() {
870        manifest["telemetry"] = telemetry;
871    }
872    serde_json::to_string_pretty(&manifest).expect("wizard manifest should serialize")
873}
874
875fn render_component_schema_json(context: &WizardContext) -> String {
876    serde_json::to_string_pretty(&context.config_schema.component_schema_file(&context.name))
877        .expect("wizard config schema should serialize")
878}
879
880fn render_lib_rs(context: &WizardContext) -> String {
881    let user_describe_ops = render_lib_user_describe_ops(context);
882    let config_schema_rust = context.config_schema.rust_schema_ir();
883    format!(
884        r#"#[cfg(target_arch = "wasm32")]
885use std::collections::BTreeMap;
886
887#[cfg(target_arch = "wasm32")]
888use greentic_interfaces_guest::component_v0_6::node;
889#[cfg(target_arch = "wasm32")]
890use greentic_types::cbor::canonical;
891#[cfg(target_arch = "wasm32")]
892use greentic_types::schemas::common::schema_ir::{{AdditionalProperties, SchemaIr}};
893#[cfg(target_arch = "wasm32")]
894use greentic_types::schemas::component::v0_6_0::{{ComponentInfo, I18nText}};
895
896// i18n: runtime lookup + embedded CBOR bundle helpers.
897pub mod i18n;
898pub mod i18n_bundle;
899// qa: mode normalization, QA spec generation, apply-answers validation.
900pub mod qa;
901
902const COMPONENT_NAME: &str = "{name}";
903#[cfg(target_arch = "wasm32")]
904const COMPONENT_ORG: &str = "com.example";
905#[cfg(target_arch = "wasm32")]
906const COMPONENT_VERSION: &str = "0.1.0";
907
908#[cfg(target_arch = "wasm32")]
909#[used]
910#[unsafe(link_section = ".greentic.wasi")]
911static WASI_TARGET_MARKER: [u8; 13] = *b"wasm32-wasip2";
912
913#[cfg(target_arch = "wasm32")]
914struct Component;
915
916#[cfg(target_arch = "wasm32")]
917impl node::Guest for Component {{
918    // Component metadata advertised to host/operator tooling.
919    // Extend here when you add more operations or capability declarations.
920    fn describe() -> node::ComponentDescriptor {{
921        let input_schema_cbor = input_schema_cbor();
922        let output_schema_cbor = output_schema_cbor();
923        let mut ops = vec![
924{user_describe_ops}
925        ];
926        ops.extend(vec![
927            node::Op {{
928                name: "qa-spec".to_string(),
929                summary: Some("Return QA spec for requested mode".to_string()),
930                input: node::IoSchema {{
931                    schema: node::SchemaSource::InlineCbor(input_schema_cbor.clone()),
932                    content_type: "application/cbor".to_string(),
933                    schema_version: None,
934                }},
935                output: node::IoSchema {{
936                    schema: node::SchemaSource::InlineCbor(output_schema_cbor.clone()),
937                    content_type: "application/cbor".to_string(),
938                    schema_version: None,
939                }},
940                examples: Vec::new(),
941            }},
942            node::Op {{
943                name: "apply-answers".to_string(),
944                summary: Some("Apply QA answers and optionally return config override".to_string()),
945                input: node::IoSchema {{
946                    schema: node::SchemaSource::InlineCbor(input_schema_cbor.clone()),
947                    content_type: "application/cbor".to_string(),
948                    schema_version: None,
949                }},
950                output: node::IoSchema {{
951                    schema: node::SchemaSource::InlineCbor(output_schema_cbor.clone()),
952                    content_type: "application/cbor".to_string(),
953                    schema_version: None,
954                }},
955                examples: Vec::new(),
956            }},
957            node::Op {{
958                name: "i18n-keys".to_string(),
959                summary: Some("Return i18n keys referenced by QA/setup".to_string()),
960                input: node::IoSchema {{
961                    schema: node::SchemaSource::InlineCbor(input_schema_cbor.clone()),
962                    content_type: "application/cbor".to_string(),
963                    schema_version: None,
964                }},
965                output: node::IoSchema {{
966                    schema: node::SchemaSource::InlineCbor(output_schema_cbor),
967                    content_type: "application/cbor".to_string(),
968                    schema_version: None,
969                }},
970                examples: Vec::new(),
971            }},
972        ]);
973        node::ComponentDescriptor {{
974            name: COMPONENT_NAME.to_string(),
975            version: COMPONENT_VERSION.to_string(),
976            summary: Some(format!("Greentic component {{COMPONENT_NAME}}")),
977            capabilities: Vec::new(),
978            ops,
979            schemas: Vec::new(),
980            setup: None,
981        }}
982    }}
983
984    // Single ABI entrypoint. Keep this dispatcher model intact.
985    // Extend behavior by adding/adjusting operation branches in `run_component_cbor`.
986    fn invoke(
987        operation: String,
988        envelope: node::InvocationEnvelope,
989    ) -> Result<node::InvocationResult, node::NodeError> {{
990        let output = run_component_cbor(&operation, envelope.payload_cbor);
991        Ok(node::InvocationResult {{
992            ok: true,
993            output_cbor: output,
994            output_metadata_cbor: None,
995        }})
996    }}
997}}
998
999#[cfg(target_arch = "wasm32")]
1000greentic_interfaces_guest::export_component_v060!(Component);
1001
1002// Default user-operation implementation.
1003// Replace this with domain logic for your component.
1004pub fn handle_message(operation: &str, input: &str) -> String {{
1005    format!("{{COMPONENT_NAME}}::{{operation}} => {{}}", input.trim())
1006}}
1007
1008#[cfg(target_arch = "wasm32")]
1009fn encode_cbor<T: serde::Serialize>(value: &T) -> Vec<u8> {{
1010    canonical::to_canonical_cbor_allow_floats(value).expect("encode cbor")
1011}}
1012
1013#[cfg(target_arch = "wasm32")]
1014// Accept canonical CBOR first, then fall back to JSON for local debugging.
1015fn parse_payload(input: &[u8]) -> serde_json::Value {{
1016    if let Ok(value) = canonical::from_cbor(input) {{
1017        return value;
1018    }}
1019    serde_json::from_slice(input).unwrap_or_else(|_| serde_json::json!({{}}))
1020}}
1021
1022#[cfg(target_arch = "wasm32")]
1023// Keep ingress compatibility: default/setup/install -> setup, update/upgrade -> update.
1024fn normalized_mode(payload: &serde_json::Value) -> qa::NormalizedMode {{
1025    let mode = payload
1026        .get("mode")
1027        .and_then(|v| v.as_str())
1028        .or_else(|| payload.get("operation").and_then(|v| v.as_str()))
1029        .unwrap_or("setup");
1030    qa::normalize_mode(mode).unwrap_or(qa::NormalizedMode::Setup)
1031}}
1032
1033#[cfg(target_arch = "wasm32")]
1034// Minimal schema for generic operation input.
1035// Extend these schemas when you harden operation contracts.
1036fn input_schema() -> SchemaIr {{
1037    SchemaIr::Object {{
1038        properties: BTreeMap::from([(
1039            "input".to_string(),
1040            SchemaIr::String {{
1041                min_len: Some(0),
1042                max_len: None,
1043                regex: None,
1044                format: None,
1045            }},
1046        )]),
1047        required: vec!["input".to_string()],
1048        additional: AdditionalProperties::Allow,
1049    }}
1050}}
1051
1052#[cfg(target_arch = "wasm32")]
1053fn output_schema() -> SchemaIr {{
1054    SchemaIr::Object {{
1055        properties: BTreeMap::from([(
1056            "message".to_string(),
1057            SchemaIr::String {{
1058                min_len: Some(0),
1059                max_len: None,
1060                regex: None,
1061                format: None,
1062            }},
1063        )]),
1064        required: vec!["message".to_string()],
1065        additional: AdditionalProperties::Allow,
1066    }}
1067}}
1068
1069#[cfg(target_arch = "wasm32")]
1070#[allow(dead_code)]
1071fn config_schema() -> SchemaIr {{
1072    {config_schema_rust}
1073}}
1074
1075#[cfg(target_arch = "wasm32")]
1076#[allow(dead_code)]
1077fn component_info() -> ComponentInfo {{
1078    ComponentInfo {{
1079        id: format!("{{COMPONENT_ORG}}.{{COMPONENT_NAME}}"),
1080        version: COMPONENT_VERSION.to_string(),
1081        role: "tool".to_string(),
1082        display_name: Some(I18nText::new("component.display_name", Some(COMPONENT_NAME.to_string()))),
1083    }}
1084}}
1085
1086#[cfg(target_arch = "wasm32")]
1087fn input_schema_cbor() -> Vec<u8> {{
1088    encode_cbor(&input_schema())
1089}}
1090
1091#[cfg(target_arch = "wasm32")]
1092fn output_schema_cbor() -> Vec<u8> {{
1093    encode_cbor(&output_schema())
1094}}
1095
1096#[cfg(target_arch = "wasm32")]
1097// Central operation dispatcher.
1098// This is the primary extension point for new operations.
1099fn run_component_cbor(operation: &str, input: Vec<u8>) -> Vec<u8> {{
1100    let value = parse_payload(&input);
1101    let output = match operation {{
1102        "qa-spec" => {{
1103            let mode = normalized_mode(&value);
1104            qa::qa_spec_json(mode)
1105        }}
1106        "apply-answers" => {{
1107            let mode = normalized_mode(&value);
1108            qa::apply_answers(mode, &value)
1109        }}
1110        "i18n-keys" => serde_json::Value::Array(
1111            qa::i18n_keys()
1112                .into_iter()
1113                .map(serde_json::Value::String)
1114                .collect(),
1115        ),
1116        _ => {{
1117            let op_name = value
1118                .get("operation")
1119                .and_then(|v| v.as_str())
1120                .unwrap_or(operation);
1121            let input_text = value
1122                .get("input")
1123                .and_then(|v| v.as_str())
1124                .map(ToOwned::to_owned)
1125                .unwrap_or_else(|| value.to_string());
1126            serde_json::json!({{
1127                "message": handle_message(op_name, &input_text)
1128            }})
1129        }}
1130    }};
1131    encode_cbor(&output)
1132}}
1133"#,
1134        name = context.name,
1135        user_describe_ops = user_describe_ops
1136    )
1137}
1138
1139fn render_lib_user_describe_ops(context: &WizardContext) -> String {
1140    context
1141        .user_operations
1142        .iter()
1143        .map(|name| {
1144            format!(
1145                r#"            node::Op {{
1146                name: "{name}".to_string(),
1147                summary: Some("Handle a single message input".to_string()),
1148                input: node::IoSchema {{
1149                    schema: node::SchemaSource::InlineCbor(input_schema_cbor.clone()),
1150                    content_type: "application/cbor".to_string(),
1151                    schema_version: None,
1152                }},
1153                output: node::IoSchema {{
1154                    schema: node::SchemaSource::InlineCbor(output_schema_cbor.clone()),
1155                    content_type: "application/cbor".to_string(),
1156                    schema_version: None,
1157                }},
1158                examples: Vec::new(),
1159            }}"#,
1160                name = name
1161            )
1162        })
1163        .collect::<Vec<_>>()
1164        .join(",\n")
1165}
1166
1167fn render_qa_rs() -> String {
1168    r#"use greentic_types::i18n_text::I18nText;
1169use greentic_types::schemas::component::v0_6_0::{QaMode, Question};
1170use serde_json::{json, Value as JsonValue};
1171
1172// Internal normalized lifecycle semantics used by scaffolded QA operations.
1173// Input compatibility accepts legacy/provision aliases via `normalize_mode`.
1174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1175pub enum NormalizedMode {
1176    Setup,
1177    Update,
1178    Remove,
1179}
1180
1181impl NormalizedMode {
1182    pub fn as_str(self) -> &'static str {
1183        match self {
1184            Self::Setup => "setup",
1185            Self::Update => "update",
1186            Self::Remove => "remove",
1187        }
1188    }
1189}
1190
1191// Compatibility mapping for mode strings from operator/flow payloads.
1192pub fn normalize_mode(raw: &str) -> Option<NormalizedMode> {
1193    match raw {
1194        "default" | "setup" | "install" => Some(NormalizedMode::Setup),
1195        "update" | "upgrade" => Some(NormalizedMode::Update),
1196        "remove" => Some(NormalizedMode::Remove),
1197        _ => None,
1198    }
1199}
1200
1201// Primary QA authoring entrypoint.
1202// Extend question sets here for your real setup/update/remove requirements.
1203pub fn qa_spec_json(mode: NormalizedMode) -> JsonValue {
1204    let (title_key, description_key, questions) = match mode {
1205        NormalizedMode::Setup => (
1206            "qa.install.title",
1207            Some("qa.install.description"),
1208            vec![
1209                question("api_key", "qa.field.api_key.label", "qa.field.api_key.help", true),
1210                question("region", "qa.field.region.label", "qa.field.region.help", true),
1211                question(
1212                    "webhook_base_url",
1213                    "qa.field.webhook_base_url.label",
1214                    "qa.field.webhook_base_url.help",
1215                    true,
1216                ),
1217                question("enabled", "qa.field.enabled.label", "qa.field.enabled.help", false),
1218            ],
1219        ),
1220        NormalizedMode::Update => (
1221            "qa.update.title",
1222            Some("qa.update.description"),
1223            vec![
1224                question("api_key", "qa.field.api_key.label", "qa.field.api_key.help", false),
1225                question("region", "qa.field.region.label", "qa.field.region.help", false),
1226                question(
1227                    "webhook_base_url",
1228                    "qa.field.webhook_base_url.label",
1229                    "qa.field.webhook_base_url.help",
1230                    false,
1231                ),
1232                question("enabled", "qa.field.enabled.label", "qa.field.enabled.help", false),
1233            ],
1234        ),
1235        NormalizedMode::Remove => (
1236            "qa.remove.title",
1237            Some("qa.remove.description"),
1238            vec![question(
1239                "confirm_remove",
1240                "qa.field.confirm_remove.label",
1241                "qa.field.confirm_remove.help",
1242                true,
1243            )],
1244        ),
1245    };
1246
1247    json!({
1248        "mode": match mode {
1249            NormalizedMode::Setup => QaMode::Setup,
1250            NormalizedMode::Update => QaMode::Update,
1251            NormalizedMode::Remove => QaMode::Remove,
1252        },
1253        "title": I18nText::new(title_key, None),
1254        "description": description_key.map(|key| I18nText::new(key, None)),
1255        "questions": questions,
1256        "defaults": {}
1257    })
1258}
1259
1260fn question(id: &str, label_key: &str, help_key: &str, required: bool) -> Question {
1261    serde_json::from_value(json!({
1262        "id": id,
1263        "label": I18nText::new(label_key, None),
1264        "help": I18nText::new(help_key, None),
1265        "error": null,
1266        "kind": { "type": "text" },
1267        "required": required,
1268        "default": null
1269    }))
1270    .expect("question should deserialize")
1271}
1272
1273// Used by `i18n-keys` operation and contract checks in operator.
1274pub fn i18n_keys() -> Vec<String> {
1275    crate::i18n::all_keys()
1276}
1277
1278// Apply answers and return operator-friendly base shape:
1279// { ok, config?, warnings, errors, ...optional metadata }
1280// Extend this method for domain validation rules and config patching.
1281pub fn apply_answers(mode: NormalizedMode, payload: &JsonValue) -> JsonValue {
1282    let answers = payload.get("answers").cloned().unwrap_or_else(|| json!({}));
1283    let current_config = payload
1284        .get("current_config")
1285        .cloned()
1286        .unwrap_or_else(|| json!({}));
1287
1288    let mut errors = Vec::new();
1289    match mode {
1290        NormalizedMode::Setup => {
1291            for key in ["api_key", "region", "webhook_base_url"] {
1292                if answers.get(key).and_then(|v| v.as_str()).is_none() {
1293                    errors.push(json!({
1294                        "key": "qa.error.required",
1295                        "msg_key": "qa.error.required",
1296                        "fields": [key]
1297                    }));
1298                }
1299            }
1300        }
1301        NormalizedMode::Remove => {
1302            if answers
1303                .get("confirm_remove")
1304                .and_then(|v| v.as_str())
1305                .map(|v| v != "true")
1306                .unwrap_or(true)
1307            {
1308                errors.push(json!({
1309                    "key": "qa.error.remove_confirmation",
1310                    "msg_key": "qa.error.remove_confirmation",
1311                    "fields": ["confirm_remove"]
1312                }));
1313            }
1314        }
1315        NormalizedMode::Update => {}
1316    }
1317
1318    if !errors.is_empty() {
1319        return json!({
1320            "ok": false,
1321            "warnings": [],
1322            "errors": errors,
1323            "meta": {
1324                "mode": mode.as_str(),
1325                "version": "v1"
1326            }
1327        });
1328    }
1329
1330    let mut config = match current_config {
1331        JsonValue::Object(map) => map,
1332        _ => serde_json::Map::new(),
1333    };
1334    if let JsonValue::Object(map) = answers {
1335        for (key, value) in map {
1336            config.insert(key, value);
1337        }
1338    }
1339    if mode == NormalizedMode::Remove {
1340        config.insert("enabled".to_string(), JsonValue::Bool(false));
1341    }
1342
1343    json!({
1344        "ok": true,
1345        "config": config,
1346        "warnings": [],
1347        "errors": [],
1348        "meta": {
1349            "mode": mode.as_str(),
1350            "version": "v1"
1351        },
1352        "audit": {
1353            "reasons": ["qa.apply_answers"],
1354            "timings_ms": {}
1355        }
1356    })
1357}
1358"#
1359    .to_string()
1360}
1361
1362#[allow(dead_code)]
1363fn render_descriptor_rs(context: &WizardContext) -> String {
1364    let _ = context;
1365    String::new()
1366}
1367
1368#[allow(dead_code)]
1369fn render_capability_list(capabilities: &[String]) -> String {
1370    let _ = capabilities;
1371    "&[]".to_string()
1372}
1373
1374#[allow(dead_code)]
1375fn render_schema_rs() -> String {
1376    r#"use std::collections::BTreeMap;
1377
1378use greentic_types::cbor::canonical;
1379use greentic_types::schemas::common::schema_ir::{AdditionalProperties, SchemaIr};
1380
1381pub fn input_schema() -> SchemaIr {
1382    object_schema(vec![(
1383        "message",
1384        SchemaIr::String {
1385            min_len: Some(1),
1386            max_len: Some(1024),
1387            regex: None,
1388            format: None,
1389        },
1390    )])
1391}
1392
1393pub fn output_schema() -> SchemaIr {
1394    object_schema(vec![(
1395        "result",
1396        SchemaIr::String {
1397            min_len: Some(1),
1398            max_len: Some(1024),
1399            regex: None,
1400            format: None,
1401        },
1402    )])
1403}
1404
1405pub fn config_schema() -> SchemaIr {
1406    object_schema(vec![("enabled", SchemaIr::Bool)])
1407}
1408
1409pub fn input_schema_cbor() -> Vec<u8> {
1410    canonical::to_canonical_cbor_allow_floats(&input_schema()).unwrap_or_default()
1411}
1412
1413pub fn output_schema_cbor() -> Vec<u8> {
1414    canonical::to_canonical_cbor_allow_floats(&output_schema()).unwrap_or_default()
1415}
1416
1417pub fn config_schema_cbor() -> Vec<u8> {
1418    canonical::to_canonical_cbor_allow_floats(&config_schema()).unwrap_or_default()
1419}
1420
1421fn object_schema(props: Vec<(&str, SchemaIr)>) -> SchemaIr {
1422    let mut properties = BTreeMap::new();
1423    let mut required = Vec::new();
1424    for (name, schema) in props {
1425        properties.insert(name.to_string(), schema);
1426        required.push(name.to_string());
1427    }
1428    SchemaIr::Object {
1429        properties,
1430        required,
1431        additional: AdditionalProperties::Forbid,
1432    }
1433}
1434"#
1435    .to_string()
1436}
1437
1438#[allow(dead_code)]
1439fn render_runtime_rs() -> String {
1440    r#"use std::collections::BTreeMap;
1441
1442use greentic_types::cbor::canonical;
1443use serde_json::Value as JsonValue;
1444
1445pub fn run(input: Vec<u8>, state: Vec<u8>) -> (Vec<u8>, Vec<u8>) {
1446    let input_map = decode_map(&input);
1447    let message = input_map
1448        .get("message")
1449        .and_then(|value| value.as_str())
1450        .unwrap_or("ok");
1451    let mut output = BTreeMap::new();
1452    output.insert(
1453        "result".to_string(),
1454        JsonValue::String(format!("processed: {message}")),
1455    );
1456    let output_cbor = canonical::to_canonical_cbor_allow_floats(&output).unwrap_or_default();
1457    let state_cbor = canonicalize_or_empty(&state);
1458    (output_cbor, state_cbor)
1459}
1460
1461fn canonicalize_or_empty(bytes: &[u8]) -> Vec<u8> {
1462    let empty = || {
1463        canonical::to_canonical_cbor_allow_floats(&BTreeMap::<String, JsonValue>::new())
1464            .unwrap_or_default()
1465    };
1466    if bytes.is_empty() {
1467        return empty();
1468    }
1469    let value: JsonValue = match canonical::from_cbor(bytes) {
1470        Ok(value) => value,
1471        Err(_) => return empty(),
1472    };
1473    canonical::to_canonical_cbor_allow_floats(&value).unwrap_or_default()
1474}
1475
1476fn decode_map(bytes: &[u8]) -> BTreeMap<String, JsonValue> {
1477    if bytes.is_empty() {
1478        return BTreeMap::new();
1479    }
1480    let value: JsonValue = match canonical::from_cbor(bytes) {
1481        Ok(value) => value,
1482        Err(_) => return BTreeMap::new(),
1483    };
1484    let JsonValue::Object(map) = value else {
1485        return BTreeMap::new();
1486    };
1487    map.into_iter().collect()
1488}
1489"#
1490    .to_string()
1491}
1492
1493fn render_i18n_rs() -> String {
1494    r#"use std::collections::BTreeMap;
1495use std::sync::OnceLock;
1496
1497use crate::i18n_bundle::{unpack_locales_from_cbor, LocaleBundle};
1498
1499// Generated by build.rs: static embedded CBOR translation bundle.
1500include!(concat!(env!("OUT_DIR"), "/i18n_bundle.rs"));
1501
1502// Decode once for process lifetime.
1503static I18N_BUNDLE: OnceLock<LocaleBundle> = OnceLock::new();
1504
1505fn bundle() -> &'static LocaleBundle {
1506    I18N_BUNDLE.get_or_init(|| unpack_locales_from_cbor(I18N_BUNDLE_CBOR).unwrap_or_default())
1507}
1508
1509// Fallback precedence is deterministic:
1510// exact locale -> base language -> en
1511fn locale_chain(locale: &str) -> Vec<String> {
1512    let normalized = locale.replace('_', "-");
1513    let mut chain = vec![normalized.clone()];
1514    if let Some((base, _)) = normalized.split_once('-') {
1515        chain.push(base.to_string());
1516    }
1517    chain.push("en".to_string());
1518    chain
1519}
1520
1521// Translation lookup function used throughout generated QA/setup code.
1522// Extend by adding pluralization/context handling if your component needs it.
1523pub fn t(locale: &str, key: &str) -> String {
1524    for candidate in locale_chain(locale) {
1525        if let Some(map) = bundle().get(&candidate)
1526            && let Some(value) = map.get(key)
1527        {
1528            return value.clone();
1529        }
1530    }
1531    key.to_string()
1532}
1533
1534// Returns canonical source key list (from `en`).
1535pub fn all_keys() -> Vec<String> {
1536    let Some(en) = bundle().get("en") else {
1537        return Vec::new();
1538    };
1539    en.keys().cloned().collect()
1540}
1541
1542// Returns English dictionary for diagnostics/tests/tools.
1543pub fn en_messages() -> BTreeMap<String, String> {
1544    bundle().get("en").cloned().unwrap_or_default()
1545}
1546"#
1547    .to_string()
1548}
1549
1550fn render_i18n_bundle() -> String {
1551    r#"{
1552  "qa.install.title": "Install configuration",
1553  "qa.install.description": "Provide values for initial provider setup.",
1554  "qa.update.title": "Update configuration",
1555  "qa.update.description": "Adjust existing provider settings.",
1556  "qa.remove.title": "Remove configuration",
1557  "qa.remove.description": "Confirm provider removal settings.",
1558  "qa.field.api_key.label": "API key",
1559  "qa.field.api_key.help": "Secret key used to authenticate provider requests.",
1560  "qa.field.region.label": "Region",
1561  "qa.field.region.help": "Region identifier for the provider account.",
1562  "qa.field.webhook_base_url.label": "Webhook base URL",
1563  "qa.field.webhook_base_url.help": "Public base URL used for webhook callbacks.",
1564  "qa.field.enabled.label": "Enable provider",
1565  "qa.field.enabled.help": "Enable this provider after setup completes.",
1566  "qa.field.confirm_remove.label": "Confirm removal",
1567  "qa.field.confirm_remove.help": "Set to true to allow provider removal.",
1568  "qa.error.required": "One or more required fields are missing.",
1569  "qa.error.remove_confirmation": "Removal requires explicit confirmation."
1570}
1571"#
1572    .to_string()
1573}
1574
1575fn render_i18n_locales_json() -> String {
1576    r#"["ar","ar-AE","ar-DZ","ar-EG","ar-IQ","ar-MA","ar-SA","ar-SD","ar-SY","ar-TN","ay","bg","bn","cs","da","de","el","en-GB","es","et","fa","fi","fr","fr-FR","gn","gu","hi","hr","ht","hu","id","it","ja","km","kn","ko","lo","lt","lv","ml","mr","ms","my","nah","ne","nl","nl-NL","no","pa","pl","pt","qu","ro","ru","si","sk","sr","sv","ta","te","th","tl","tr","uk","ur","vi","zh"]
1577"#
1578    .to_string()
1579}
1580
1581fn render_i18n_bundle_rs() -> String {
1582    r#"use std::collections::BTreeMap;
1583use std::fs;
1584use std::path::Path;
1585
1586use greentic_types::cbor::canonical;
1587
1588// Locale -> (key -> translated message)
1589pub type LocaleBundle = BTreeMap<String, BTreeMap<String, String>>;
1590
1591// Reads `assets/i18n/*.json` locale maps and returns stable BTreeMap ordering.
1592// Extend here if you need stricter file validation rules.
1593pub fn load_locale_files(dir: &Path) -> Result<LocaleBundle, String> {
1594    let mut locales = LocaleBundle::new();
1595    if !dir.exists() {
1596        return Ok(locales);
1597    }
1598    for entry in fs::read_dir(dir).map_err(|err| err.to_string())? {
1599        let entry = entry.map_err(|err| err.to_string())?;
1600        let path = entry.path();
1601        if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
1602            continue;
1603        }
1604        let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
1605            continue;
1606        };
1607        // locales.json is metadata, not a translation dictionary.
1608        if stem == "locales" {
1609            continue;
1610        }
1611        let raw = fs::read_to_string(&path).map_err(|err| err.to_string())?;
1612        let map: BTreeMap<String, String> = serde_json::from_str(&raw).map_err(|err| err.to_string())?;
1613        locales.insert(stem.to_string(), map);
1614    }
1615    Ok(locales)
1616}
1617
1618pub fn pack_locales_to_cbor(locales: &LocaleBundle) -> Result<Vec<u8>, String> {
1619    canonical::to_canonical_cbor_allow_floats(locales).map_err(|err| err.to_string())
1620}
1621
1622#[allow(dead_code)]
1623// Runtime decode helper used by src/i18n.rs.
1624pub fn unpack_locales_from_cbor(bytes: &[u8]) -> Result<LocaleBundle, String> {
1625    canonical::from_cbor(bytes).map_err(|err| err.to_string())
1626}
1627
1628#[cfg(test)]
1629mod tests {
1630    use super::*;
1631
1632    #[test]
1633    fn pack_roundtrip_contains_en() {
1634        let mut locales = LocaleBundle::new();
1635        let mut en = BTreeMap::new();
1636        en.insert("qa.install.title".to_string(), "Install".to_string());
1637        locales.insert("en".to_string(), en);
1638
1639        let cbor = pack_locales_to_cbor(&locales).expect("pack locales");
1640        let decoded = unpack_locales_from_cbor(&cbor).expect("decode locales");
1641        assert!(decoded.contains_key("en"));
1642    }
1643}
1644"#
1645    .to_string()
1646}
1647
1648fn render_build_rs() -> String {
1649    r#"#[path = "src/i18n_bundle.rs"]
1650mod i18n_bundle;
1651
1652use std::env;
1653use std::fs;
1654use std::path::Path;
1655
1656// Build-time embedding pipeline:
1657// 1) Read assets/i18n/*.json
1658// 2) Pack canonical CBOR bundle
1659// 3) Emit OUT_DIR constants included by src/i18n.rs
1660fn main() {
1661    let i18n_dir = Path::new("assets/i18n");
1662    println!("cargo:rerun-if-changed={}", i18n_dir.display());
1663
1664    let locales = i18n_bundle::load_locale_files(i18n_dir)
1665        .unwrap_or_else(|err| panic!("failed to load locale files: {err}"));
1666    let bundle = i18n_bundle::pack_locales_to_cbor(&locales)
1667        .unwrap_or_else(|err| panic!("failed to pack locale bundle: {err}"));
1668
1669    let out_dir = env::var("OUT_DIR").expect("OUT_DIR must be set by cargo");
1670    let bundle_path = Path::new(&out_dir).join("i18n.bundle.cbor");
1671    fs::write(&bundle_path, bundle).expect("write i18n.bundle.cbor");
1672
1673    let rs_path = Path::new(&out_dir).join("i18n_bundle.rs");
1674    fs::write(
1675        &rs_path,
1676        "pub const I18N_BUNDLE_CBOR: &[u8] = include_bytes!(concat!(env!(\"OUT_DIR\"), \"/i18n.bundle.cbor\"));\n",
1677    )
1678    .expect("write i18n_bundle.rs");
1679}
1680"#
1681    .to_string()
1682}
1683
1684fn render_i18n_sh() -> String {
1685    r#"#!/usr/bin/env bash
1686set -euo pipefail
1687
1688ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
1689LOCALES_FILE="$ROOT_DIR/assets/i18n/locales.json"
1690SOURCE_FILE="$ROOT_DIR/assets/i18n/en.json"
1691
1692log() {
1693  printf '[i18n] %s\n' "$*"
1694}
1695
1696fail() {
1697  printf '[i18n] error: %s\n' "$*" >&2
1698  exit 1
1699}
1700
1701ensure_codex() {
1702  if command -v codex >/dev/null 2>&1; then
1703    return
1704  fi
1705  if command -v npm >/dev/null 2>&1; then
1706    log "installing Codex CLI via npm"
1707    npm i -g @openai/codex || fail "failed to install Codex CLI via npm"
1708  elif command -v brew >/dev/null 2>&1; then
1709    log "installing Codex CLI via brew"
1710    brew install codex || fail "failed to install Codex CLI via brew"
1711  else
1712    fail "Codex CLI not found and no supported installer available (npm or brew)"
1713  fi
1714}
1715
1716ensure_codex_login() {
1717  if codex login status >/dev/null 2>&1; then
1718    return
1719  fi
1720  log "Codex login status unavailable or not logged in; starting login flow"
1721  codex login || fail "Codex login failed"
1722}
1723
1724probe_translator() {
1725  command -v greentic-i18n-translator >/dev/null 2>&1 || fail "greentic-i18n-translator not found. Install it and rerun this script."
1726  local help_output
1727  help_output="$(greentic-i18n-translator --help 2>&1 || true)"
1728  [[ -n "$help_output" ]] || fail "unable to inspect greentic-i18n-translator --help"
1729  if ! greentic-i18n-translator translate --help >/dev/null 2>&1; then
1730    fail "translator subcommand 'translate' is required but unavailable"
1731  fi
1732}
1733
1734run_translate() {
1735  while IFS= read -r locale; do
1736    [[ -n "$locale" ]] || continue
1737    log "translating locale: $locale"
1738    greentic-i18n-translator translate \
1739      --langs "$locale" \
1740      --en "$SOURCE_FILE" || fail "translate failed for locale $locale"
1741  done < <(python3 - "$LOCALES_FILE" <<'PY'
1742import json
1743import sys
1744with open(sys.argv[1], 'r', encoding='utf-8') as f:
1745    data = json.load(f)
1746for locale in data:
1747    if locale != "en":
1748        print(locale)
1749PY
1750)
1751}
1752
1753run_validate_per_locale() {
1754  local failed=0
1755  while IFS= read -r locale; do
1756    [[ -n "$locale" ]] || continue
1757    if ! greentic-i18n-translator validate --langs "$locale" --en "$SOURCE_FILE"; then
1758      log "validate failed for locale: $locale"
1759      failed=1
1760    fi
1761  done < <(python3 - "$LOCALES_FILE" <<'PY'
1762import json
1763import sys
1764with open(sys.argv[1], 'r', encoding='utf-8') as f:
1765    data = json.load(f)
1766for locale in data:
1767    if locale != "en":
1768        print(locale)
1769PY
1770)
1771  return "$failed"
1772}
1773
1774run_status_per_locale() {
1775  local failed=0
1776  while IFS= read -r locale; do
1777    [[ -n "$locale" ]] || continue
1778    if ! greentic-i18n-translator status --langs "$locale" --en "$SOURCE_FILE"; then
1779      log "status failed for locale: $locale"
1780      failed=1
1781    fi
1782  done < <(python3 - "$LOCALES_FILE" <<'PY'
1783import json
1784import sys
1785with open(sys.argv[1], 'r', encoding='utf-8') as f:
1786    data = json.load(f)
1787for locale in data:
1788    if locale != "en":
1789        print(locale)
1790PY
1791)
1792  return "$failed"
1793}
1794
1795run_optional_checks() {
1796  if greentic-i18n-translator validate --help >/dev/null 2>&1; then
1797    log "running translator validate"
1798    if ! run_validate_per_locale; then
1799      fail "translator validate failed"
1800    fi
1801  else
1802    log "warning: translator validate command not available; skipping"
1803  fi
1804  if greentic-i18n-translator status --help >/dev/null 2>&1; then
1805    log "running translator status"
1806    run_status_per_locale || fail "translator status failed"
1807  else
1808    log "warning: translator status command not available; skipping"
1809  fi
1810}
1811
1812[[ -f "$LOCALES_FILE" ]] || fail "missing locales file: $LOCALES_FILE"
1813[[ -f "$SOURCE_FILE" ]] || fail "missing source locale file: $SOURCE_FILE"
1814
1815ensure_codex
1816ensure_codex_login
1817probe_translator
1818run_translate
1819run_optional_checks
1820log "translations updated. Run cargo build to embed translations into WASM"
1821"#
1822    .to_string()
1823}
1824
1825#[allow(dead_code)]
1826fn bytes_literal(bytes: &[u8]) -> String {
1827    if bytes.is_empty() {
1828        return "&[]".to_string();
1829    }
1830    let rendered = bytes
1831        .iter()
1832        .map(|b| format!("0x{b:02x}"))
1833        .collect::<Vec<_>>()
1834        .join(", ");
1835    format!("&[{rendered}]")
1836}
1837
1838#[cfg(test)]
1839mod tests {
1840    use super::*;
1841
1842    #[test]
1843    fn encodes_answers_cbor() {
1844        let json = serde_json::json!({"b": 1, "a": 2});
1845        let cbor = canonical::to_canonical_cbor_allow_floats(&json).unwrap();
1846        assert!(!cbor.is_empty());
1847    }
1848}