offline-cli 0.3.3

The Offline Protocol developer CLI
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
//! `offline create`: scaffold from a workflow, template, or prompt.
//!
//! Example applications from offline-app-examples (full React Native apps with
//! native projects and vendored mesh/ui packages):
//!
//! ```text
//! offline create orderup --name my-kitchen
//! offline create --template stocksync --dir ./stocksync-demo
//! offline create cowrite -y --name cowrite-lab --dir ./cowrite-lab
//! ```

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use clap::Args;
use offline_registry::{normalize_platform, Registry};
use serde_json::json;

use crate::commands::post_generate::{self, PostGenerateMode};
use crate::commands::react_native_shell;
use crate::config::storage::CliConfig;
use crate::output;

#[derive(Args)]
pub struct CreateArgs {
    /// Workflow (e.g. offline-social-network) or template (e.g. nextjs-social, orderup).
    /// Omit and use --prompt to plan from a description, or pick a framework interactively.
    pub target: Option<String>,
    /// Same as positional target: starter template (e.g. orderup, stocksync, cowrite).
    #[arg(long, conflicts_with = "target")]
    pub template: Option<String>,
    /// Plan from a natural-language description instead of naming a workflow
    #[arg(long, conflicts_with = "target")]
    pub prompt: Option<String>,
    /// Project name (defaults to the target directory name)
    #[arg(long)]
    pub name: Option<String>,
    /// Target platform: nextjs | react-vite | react-native
    #[arg(long)]
    pub platform: Option<String>,
    /// Output directory (defaults to ./<name>)
    #[arg(long)]
    pub dir: Option<PathBuf>,
    /// Template variable override, repeatable: --var app_id=app_123
    #[arg(long = "var", value_parser = parse_key_val)]
    pub vars: Vec<(String, String)>,
    /// Non-interactive: accept defaults, fail on missing required input
    #[arg(long, short = 'y')]
    pub yes: bool,
    /// Output JSON (implies --yes)
    #[arg(long)]
    pub json: bool,
    /// Skip auto-generating android/ and ios/ for React Native templates
    #[arg(long)]
    pub skip_native_shell: bool,
    /// Enable mesh SDK (peer discovery, BLE/internet messaging). React Native only.
    #[arg(long, conflicts_with = "no_mesh")]
    pub mesh: bool,
    /// Disable mesh SDK when scaffolding React Native (default).
    #[arg(long, conflicts_with = "mesh")]
    pub no_mesh: bool,
    /// Enable Proof of Location (@offline-protocol/pol), separate from Offline ID. React Native only.
    #[arg(long, conflicts_with = "no_pol")]
    pub pol: bool,
    /// Disable PoL when scaffolding (default).
    #[arg(long, conflicts_with = "pol")]
    pub no_pol: bool,
    /// Skip auto-running npm install / dev server after scaffold
    #[arg(long)]
    pub skip_setup: bool,
}

fn parse_key_val(s: &str) -> Result<(String, String), String> {
    s.split_once('=')
        .map(|(k, v)| (k.trim().to_string(), v.to_string()))
        .ok_or_else(|| format!("expected key=value, got `{s}`"))
}

pub async fn run(args: CreateArgs) -> Result<()> {
    let non_interactive = args.yes || args.json;

    let registry = Registry::load_default()?;

    let platform = args
        .platform
        .as_deref()
        .map(|p| {
            normalize_platform(p).ok_or_else(|| {
                anyhow::anyhow!("unknown platform `{p}` (nextjs | react-vite | react-native)")
            })
        })
        .transpose()?;

    let (template_name, plan, workflow_name) = if let Some(prompt) = &args.prompt {
        let plan = registry.plan(prompt, platform.as_deref())?;
        let template = plan.template.clone().with_context(|| {
            format!(
                "workflow `{}` has no starter template for platform `{}` yet",
                plan.workflow, plan.platform
            )
        })?;
        (template, Some(plan), None)
    } else if let Some(target) = args.target.as_deref().or(args.template.as_deref()) {
        resolve_target(&registry, target, platform.as_deref())?
    } else if non_interactive {
        let platform = platform.as_deref().ok_or_else(|| {
            anyhow::anyhow!("--platform is required with --yes/--json when no target")
        })?;
        let template = template_for_platform(platform)?;
        (template.to_string(), None, None)
    } else {
        let framework = pick_framework_interactively()?;
        let template = if framework == "react-native" {
            pick_react_native_starter_interactively(&registry)?
        } else {
            template_for_platform(&framework)?.to_string()
        };
        (template, None, None)
    };

    let template = registry
        .template(&template_name)
        .expect("resolved template exists")
        .clone();

    let mesh_enabled = resolve_mesh_enabled(&args, &template)?;
    let pol_enabled = resolve_pol_enabled(&args, &template)?;

    // Only starters that talk to hosted services need an account; local BLE
    // mesh starters scaffold without one.
    let needs_login = template.requires_login;
    if needs_login {
        crate::auth::login::ensure_logged_in(!non_interactive).await?;
    } else if !args.json && !CliConfig::load()?.has_api_credentials() {
        output::note(&format!(
            "`{}` runs without hosted services, so no login is needed. \
Run `offline login` later if you add Offline ID or hosted telemetry.",
            template.name
        ));
    }

    let name = match (&args.name, &args.dir) {
        (Some(n), _) => n.clone(),
        (None, Some(dir)) => dir
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| "offline-app".to_string()),
        (None, None) if non_interactive => bail!("--name is required with --yes/--json"),
        (None, None) => dialoguer::Input::new()
            .with_prompt("Project name")
            .default("my-offline-app".to_string())
            .interact_text()?,
    };
    let name = slugify(&name);
    let target_dir = args.dir.clone().unwrap_or_else(|| PathBuf::from(&name));

    if needs_login {
        let mut cli_config = CliConfig::load()?;
        crate::commands::setup::setup_for_create(
            &mut cli_config,
            &name,
            mesh_enabled,
            pol_enabled,
            !non_interactive,
        )
        .await?;
    }
    let config_app_id = cli_config_app_id();
    let mut vars: BTreeMap<String, String> = args.vars.iter().cloned().collect();
    if let Some(legacy) = vars.remove("project_id") {
        vars.entry("app_id".to_string()).or_insert(legacy);
    }
    vars.insert(
        "enable_mesh".to_string(),
        if mesh_enabled { "true" } else { "false" }.to_string(),
    );
    vars.insert(
        "enable_pol".to_string(),
        if pol_enabled { "true" } else { "false" }.to_string(),
    );
    if let Some(wf) = workflow_name {
        vars.insert("workflow".to_string(), wf);
    } else if let Some(plan) = &plan {
        vars.insert("workflow".to_string(), plan.workflow.clone());
    }
    for v in &template.variables {
        if vars.contains_key(&v.name) {
            continue;
        }
        if !mesh_enabled && mesh_only_variable(&v.name) {
            continue;
        }
        let fallback = variable_default(v, &name, config_app_id.as_deref());
        match fallback {
            Some(value) if non_interactive => {
                if mesh_enabled || !mesh_only_variable(&v.name) {
                    vars.insert(v.name.clone(), value);
                }
            }
            None if non_interactive
                && v.required
                && (mesh_enabled || !mesh_only_variable(&v.name)) =>
            {
                bail!(
                    "missing required variable `{}` (use --var {}=...)",
                    v.name,
                    v.name
                )
            }
            _ if non_interactive => {}
            fallback => {
                let value = prompt_template_variable(v, fallback, config_app_id.as_deref())?;
                vars.insert(v.name.clone(), value);
            }
        }
    }

    if !non_interactive
        && !confirm_project_summary(&name, &target_dir, &template, mesh_enabled, pol_enabled)?
    {
        output::note("Cancelled.");
        return Ok(());
    }

    if template.platform == "react-native" {
        vars.insert(
            "rn_module_name".to_string(),
            react_native_shell::rn_module_name(&name),
        );
    }

    let generated =
        offline_generator::generate(&registry, &template.name, &target_dir, &name, &vars)?;

    let mut extra_files = Vec::new();
    let mut native_shells_added = false;
    let mut native_shell_warning: Option<String> = None;
    if template.platform == "react-native" && !args.skip_native_shell {
        let module = react_native_shell::rn_module_name(&name);
        match react_native_shell::add_native_shells(&target_dir, &module) {
            Ok(()) => {
                native_shells_added = true;
                extra_files.push("android/".to_string());
                extra_files.push("ios/".to_string());
            }
            Err(err) => {
                native_shell_warning = Some(format!("{err:#}"));
            }
        }
    }

    if template.platform == "react-native" && target_dir.join("android").is_dir() {
        let module = react_native_shell::rn_module_name(&name);
        if let Err(err) = react_native_shell::patch_network_binding(&target_dir, &module) {
            output::warn(&format!(
                "Android Wi‑Fi network binding not applied: {err:#}"
            ));
        }
    }

    if mesh_enabled && target_dir.join("ios").is_dir() {
        let module = react_native_shell::rn_module_name(&name);
        if let Err(err) = react_native_shell::patch_mesh_native_permissions(&target_dir, &module) {
            output::warn(&format!("Mesh native setup not applied: {err:#}"));
            output::warn(
                "Ensure ios/Podfile uses `use_native_modules!` (MeshSdk autolinks from \
                 @offline-protocol/mesh-sdk), then run `cd ios && pod install`.",
            );
        } else if !args.json {
            output::note(
                "Mesh iOS native module autolinks via use_native_modules!; run `cd ios && pod install` before building.",
            );
        }
    }

    if let Some(plan) = &plan {
        let arch = offline_registry::architecture_markdown(plan);
        let impl_plan = offline_registry::implementation_plan_markdown(plan);
        std::fs::write(target_dir.join("architecture.md"), arch)?;
        std::fs::write(target_dir.join("implementation-plan.md"), impl_plan)?;
        extra_files.push("architecture.md".to_string());
        extra_files.push("implementation-plan.md".to_string());
    }

    if args.json {
        let setup = if args.skip_setup {
            None
        } else {
            Some(run_project_setup(
                &target_dir,
                &generated.post_generate,
                PostGenerateMode::InstallOnly,
            ))
        };
        return output::json(&json!({
            "project": name,
            "dir": target_dir,
            "template": generated.template,
            "workflow": plan.as_ref().map(|p| p.workflow.clone()),
            "filesWritten": ([generated.files_written.clone(), extra_files].concat()),
            "postGenerate": generated.post_generate,
            "notes": generated.notes,
            "nativeShellsAdded": native_shells_added,
            "nativeShellWarning": native_shell_warning,
            "meshEnabled": mesh_enabled,
            "polEnabled": pol_enabled,
            "setup": setup,
        }));
    }

    output::success(&format!(
        "Created {} from `{}` ({} files)",
        target_dir.display(),
        generated.template,
        generated.files_written.len() + extra_files.len()
    ));
    if let Some(plan) = &plan {
        output::note(&format!(
            "workflow: {}, platform: {}, architecture.md and implementation-plan.md written",
            plan.workflow, plan.platform
        ));
    }
    if native_shells_added {
        output::note("Native android/ and ios/ folders added automatically.");
    } else if let Some(warn) = &native_shell_warning {
        output::warn(&format!("Native shells not added: {warn}"));
        output::warn("See README for manual `react-native init` steps.");
    }
    if !generated.notes.is_empty() {
        output::heading("Notes");
        for n in &generated.notes {
            output::warn(n);
        }
    }

    if args.skip_setup {
        output::heading("Next steps");
        println!("  cd {}", target_dir.display());
        for step in &generated.post_generate {
            println!("  {step}");
        }
    } else {
        run_project_setup(
            &target_dir,
            &generated.post_generate,
            PostGenerateMode::Full,
        );
    }
    Ok(())
}

fn run_project_setup(
    target_dir: &Path,
    steps: &[String],
    mode: PostGenerateMode,
) -> serde_json::Value {
    let planned = post_generate::planned_steps(steps, mode);
    if planned.is_empty() {
        return json!({ "ran": [], "skipped": [], "failed": null });
    }

    output::heading("Setting up project");
    for step in &planned {
        output::note(step);
    }

    if mode == PostGenerateMode::Full && template_has_rn_start(steps) {
        output::note(
            "After Metro starts, open another terminal and run `npm run android` or `npm run ios`.",
        );
    }

    let report = post_generate::run(target_dir, steps, mode);

    if let Some(err) = &report.failed {
        output::warn(&format!("Setup stopped: {err}"));
        output::note("Finish manually from the project directory.");
        for step in &report.skipped {
            println!("  {step}");
        }
    }

    json!({
        "ran": report.ran,
        "skipped": report.skipped,
        "failed": report.failed,
    })
}

fn template_has_rn_start(steps: &[String]) -> bool {
    steps
        .iter()
        .any(|s| post_generate::clean_command(s) == "npm start")
}

/// Map a target name to a template: direct template name, or workflow name
/// (+ platform selection when the workflow spans platforms).
fn resolve_target(
    registry: &Registry,
    target: &str,
    platform: Option<&str>,
) -> Result<(String, Option<offline_registry::Plan>, Option<String>)> {
    if registry.template(target).is_some() {
        return Ok((target.to_string(), None, None));
    }
    if let Some(wf) = registry.workflow(target) {
        let platform = match platform {
            Some(p) => p.to_string(),
            None if wf.templates.len() == 1 => {
                wf.templates.keys().next().expect("len checked").clone()
            }
            None => {
                let platforms: Vec<&String> = wf.templates.keys().collect();
                let pick = dialoguer::Select::new()
                    .with_prompt("Platform")
                    .items(&platforms)
                    .default(0)
                    .interact()?;
                platforms[pick].clone()
            }
        };
        let template = wf.templates.get(&platform).with_context(|| {
            format!(
                "workflow `{target}` has no template for `{platform}` (available: {})",
                wf.templates.keys().cloned().collect::<Vec<_>>().join(", ")
            )
        })?;
        return Ok((template.clone(), None, Some(target.to_string())));
    }
    let suggestions = registry.search_workflows(target);
    let hint = suggestions
        .first()
        .map(|h| format!(". Did you mean `{}`?", h.name))
        .unwrap_or_default();
    let example_hint = if registry.template(target).is_none() {
        format!(
            " Example apps: {}.",
            offline_registry::EXAMPLE_APP_TEMPLATE_IDS.join(", ")
        )
    } else {
        String::new()
    };
    bail!(
        "`{target}` is not a workflow or template{hint} \
(see `offline registry list templates` or `offline registry list workflows`){example_hint}"
    )
}

const FRAMEWORKS: &[(&str, &str)] = &[
    ("nextjs", "Next.js"),
    ("react-vite", "React (Vite)"),
    ("react-native", "React Native"),
];

fn pick_framework_interactively() -> Result<String> {
    let labels: Vec<&str> = FRAMEWORKS.iter().map(|(_, label)| *label).collect();
    let pick = dialoguer::Select::new()
        .with_prompt("Which framework?")
        .items(&labels)
        .default(0)
        .interact()?;
    Ok(FRAMEWORKS[pick].0.to_string())
}

fn pick_react_native_starter_interactively(registry: &Registry) -> Result<String> {
    let mut options: Vec<(String, String)> = vec![(
        "react-native-social".to_string(),
        "Offline ID social starter (default)".to_string(),
    )];
    for id in offline_registry::EXAMPLE_APP_TEMPLATE_IDS {
        let meta = registry
            .template(id)
            .unwrap_or_else(|| panic!("example template `{id}` missing"));
        options.push((id.to_string(), meta.title.clone()));
    }
    let labels: Vec<&str> = options.iter().map(|(_, label)| label.as_str()).collect();
    let pick = dialoguer::Select::new()
        .with_prompt("Which React Native starter?")
        .items(&labels)
        .default(0)
        .interact()?;
    Ok(options[pick].0.clone())
}

fn template_for_platform(platform: &str) -> Result<&'static str> {
    match platform {
        "nextjs" => Ok("nextjs-social"),
        "react-vite" => Ok("react-vite-social"),
        "react-native" => Ok("react-native-social"),
        other => bail!("no starter template for platform `{other}`"),
    }
}

fn mesh_only_variable(name: &str) -> bool {
    matches!(name, "mesh_app_id" | "relay_server_url")
}

fn resolve_mesh_enabled(
    args: &CreateArgs,
    template: &offline_registry::TemplateMeta,
) -> Result<bool> {
    if template.platform != "react-native" {
        if args.mesh || args.no_mesh {
            bail!("--mesh and --no-mesh only apply to React Native projects");
        }
        return Ok(false);
    }
    if template.requires_mesh {
        if args.no_mesh {
            let message = format!(
                "`{}` is built on the Mesh SDK throughout; ignoring --no-mesh.",
                template.name
            );
            if args.json {
                eprintln!("warning: {message}");
            } else {
                output::warn(&message);
            }
        }
        return Ok(true);
    }
    if let Some((_, value)) = args.vars.iter().find(|(k, _)| k == "enable_mesh") {
        return Ok(value == "true");
    }
    if args.mesh {
        return Ok(true);
    }
    if args.no_mesh {
        return Ok(false);
    }
    if args.yes || args.json {
        return Ok(false);
    }
    prompt_mesh_interactively()
}

fn prompt_mesh_interactively() -> Result<bool> {
    dialoguer::Confirm::new()
        .with_prompt(
            "Enable mesh capabilities?\n  \
             - Discover and connect to nearby peers over Bluetooth LE\n  \
             - Send encrypted messages over local mesh or internet relay",
        )
        .default(false)
        .interact()
        .map_err(Into::into)
}

fn resolve_pol_enabled(
    args: &CreateArgs,
    template: &offline_registry::TemplateMeta,
) -> Result<bool> {
    if template.platform != "react-native" {
        if args.pol || args.no_pol {
            bail!("--pol and --no-pol only apply to React Native projects");
        }
        return Ok(false);
    }
    if let Some((_, value)) = args.vars.iter().find(|(k, _)| k == "enable_pol") {
        return Ok(value == "true");
    }
    if args.pol {
        return Ok(true);
    }
    if args.no_pol {
        return Ok(false);
    }
    if args.yes || args.json {
        return Ok(false);
    }
    prompt_pol_interactively()
}

fn prompt_pol_interactively() -> Result<bool> {
    dialoguer::Confirm::new()
        .with_prompt(
            "Enable Proof of Location (@offline-protocol/pol)?\n  \
             - Separate from OfflineID; uses the same app id and the JWT from useAuth()\n  \
             - location.verify() and location.commit() on the home screen",
        )
        .default(false)
        .interact()
        .map_err(Into::into)
}

fn confirm_project_summary(
    name: &str,
    target_dir: &Path,
    template: &offline_registry::TemplateMeta,
    mesh_enabled: bool,
    pol_enabled: bool,
) -> Result<bool> {
    output::heading("Project summary");
    println!("  Framework:  {}", template.platform);
    println!("  Template:   {}", template.name);
    println!("  Name:       {name}");
    println!("  Directory:  {}", target_dir.display());
    if template.platform == "react-native" {
        println!(
            "  Mesh:       {}",
            if mesh_enabled { "enabled" } else { "disabled" }
        );
        if !template.example_app {
            println!(
                "  PoL:        {}",
                if pol_enabled { "enabled" } else { "disabled" }
            );
        }
    }
    println!();
    if template.example_app {
        println!("  {}", template.description);
        println!();
        println!("  Includes:");
        println!("    - Vendored packages/mesh and packages/ui from offline-app-examples");
        println!("    - Native android/ and ios/ from the example app");
        println!("    - @offline-protocol/mesh-sdk (AGPL-3.0-only, or a commercial license; review before shipping)");
    } else {
        let sdk = match template.platform.as_str() {
            "react-native" => "id-react-native",
            _ => "id-react",
        };
        println!("  Includes:");
        println!("    - OfflineID login ({sdk} SDK)");
        println!("    - Member directory with username search");
        println!("    - Add friends via connect API");
        if template.platform == "react-native" {
            println!("    - Native android/ + ios/ projects (auto-generated)");
        }
        if mesh_enabled {
            println!("    - Mesh peer discovery (Bluetooth LE)");
            println!("    - Encrypted 1:1 messaging with internet relay fallback");
            println!(
                "    - mesh-sdk (AGPL-3.0-only, or a commercial license; review before shipping)"
            );
        }
        if pol_enabled {
            println!(
                "    - Proof of Location (@offline-protocol/pol): PolProvider and verify/commit UI"
            );
            println!("    - Enable PoL for your app id in the developer portal before testing");
        }
        println!("    - Profile view and profile update page");
    }
    println!();
    dialoguer::Confirm::new()
        .with_prompt("Create this project?")
        .default(true)
        .interact()
        .map_err(Into::into)
}

fn slugify(name: &str) -> String {
    let slug: String = name
        .to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '-' })
        .collect();
    slug.trim_matches('-').replace("--", "-")
}

/// Application ID saved by `offline login` / `offline setup` in `~/.offline/config.json`.
fn cli_config_app_id() -> Option<String> {
    CliConfig::load()
        .ok()
        .and_then(|c| c.effective_app_id())
        .filter(|id| !id.trim().is_empty())
}

/// Default value for a template variable before prompting (or in `--yes` mode).
fn variable_default(
    variable: &offline_registry::TemplateVariable,
    project_slug: &str,
    config_app_id: Option<&str>,
) -> Option<String> {
    if variable.name == "app_id" {
        return config_app_id
            .map(str::to_string)
            .or_else(|| variable.default.clone())
            // Local mesh starters use `app_id` as the mesh identifier; without
            // a login there is no portal id, so default to the project slug.
            .or_else(|| variable.required.then(|| project_slug.to_string()));
    }
    if variable.name == "app_id" && variable.default.as_deref().is_some_and(|d| !d.is_empty()) {
        return variable.default.clone();
    }
    if variable.name == "mesh_app_id" {
        return Some(project_slug.to_string());
    }
    if variable.name == "relay_server_url" {
        return variable
            .default
            .clone()
            .or_else(|| Some("wss://relay.offlineprotocol.com".to_string()));
    }
    variable.default.clone()
}

fn prompt_template_variable(
    variable: &offline_registry::TemplateVariable,
    fallback: Option<String>,
    config_app_id: Option<&str>,
) -> Result<String> {
    if variable.name == "app_id" {
        if let Some(config_id) = config_app_id {
            let use_config = dialoguer::Confirm::new()
                .with_prompt(format!(
                    "Use application ID from your CLI login ({config_id})?"
                ))
                .default(true)
                .interact()?;
            if use_config {
                return Ok(config_id.to_string());
            }
            return dialoguer::Input::new()
                .with_prompt("Enter a custom Offline application ID (leave blank to fill in later)")
                .default(String::new())
                .allow_empty(!variable.required)
                .interact_text()
                .map_err(Into::into);
        }
    }

    dialoguer::Input::new()
        .with_prompt(&variable.prompt)
        .default(fallback.unwrap_or_default())
        .allow_empty(!variable.required)
        .interact_text()
        .map_err(Into::into)
}

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

    fn portal_app_id_var() -> TemplateVariable {
        TemplateVariable {
            name: "app_id".into(),
            prompt: "Portal application id".into(),
            default: Some(String::new()),
            required: false,
        }
    }

    #[test]
    fn variable_default_prefers_cli_config_for_app_id() {
        let var = portal_app_id_var();
        assert_eq!(
            variable_default(&var, "my-app", Some("app_from_config")).as_deref(),
            Some("app_from_config")
        );
    }

    #[test]
    fn variable_default_falls_back_to_template_default_for_app_id() {
        let var = portal_app_id_var();
        assert_eq!(variable_default(&var, "my-app", None).as_deref(), Some(""));
    }

    #[test]
    fn required_mesh_app_id_defaults_to_slug_without_login() {
        let var = TemplateVariable {
            name: "app_id".into(),
            prompt: "Application identifier for the mesh".into(),
            default: None,
            required: true,
        };
        assert_eq!(
            variable_default(&var, "pulse", None).as_deref(),
            Some("pulse")
        );
        assert_eq!(
            variable_default(&var, "pulse", Some("app_cfg")).as_deref(),
            Some("app_cfg")
        );
    }

    #[test]
    fn only_local_mesh_templates_skip_login() {
        let registry = Registry::load_default().unwrap();
        for name in ["react-native-mesh-app", "react-native-mesh-custom-app"] {
            assert!(!registry.template(name).unwrap().requires_login, "{name}");
        }
        for name in [
            "react-native-social",
            "react-native-id-only",
            "nextjs-social",
            "react-vite-social",
        ] {
            assert!(registry.template(name).unwrap().requires_login, "{name}");
        }
    }

    #[test]
    fn mesh_only_variable_names() {
        assert!(mesh_only_variable("mesh_app_id"));
        assert!(mesh_only_variable("relay_server_url"));
        assert!(!mesh_only_variable("app_id"));
    }

    #[test]
    fn example_app_templates_are_registered() {
        let registry = Registry::load_default().unwrap();
        for id in offline_registry::EXAMPLE_APP_TEMPLATE_IDS {
            let t = registry.template(id).expect(id);
            assert!(t.example_app, "{id}");
            assert!(t.requires_mesh, "{id}");
            assert!(!t.requires_login, "{id}");
        }
    }

    #[test]
    fn resolve_target_accepts_example_template_names() {
        let registry = Registry::load_default().unwrap();
        for id in offline_registry::EXAMPLE_APP_TEMPLATE_IDS {
            let (name, _, _) = resolve_target(&registry, id, None).unwrap();
            assert_eq!(name, *id);
        }
    }

    #[test]
    fn unknown_template_name_includes_example_hint() {
        let registry = Registry::load_default().unwrap();
        let err = resolve_target(&registry, "not-a-real-template", None).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("orderup"));
    }

    #[test]
    fn variable_default_uses_slug_for_mesh_app_id() {
        let var = TemplateVariable {
            name: "mesh_app_id".into(),
            prompt: "mesh app id".into(),
            default: None,
            required: true,
        };
        assert_eq!(
            variable_default(&var, "my-offline-app", None).as_deref(),
            Some("my-offline-app")
        );
    }
}