appctl 0.17.3

CLI: sync OpenAPI, databases, and frameworks into LLM tool definitions; chat, run, and HTTP serve.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
//! Guided first-run setup (`appctl setup`).
//!
//! The **portable** tool source is an **OpenAPI** document (file or URL): one contract, any stack.
//! **Framework- and database-specific** sync paths (Flask, Django, `sync --db`, …) are **optional
//! heuristics** for repos that do not have (or do not want to maintain) a spec; they are not a
//! substitute for a published OpenAPI contract when you need spec-accurate HTTP.

use std::{
    fs,
    io::{self, IsTerminal},
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use dialoguer::{Confirm, Input, Select};
use serde_json::Value;

use crate::{
    auth::oauth::{OAuthLoginConfig, OAuthTokenNamespace, login as oauth_login},
    config::{AppConfig, ConfigPaths},
    doctor::{DoctorRunArgs, run_doctor},
    init::{prompt_register_app, refine_app_label_and_description, run_init},
    sync::{SyncRequest, run_sync},
    term::{
        print_flow_header, print_path_row, print_section_title, print_status_success,
        print_status_warn, print_tip,
    },
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SetupSourceChoice {
    AutoDetect,
    OpenApi,
    Database,
    Django,
    Flask,
    Rails,
    Laravel,
    AspNet,
    Strapi,
    Url,
    SkipSync,
    NotSure,
}

impl SetupSourceChoice {
    fn items() -> &'static [&'static str] {
        &[
            "Inspect project folder — find OpenAPI, DB, or framework (start here)",
            "OpenAPI spec: URL (running server) or path to file",
            "Database / datastore connection",
            "Django project",
            "Flask project",
            "Rails project",
            "Laravel project",
            "ASP.NET project",
            "Strapi project",
            "Website / browser-login URL",
            "Skip sync for now (I already have tools or will sync later)",
            "I'm not sure yet",
        ]
    }

    fn from_index(index: usize) -> Self {
        match index {
            0 => Self::AutoDetect,
            1 => Self::OpenApi,
            2 => Self::Database,
            3 => Self::Django,
            4 => Self::Flask,
            5 => Self::Rails,
            6 => Self::Laravel,
            7 => Self::AspNet,
            8 => Self::Strapi,
            9 => Self::Url,
            10 => Self::SkipSync,
            _ => Self::NotSure,
        }
    }

    fn is_http_like(self) -> bool {
        !matches!(
            self,
            Self::AutoDetect | Self::Database | Self::SkipSync | Self::NotSure
        )
    }
}

#[derive(Debug, Clone)]
struct SetupSyncOutcome {
    did_sync: bool,
    doctor_source: Option<SetupSourceChoice>,
}

impl SetupSyncOutcome {
    fn skipped() -> Self {
        Self {
            did_sync: false,
            doctor_source: None,
        }
    }

    fn synced(source: SetupSourceChoice) -> Self {
        Self {
            did_sync: true,
            doctor_source: Some(source),
        }
    }
}

#[derive(Debug, Clone)]
struct DetectedSyncSource {
    label: String,
    source: SetupSourceChoice,
    request: SyncRequest,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SetupMode {
    Full,
    TargetAuthOnly,
    ToolsOnly,
    ProviderOnly,
}

pub async fn run_setup(paths: &ConfigPaths) -> Result<()> {
    paths.ensure()?;
    print_flow_header(
        "setup",
        Some("A guided path from install to a working terminal or web chat"),
    );
    print_app_context(paths)?;

    if !io::stdin().is_terminal() {
        print_non_interactive_setup(paths);
        return Ok(());
    }

    match choose_setup_mode(paths)? {
        SetupMode::Full => {
            ensure_provider(paths).await?;
            ensure_app_identity(paths)?;
            let source = choose_source()?;
            let outcome = maybe_run_sync(paths, source).await?;
            ensure_target_auth(paths, &outcome, false).await?;
            let checks_ok = maybe_run_doctor(paths, outcome).await;
            print_next_steps(paths, checks_ok);
        }
        SetupMode::TargetAuthOnly => {
            print_tip("Auth-only setup does not resync tools or reconfigure the AI provider.");
            ensure_target_auth(paths, &SetupSyncOutcome::skipped(), true).await?;
            let checks_ok = maybe_run_doctor(paths, SetupSyncOutcome::skipped()).await;
            print_next_steps(paths, checks_ok);
        }
        SetupMode::ToolsOnly => {
            let source = choose_source()?;
            let outcome = maybe_run_sync(paths, source).await?;
            let checks_ok = maybe_run_doctor(paths, outcome).await;
            print_next_steps(paths, checks_ok);
        }
        SetupMode::ProviderOnly => {
            ensure_provider(paths).await?;
            print_next_steps(paths, true);
        }
    }
    Ok(())
}

fn choose_setup_mode(paths: &ConfigPaths) -> Result<SetupMode> {
    let config_exists = paths.config.exists();
    let tools_exist = paths.has_synced_artifacts();
    if !config_exists && !tools_exist {
        return Ok(SetupMode::Full);
    }
    print_section_title("Setup scope");
    println!("  Choose the smallest thing you want to change right now.");
    let items = [
        "Full setup (provider, app identity, tools, target auth, checks)",
        "Target app auth only (Bearer, cookie, OAuth profile; no resync)",
        "Tools/sync only (refresh OpenAPI/DB/framework tools)",
        "AI provider only",
    ];
    let index = Select::new()
        .with_prompt("What should setup configure?")
        .items(items)
        .default(1)
        .interact()?;
    Ok(match index {
        1 => SetupMode::TargetAuthOnly,
        2 => SetupMode::ToolsOnly,
        3 => SetupMode::ProviderOnly,
        _ => SetupMode::Full,
    })
}

fn print_app_context(paths: &ConfigPaths) -> Result<()> {
    print_section_title("0. App context");
    let cwd = std::env::current_dir().context("failed to read current working directory")?;
    print_path_row("current directory", &cwd);
    print_path_row("app directory", &paths.root);
    print_path_row("config", &paths.config);
    print_path_row("tools", &paths.tools);

    if dirs::home_dir()
        .map(|h| h.join(".appctl") == paths.root)
        .unwrap_or(false)
    {
        print_tip(
            "Global home app: use this only on purpose. For a project, run setup from the project folder or pass `--app-dir project/.appctl`.",
        );
    } else {
        print_tip(
            "Project app: setup will write config and synced tools under this project’s `.appctl`.",
        );
    }
    Ok(())
}

async fn ensure_provider(paths: &ConfigPaths) -> Result<()> {
    let needs_provider = match AppConfig::load(paths) {
        Ok(config) => config.providers.is_empty(),
        Err(_) => true,
    };

    if needs_provider {
        print_section_title("1. AI provider");
        println!("  appctl needs one AI provider before chat, run, or serve can work.");
        run_init(paths).await?;
    } else {
        print_section_title("1. AI provider");
        print_status_success("provider already configured");
        if Confirm::new()
            .with_prompt("Reconfigure the AI provider now?")
            .default(false)
            .interact()?
        {
            run_init(paths).await?;
        }
    }
    Ok(())
}

fn ensure_app_identity(paths: &ConfigPaths) -> Result<()> {
    print_section_title("App identity");
    refine_app_label_and_description(paths)?;
    prompt_register_app(paths)?;
    Ok(())
}

fn choose_source() -> Result<SetupSourceChoice> {
    print_section_title("2. App tools");
    println!("  appctl needs synced tools so the agent knows what it can do.");
    let items = [
        "Inspect this project and recommend a source",
        "OpenAPI spec URL or file",
        "Database connection",
        "Manual / advanced source list",
        "Skip sync for now",
    ];
    let index = Select::new()
        .with_prompt("What should appctl connect to?")
        .items(items)
        .default(0)
        .interact()?;
    Ok(match index {
        0 => SetupSourceChoice::AutoDetect,
        1 => SetupSourceChoice::OpenApi,
        2 => SetupSourceChoice::Database,
        3 => SetupSourceChoice::NotSure,
        _ => SetupSourceChoice::SkipSync,
    })
}

async fn maybe_run_sync(
    paths: &ConfigPaths,
    source: SetupSourceChoice,
) -> Result<SetupSyncOutcome> {
    match source {
        SetupSourceChoice::AutoDetect => run_auto_detected_sync(paths).await,
        SetupSourceChoice::NotSure => run_not_sure_sync(paths).await,
        _ => run_manual_source_sync(paths, source).await,
    }
}

/// When the user is unsure, explain options instead of jumping straight into a scan.
async fn run_not_sure_sync(paths: &ConfigPaths) -> Result<SetupSyncOutcome> {
    print_section_title("2. App tools — not sure yet");
    tip_if_home_global_appctl(paths);
    print_tip("Scan this directory, or use `--app-dir` for another project’s `.appctl`.");

    let items = [
        "Scan my current directory for sources (OpenAPI / framework / SQLite)",
        "Choose OpenAPI, database, or framework manually",
        "Skip sync for now",
    ];
    let selected = Select::new()
        .with_prompt("What do you want to do?")
        .items(items)
        .default(0)
        .interact()?;

    match selected {
        0 => run_auto_detected_sync(paths).await,
        1 => {
            let manual = choose_manual_source()?;
            run_manual_source_sync(paths, manual).await
        }
        2 => {
            print_status_warn("skipped sync");
            print_tip("Run `appctl sync --help` when you are ready to add tools.");
            Ok(SetupSyncOutcome::skipped())
        }
        _ => unreachable!(),
    }
}

async fn run_manual_source_sync(
    paths: &ConfigPaths,
    source: SetupSourceChoice,
) -> Result<SetupSyncOutcome> {
    if matches!(source, SetupSourceChoice::SkipSync) {
        print_status_warn("skipped sync");
        print_tip("Run `appctl sync --help` when you are ready to add tools.");
        return Ok(SetupSyncOutcome::skipped());
    }

    let force = confirm_replace_existing_tools(paths)?;

    let mut request = SyncRequest {
        force,
        ..Default::default()
    };

    match source {
        SetupSourceChoice::OpenApi => {
            let scan_root = inspection_project_root(paths)?;
            let spec_files = find_openapi_spec_files(&scan_root);
            let default_line = spec_files
                .first()
                .map(|p| openapi_prompt_default_path(p))
                .or_else(|| stored_openapi_url_default(paths));
            if default_line.is_none() {
                print_tip(
                    "No openapi/swagger file found under this project. Use a file path, a live URL (server running), or go back and pick \"Inspect project\".",
                );
            } else if spec_files.is_empty() {
                if let Some(url) = stored_openapi_url_default(paths) {
                    print_tip(&format!(
                        "You already have a synced OpenAPI schema under `.appctl/`. A common live URL is {url} (start the API, then sync)."
                    ));
                }
            }
            request.openapi = Some(prompt_string(
                "OpenAPI: URL or spec file path",
                default_line.as_deref(),
            )?);

            let config = AppConfig::load_or_init(paths)?;
            let target_base_url = config
                .target
                .base_url
                .as_deref()
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .map(str::to_string);
            let target_auth_header = config
                .target
                .auth_header
                .as_deref()
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .map(str::to_string);

            request.base_url = target_base_url.or_else(|| stored_sync_base_url(paths));

            if request.base_url.is_none() {
                request.base_url = prompt_optional("Base URL (optional, for calling the API)")?;
            }

            request.auth_header = if let Some(header) = target_auth_header {
                Some(header)
            } else {
                prompt_auth_header_optional(
                    "Auth header (optional, e.g. Authorization: Bearer env:TOKEN)",
                )?
            };
        }
        SetupSourceChoice::Database => {
            request.db = Some(prompt_string(
                "Database URL, e.g. sqlite:///path/app.db or postgres://...",
                None,
            )?);
        }
        SetupSourceChoice::Django => {
            request.django = Some(prompt_path("Django project root", Some("."))?);
            request.base_url = Some(prompt_string_nonempty(
                "Base URL for HTTP tool calls (your running app)",
                "http://127.0.0.1:8000",
            )?);
        }
        SetupSourceChoice::Flask => {
            request.flask = Some(prompt_path("Flask project root", Some("."))?);
            request.base_url = Some(prompt_string_nonempty(
                "Base URL for HTTP tool calls (your running app)",
                "http://127.0.0.1:5000",
            )?);
        }
        SetupSourceChoice::Rails => {
            request.rails = Some(prompt_path("Rails project root", Some("."))?);
            request.base_url = Some(prompt_string_nonempty(
                "Base URL for HTTP tool calls (your running app)",
                "http://127.0.0.1:3000",
            )?);
        }
        SetupSourceChoice::Laravel => {
            request.laravel = Some(prompt_path("Laravel project root", Some("."))?);
            request.base_url = Some(prompt_string_nonempty(
                "Base URL for HTTP tool calls (your running app)",
                "http://127.0.0.1:8000",
            )?);
        }
        SetupSourceChoice::AspNet => {
            request.aspnet = Some(prompt_path("ASP.NET project root", Some("."))?);
            request.base_url = Some(prompt_string_nonempty(
                "Base URL for HTTP tool calls (your running app)",
                "http://127.0.0.1:5000",
            )?);
        }
        SetupSourceChoice::Strapi => {
            request.strapi = Some(prompt_path("Strapi project root", Some("."))?);
            request.base_url = Some(prompt_string_nonempty(
                "Base URL for HTTP tool calls (your running app)",
                "http://127.0.0.1:1337",
            )?);
        }
        SetupSourceChoice::Url => {
            request.url = Some(prompt_string("Website root URL", None)?);
            request.login_url = prompt_optional("Login page URL (optional)")?;
            request.login_user = prompt_optional("Login username (optional)")?;
            request.login_password = prompt_optional("Login password (optional)")?;
        }
        SetupSourceChoice::AutoDetect
        | SetupSourceChoice::SkipSync
        | SetupSourceChoice::NotSure => {
            unreachable!()
        }
    }

    run_sync(paths.clone(), request).await?;
    Ok(SetupSyncOutcome::synced(source))
}

async fn run_auto_detected_sync(paths: &ConfigPaths) -> Result<SetupSyncOutcome> {
    let project_root = inspection_project_root(paths)?;
    print_section_title("2a. Inspecting project");
    print_path_row(
        "inspection root (scan here for OpenAPI / code / DB files)",
        &project_root,
    );
    tip_if_home_global_appctl(paths);

    let candidates = detect_sync_sources(&project_root);
    if candidates.is_empty() {
        print_status_warn("no obvious sync source found");
        print_tip("If your app exposes OpenAPI, choose OpenAPI and paste the URL or file path.");
        print_tip("If you mainly need data tools, choose Database and paste a connection string.");
        let manual = choose_manual_source()?;
        return run_manual_source_sync(paths, manual).await;
    }

    let mut items: Vec<String> = candidates
        .iter()
        .map(|candidate| candidate.label.clone())
        .collect();
    items.push("Choose a source manually instead".to_string());
    items.push("Skip sync for now".to_string());

    let selected = Select::new()
        .with_prompt("I found these likely app sources. Which should I sync?")
        .items(&items)
        .default(0)
        .interact()?;

    if selected == candidates.len() {
        let manual = choose_manual_source()?;
        return run_manual_source_sync(paths, manual).await;
    }
    if selected == candidates.len() + 1 {
        print_status_warn("skipped sync");
        return Ok(SetupSyncOutcome::skipped());
    }

    let candidate = &candidates[selected];
    if matches!(candidate.source, SetupSourceChoice::Flask) {
        print_tip(
            "Flask: tools are inferred from Python in the project (introspection only). For a spec-driven API, prefer the OpenAPI menu. You will be asked for the HTTP `base_url` the tools should call; default is http://127.0.0.1:5000 if your `flask run` matches.",
        );
    }
    let mut request = candidate.request.clone();
    request.force = confirm_replace_existing_tools(paths)?;
    fill_detected_missing_values(candidate.source, &mut request)?;

    print_status_success(&format!("syncing detected source: {}", candidate.label));
    run_sync(paths.clone(), request).await?;
    Ok(SetupSyncOutcome::synced(candidate.source))
}

fn choose_manual_source() -> Result<SetupSourceChoice> {
    let items = &SetupSourceChoice::items()[1..SetupSourceChoice::items().len() - 1];
    let index = Select::new()
        .with_prompt("Choose the source manually")
        .items(items)
        .default(0)
        .interact()?;
    Ok(SetupSourceChoice::from_index(index + 1))
}

fn confirm_replace_existing_tools(paths: &ConfigPaths) -> Result<bool> {
    if paths.schema.exists() {
        Confirm::new()
            .with_prompt("Tools are already synced. Replace them with this setup sync?")
            .default(false)
            .interact()
            .context("prompt failed")
    } else {
        Ok(false)
    }
}

/// Default dev `http://` guess for the selected sync source. User can override; wrong host/port
/// is better than an empty base URL, which would break every HTTP tool at runtime.
fn default_dev_base_url_for_setup(source: SetupSourceChoice) -> &'static str {
    match source {
        SetupSourceChoice::Django | SetupSourceChoice::Laravel => "http://127.0.0.1:8000",
        SetupSourceChoice::Rails => "http://127.0.0.1:3000",
        SetupSourceChoice::Strapi => "http://127.0.0.1:1337",
        SetupSourceChoice::Flask | SetupSourceChoice::AspNet => "http://127.0.0.1:5000",
        SetupSourceChoice::Url => "http://127.0.0.1:5000",
        // Only used when a future auto-detect candidate adds a new `http_like` source.
        _ => "http://127.0.0.1:8080",
    }
}

fn fill_detected_missing_values(
    source: SetupSourceChoice,
    request: &mut SyncRequest,
) -> Result<()> {
    match source {
        SetupSourceChoice::OpenApi => {
            request.base_url = prompt_optional("Base URL for the running API (optional)")?;
            request.auth_header = prompt_auth_header_optional(
                "Auth header for protected routes, e.g. Authorization: Bearer env:API_TOKEN (optional)",
            )?;
        }
        source if source.is_http_like() => {
            let def = default_dev_base_url_for_setup(source);
            request.base_url = Some(prompt_string_nonempty(
                "Base URL for HTTP tool calls (where this app is reachable; required for list/get/…)",
                def,
            )?);
        }
        _ => {}
    }
    Ok(())
}

async fn ensure_target_auth(
    paths: &ConfigPaths,
    outcome: &SetupSyncOutcome,
    force_prompt: bool,
) -> Result<()> {
    if !force_prompt
        && !outcome
            .doctor_source
            .is_some_and(SetupSourceChoice::is_http_like)
    {
        return Ok(());
    }

    print_section_title("2b. Target app auth");
    println!(
        "  This controls how appctl calls your app/API. The AI never sees passwords, tokens, cookies, or client secrets."
    );

    let items = [
        "Public API / no auth",
        "Bearer token from an environment variable",
        "Bearer token stored in appctl keychain",
        "Cookie/session value from an environment variable",
        "OAuth browser login now",
        "Use an existing OAuth target profile",
        "Skip for now",
    ];
    let selected = Select::new()
        .with_prompt("How should appctl authenticate to the target app?")
        .items(items)
        .default(5)
        .interact()?;

    match selected {
        0 => {
            let mut config = AppConfig::load_or_init(paths)?;
            config.target.auth_header = None;
            config.target.oauth_provider = None;
            config.save(paths)?;
            print_status_success(
                "target auth cleared; appctl will call the API without extra auth",
            );
        }
        1 => {
            let env_name = prompt_string_nonempty(
                "Environment variable that holds the bearer token",
                "API_TOKEN",
            )?;
            set_target_auth_header(paths, format!("Authorization: Bearer env:{env_name}"))?;
            print_status_success(&format!(
                "target auth will use Authorization: Bearer env:{env_name}"
            ));
        }
        2 => {
            let secret_name = prompt_string_nonempty(
                "Keychain secret name that holds the bearer token",
                "API_TOKEN",
            )?;
            set_target_auth_header(
                paths,
                format!("Authorization: Bearer keychain:{secret_name}"),
            )?;
            print_status_success(&format!(
                "target auth will use Authorization: Bearer keychain:{secret_name}"
            ));
            print_tip(&format!(
                "Store/refresh it with: appctl config set-secret {secret_name}"
            ));
        }
        3 => {
            let env_name = prompt_string_nonempty(
                "Environment variable that holds the Cookie header value",
                "APP_SESSION_COOKIE",
            )?;
            set_target_auth_header(paths, format!("Cookie: env:{env_name}"))?;
            print_status_success(&format!("target auth will use Cookie: env:{env_name}"));
        }
        4 => {
            login_target_oauth_from_setup(paths).await?;
        }
        5 => {
            let profile = prompt_string_nonempty("Existing target OAuth profile name", "default")?;
            set_target_oauth_provider(paths, &profile)?;
            print_status_success(&format!(
                "target OAuth profile `{profile}` will be used for HTTP tools"
            ));
            print_tip(&format!(
                "If it has no stored token yet, run `appctl auth target login {profile}`."
            ));
        }
        _ => {
            print_tip(
                "Skipped target auth. You can add it later with `appctl auth target set-bearer --env API_TOKEN` or `appctl auth target login <name>`.",
            );
        }
    }
    Ok(())
}

async fn login_target_oauth_from_setup(paths: &ConfigPaths) -> Result<()> {
    let profile = prompt_string_nonempty("Target OAuth profile name", "default")?;
    let client_id = prompt_string("OAuth client id (public value)", None)?;
    let auth_url = prompt_string("OAuth authorization URL", None)?;
    let token_url = prompt_string("OAuth token URL", None)?;
    let secret_env = prompt_optional(
        "Client secret environment variable (optional; leave blank for public PKCE clients)",
    )?;
    let client_secret = match secret_env {
        Some(name) => match std::env::var(&name) {
            Ok(value) => Some(value),
            Err(_) => {
                print_status_warn(&format!(
                    "environment variable `{name}` is not set; continuing without a client secret"
                ));
                None
            }
        },
        None => None,
    };
    let scope_line = prompt_optional("OAuth scopes (space-separated, optional)")?;
    let scopes = scope_line
        .as_deref()
        .unwrap_or_default()
        .split_whitespace()
        .map(str::to_string)
        .collect::<Vec<_>>();

    let tokens = oauth_login(OAuthLoginConfig {
        provider: profile.clone(),
        storage_key: profile.clone(),
        namespace: OAuthTokenNamespace::Target,
        client_id,
        client_secret,
        auth_url,
        token_url,
        scopes,
        redirect_port: 8421,
    })
    .await?;

    set_target_oauth_provider(paths, &profile)?;
    print_status_success(&format!(
        "logged in target profile `{profile}` and stored {} scope entries",
        tokens.scopes.len()
    ));
    Ok(())
}

fn set_target_auth_header(paths: &ConfigPaths, auth_header: String) -> Result<()> {
    let mut config = AppConfig::load_or_init(paths)?;
    config.target.auth_header = Some(auth_header);
    config.target.oauth_provider = None;
    config.save(paths)
}

fn set_target_oauth_provider(paths: &ConfigPaths, profile: &str) -> Result<()> {
    let mut config = AppConfig::load_or_init(paths)?;
    config.target.oauth_provider = Some(profile.to_string());
    config.save(paths)
}

/// Folder to scan for OpenAPI files, framework markers, and SQLite databases during setup.
///
/// If `.appctl` is `~/.appctl`, the parent directory would be the entire home folder — that is
/// never a useful “project” for a shallow scan. In that case we use **current working directory**
/// (the folder the user `cd`’d into) instead. Tools and config still live under `paths.root`.
fn inspection_project_root(paths: &ConfigPaths) -> Result<PathBuf> {
    let cwd = std::env::current_dir().context("failed to get current working directory")?;
    let home = dirs::home_dir();
    Ok(inspection_project_root_inner(paths, home.as_deref(), &cwd))
}

fn inspection_project_root_inner(paths: &ConfigPaths, home: Option<&Path>, cwd: &Path) -> PathBuf {
    if let Some(h) = home {
        if Some(h) == paths.root.parent() {
            return cwd.to_path_buf();
        }
    }
    paths
        .root
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| paths.root.clone())
}

fn tip_if_home_global_appctl(paths: &ConfigPaths) {
    let Some(h) = dirs::home_dir() else {
        return;
    };
    if h.join(".appctl") == paths.root {
        print_tip("Scan uses this directory only; config stays in ~/.appctl.");
    }
}

fn is_openapi_spec_file_name(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "openapi.json"
            | "openapi.yaml"
            | "openapi.yml"
            | "swagger.json"
            | "swagger.yaml"
            | "swagger.yml"
    )
}

/// Shallowest matching spec files first (used as the default in the OpenAPI prompt).
fn find_openapi_spec_files(project_root: &Path) -> Vec<PathBuf> {
    let files = collect_project_files(project_root, 5);
    let mut out: Vec<PathBuf> = files
        .into_iter()
        .filter(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .map(is_openapi_spec_file_name)
                .unwrap_or(false)
        })
        .collect();
    out.sort_by_key(|p| p.components().count());
    out
}

fn openapi_prompt_default_path(file: &Path) -> String {
    if let Ok(cwd) = std::env::current_dir() {
        if let Ok(rel) = file.strip_prefix(&cwd) {
            return rel.display().to_string();
        }
    }
    file.display().to_string()
}

fn stored_schema_json(paths: &ConfigPaths) -> Option<Value> {
    let path = paths.root.join("schema.json");
    let raw = fs::read_to_string(path).ok()?;
    serde_json::from_str(&raw).ok()
}

fn stored_sync_base_url(paths: &ConfigPaths) -> Option<String> {
    let schema = stored_schema_json(paths)?;
    let source = schema.get("source")?.as_str()?;
    if source != "openapi" {
        return None;
    }
    let base_url = schema.get("base_url")?.as_str()?.trim();
    if base_url.is_empty() {
        return None;
    }
    Some(normalize_base_url(base_url))
}

fn stored_openapi_url_default(paths: &ConfigPaths) -> Option<String> {
    let base = stored_sync_base_url(paths)?;
    Some(join_url_path(&base, "openapi.json"))
}

fn normalize_base_url(base_url: &str) -> String {
    base_url.trim_end_matches('/').to_string()
}

fn join_url_path(base_url: &str, suffix: &str) -> String {
    let base = normalize_base_url(base_url);
    format!("{base}/{suffix}")
}

fn detect_sync_sources(project_root: &Path) -> Vec<DetectedSyncSource> {
    let mut candidates = Vec::new();
    let dirs = collect_project_dirs(project_root, 3);
    let files = collect_project_files(project_root, 4);

    for file in &files {
        let Some(name) = file.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        if is_openapi_spec_file_name(name) {
            candidates.push(DetectedSyncSource {
                label: format!("OpenAPI document: {}", short_path(project_root, file)),
                source: SetupSourceChoice::OpenApi,
                request: SyncRequest {
                    openapi: Some(file.display().to_string()),
                    ..Default::default()
                },
            });
        }

        if is_likely_sqlite_file(file) && !is_junk_sqlite_path(file) {
            candidates.push(DetectedSyncSource {
                label: format!("SQLite database: {}", short_path(project_root, file)),
                source: SetupSourceChoice::Database,
                request: SyncRequest {
                    db: Some(format!("sqlite://{}", file.display())),
                    ..Default::default()
                },
            });
        }
    }

    for dir in dirs {
        if dir.join("manage.py").exists() {
            candidates.push(path_candidate(
                project_root,
                &dir,
                "Django project",
                SetupSourceChoice::Django,
                |path| SyncRequest {
                    django: Some(path),
                    ..Default::default()
                },
            ));
        }
        if dir.join("artisan").exists() {
            candidates.push(path_candidate(
                project_root,
                &dir,
                "Laravel project",
                SetupSourceChoice::Laravel,
                |path| SyncRequest {
                    laravel: Some(path),
                    ..Default::default()
                },
            ));
        }
        if dir.join("config").join("routes.rb").exists() {
            candidates.push(path_candidate(
                project_root,
                &dir,
                "Rails project",
                SetupSourceChoice::Rails,
                |path| SyncRequest {
                    rails: Some(path),
                    ..Default::default()
                },
            ));
        }
        if dir.join("src").join("api").exists()
            && dir.join("package.json").exists()
            && file_contains(&dir.join("package.json"), "strapi")
        {
            candidates.push(path_candidate(
                project_root,
                &dir,
                "Strapi project",
                SetupSourceChoice::Strapi,
                |path| SyncRequest {
                    strapi: Some(path),
                    ..Default::default()
                },
            ));
        }
        if has_aspnet_project_file(&dir) {
            candidates.push(path_candidate(
                project_root,
                &dir,
                "ASP.NET project",
                SetupSourceChoice::AspNet,
                |path| SyncRequest {
                    aspnet: Some(path),
                    ..Default::default()
                },
            ));
        }
        if looks_like_flask_project(&dir) {
            candidates.push(path_candidate(
                project_root,
                &dir,
                "Flask project",
                SetupSourceChoice::Flask,
                |path| SyncRequest {
                    flask: Some(path),
                    ..Default::default()
                },
            ));
        }
    }

    candidates.truncate(12);
    candidates
}

fn path_candidate(
    project_root: &Path,
    dir: &Path,
    label: &str,
    source: SetupSourceChoice,
    build_request: impl FnOnce(PathBuf) -> SyncRequest,
) -> DetectedSyncSource {
    DetectedSyncSource {
        label: format!("{label}: {}", short_path(project_root, dir)),
        source,
        request: build_request(dir.to_path_buf()),
    }
}

fn collect_project_dirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
    let mut dirs = vec![root.to_path_buf()];
    collect_project_dirs_inner(root, root, max_depth, &mut dirs);
    dirs
}

fn collect_project_dirs_inner(root: &Path, dir: &Path, max_depth: usize, out: &mut Vec<PathBuf>) {
    if depth_from(root, dir) >= max_depth {
        return;
    }
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() || should_skip_dir(&path) {
            continue;
        }
        out.push(path.clone());
        collect_project_dirs_inner(root, &path, max_depth, out);
    }
}

fn collect_project_files(root: &Path, max_depth: usize) -> Vec<PathBuf> {
    let mut files = Vec::new();
    collect_project_files_inner(root, root, max_depth, &mut files);
    files
}

fn collect_project_files_inner(root: &Path, dir: &Path, max_depth: usize, out: &mut Vec<PathBuf>) {
    if depth_from(root, dir) > max_depth {
        return;
    }
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            if !should_skip_dir(&path) {
                collect_project_files_inner(root, &path, max_depth, out);
            }
        } else {
            out.push(path);
        }
    }
}

fn depth_from(root: &Path, path: &Path) -> usize {
    path.strip_prefix(root)
        .map(|relative| relative.components().count())
        .unwrap_or(0)
}

fn should_skip_dir(path: &Path) -> bool {
    matches!(
        path.file_name().and_then(|name| name.to_str()),
        Some(
            ".appctl"
                | ".config"
                | ".continue"
                | ".cursor"
                | ".gemini"
                | ".git"
                | ".hg"
                | ".local"
                | ".svn"
                | ".next"
                | ".venv"
                | "build"
                | "dist"
                | "node_modules"
                | "target"
                | "vendor"
                | "venv"
        )
    )
}

/// Tool and browser caches often use `.db` / `.sqlite` under dot-folders; never suggest those for app sync.
fn is_junk_sqlite_path(path: &Path) -> bool {
    for c in path.components() {
        if let std::path::Component::Normal(name) = c {
            if matches!(
                name.to_string_lossy().as_ref(),
                ".config"
                    | ".cursor"
                    | ".continue"
                    | ".gemini"
                    | "node_modules"
                    | "target"
                    | "dist"
                    | "build"
                    | "vendor"
                    | "venv"
                    | ".venv"
            ) {
                return true;
            }
        }
    }
    // Extra guard: known paths under a macOS home even if layout changes.
    let s = path.to_string_lossy();
    s.contains("/.config/")
        || s.contains("/.continue/")
        || s.contains("/.cursor/")
        || s.contains("/.gemini/")
        || s.contains("github-copilot")
        || s.contains("gcloud")
        || s.contains("Application Support")
}

fn is_likely_sqlite_file(path: &Path) -> bool {
    if path.file_name().and_then(|name| name.to_str()) == Some("history.db") {
        return false;
    }
    matches!(
        path.extension().and_then(|ext| ext.to_str()),
        Some("db" | "sqlite" | "sqlite3")
    )
}

fn has_aspnet_project_file(dir: &Path) -> bool {
    let Ok(entries) = fs::read_dir(dir) else {
        return false;
    };
    entries.flatten().any(|entry| {
        matches!(
            entry.path().extension().and_then(|ext| ext.to_str()),
            Some("csproj" | "fsproj" | "vbproj")
        )
    })
}

fn looks_like_flask_project(dir: &Path) -> bool {
    if !dir.join("app.py").exists() && !dir.join("wsgi.py").exists() {
        return false;
    }
    ["requirements.txt", "pyproject.toml", "Pipfile"]
        .iter()
        .any(|name| file_contains(&dir.join(name), "flask"))
}

fn file_contains(path: &Path, needle: &str) -> bool {
    fs::read_to_string(path)
        .map(|content| content.to_ascii_lowercase().contains(needle))
        .unwrap_or(false)
}

fn short_path(root: &Path, path: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .display()
        .to_string()
}

async fn maybe_run_doctor(paths: &ConfigPaths, outcome: SetupSyncOutcome) -> bool {
    let Some(source) = outcome.doctor_source else {
        return true;
    };
    if !outcome.did_sync || !source.is_http_like() {
        return true;
    }

    print_section_title("3. Checks");
    match run_doctor(
        paths,
        DoctorRunArgs {
            write: true,
            timeout_secs: 10,
        },
    )
    .await
    {
        Ok(()) => {
            print_status_success("doctor checks completed");
            true
        }
        Err(err) => {
            print_status_warn("doctor could not finish");
            print_tip(&format!(
                "Fix this before expecting protected tools to work. Later, run `appctl doctor --write` again. Detail: {err:#}"
            ));
            false
        }
    }
}

fn print_next_steps(paths: &ConfigPaths, checks_ok: bool) {
    if checks_ok {
        print_section_title("Ready");
    } else {
        print_section_title("Setup finished — checks need attention");
    }
    print_path_row("app directory", &paths.root);
    if checks_ok {
        print_status_success("setup flow finished");
    } else {
        print_status_warn("setup saved config/tools, but target API checks did not pass");
    }
    print_tip("Terminal: appctl chat");
    print_tip("Web:      appctl serve --open");
}

fn print_non_interactive_setup(paths: &ConfigPaths) {
    print_section_title("Setup needs an interactive terminal");
    print_path_row("app directory", &paths.root);
    println!("  Run the guided setup in a terminal:");
    println!("    appctl setup");
    println!();
    println!("  Advanced manual path:");
    println!("    appctl init");
    println!("    appctl sync --openapi <url-or-file> --base-url <running-api-url>");
    println!("    appctl doctor --write");
    println!("    appctl chat");
}

fn prompt_string(prompt: &str, default: Option<&str>) -> Result<String> {
    let mut input = Input::<String>::new().with_prompt(prompt.to_string());
    if let Some(default) = default {
        input = input.default(default.to_string());
    }
    input.interact_text().context("prompt failed")
}

fn prompt_optional(prompt: &str) -> Result<Option<String>> {
    let value = Input::<String>::new()
        .with_prompt(prompt.to_string())
        .allow_empty(true)
        .interact_text()
        .context("prompt failed")?;
    let trimmed = value.trim();
    if trimmed.is_empty() {
        Ok(None)
    } else {
        Ok(Some(trimmed.to_string()))
    }
}

fn prompt_auth_header_optional(prompt: &str) -> Result<Option<String>> {
    loop {
        let Some(value) = prompt_optional(prompt)? else {
            return Ok(None);
        };
        if auth_header_looks_truncated(&value) {
            print_status_warn(
                "that auth header looks truncated (`...`). Paste the full header or use env:, e.g. Authorization: Bearer env:TOKEN.",
            );
            continue;
        }
        return Ok(Some(value));
    }
}

fn auth_header_looks_truncated(value: &str) -> bool {
    value.contains("...") || value.contains('…')
}

fn prompt_string_nonempty(prompt: &str, default: &str) -> Result<String> {
    let value = Input::<String>::new()
        .with_prompt(prompt.to_string())
        .default(default.to_string())
        .interact_text()
        .context("prompt failed")?;
    let trimmed = value.trim();
    if trimmed.is_empty() {
        Ok(default.to_string())
    } else {
        Ok(trimmed.to_string())
    }
}

fn prompt_path(prompt: &str, default: Option<&str>) -> Result<PathBuf> {
    prompt_string(prompt, default).map(PathBuf::from)
}

#[cfg(test)]
mod tests {
    use super::{
        ConfigPaths, SetupSourceChoice, auth_header_looks_truncated, detect_sync_sources,
        find_openapi_spec_files, inspection_project_root_inner, stored_openapi_url_default,
        stored_sync_base_url,
    };
    use std::fs;
    use std::path::PathBuf;
    use tempfile::tempdir;

    #[test]
    fn setup_source_choice_maps_known_indexes() {
        assert_eq!(
            SetupSourceChoice::from_index(0),
            SetupSourceChoice::AutoDetect
        );
        assert_eq!(SetupSourceChoice::from_index(1), SetupSourceChoice::OpenApi);
        assert_eq!(
            SetupSourceChoice::from_index(2),
            SetupSourceChoice::Database
        );
        assert_eq!(
            SetupSourceChoice::from_index(11),
            SetupSourceChoice::NotSure
        );
    }

    #[test]
    fn doctor_runs_only_for_http_like_sources() {
        assert!(SetupSourceChoice::OpenApi.is_http_like());
        assert!(SetupSourceChoice::Django.is_http_like());
        assert!(!SetupSourceChoice::Database.is_http_like());
        assert!(!SetupSourceChoice::SkipSync.is_http_like());
    }

    #[test]
    fn setup_detects_openapi_file_and_sqlite_db() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("openapi.json"), "{}").unwrap();
        fs::write(dir.path().join("app.sqlite"), "").unwrap();

        let found = detect_sync_sources(dir.path());

        assert!(
            found
                .iter()
                .any(|candidate| candidate.source == SetupSourceChoice::OpenApi)
        );
        assert!(
            found
                .iter()
                .any(|candidate| candidate.source == SetupSourceChoice::Database)
        );
    }

    #[test]
    fn setup_detects_framework_markers() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("manage.py"), "").unwrap();
        fs::create_dir_all(dir.path().join("config")).unwrap();
        fs::write(dir.path().join("config").join("routes.rb"), "").unwrap();

        let found = detect_sync_sources(dir.path());

        assert!(
            found
                .iter()
                .any(|candidate| candidate.source == SetupSourceChoice::Django)
        );
        assert!(
            found
                .iter()
                .any(|candidate| candidate.source == SetupSourceChoice::Rails)
        );
    }

    #[test]
    fn inspection_root_uses_cwd_when_app_dir_is_home_dot_appctl() {
        let home = PathBuf::from("/Users/person");
        let paths = ConfigPaths::new(home.join(".appctl"));
        let cwd = home.join("open").join("source").join("Quorum");
        let root = inspection_project_root_inner(&paths, Some(home.as_path()), &cwd);
        assert_eq!(root, cwd);
    }

    #[test]
    fn inspection_root_uses_project_parent_for_nested_appctl() {
        let home = PathBuf::from("/Users/person");
        let project = home.join("repos").join("myapp");
        let paths = ConfigPaths::new(project.join(".appctl"));
        let cwd = home.join("somewhere-else");
        let root = inspection_project_root_inner(&paths, Some(home.as_path()), &cwd);
        assert_eq!(root, project);
    }

    #[test]
    fn openapi_spec_search_prefers_shallowest_file() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("nested")).unwrap();
        fs::write(dir.path().join("nested").join("openapi.json"), "{}").unwrap();
        fs::write(dir.path().join("openapi.json"), "{}").unwrap();
        let found = find_openapi_spec_files(dir.path());
        assert_eq!(found[0], dir.path().join("openapi.json"));
    }

    #[test]
    fn truncated_auth_headers_are_rejected() {
        assert!(auth_header_looks_truncated("Authorization: Bearer abc..."));
        assert!(auth_header_looks_truncated("Authorization: Bearer abc…"));
        assert!(!auth_header_looks_truncated(
            "Authorization: Bearer env:TASK_API_TOKEN"
        ));
    }

    #[test]
    fn stored_schema_suggests_live_openapi_url_from_prior_sync() {
        let dir = tempdir().unwrap();
        let paths = ConfigPaths::new(dir.path().join(".appctl"));
        fs::create_dir_all(&paths.root).unwrap();
        fs::write(
            paths.root.join("schema.json"),
            r#"{"source":"openapi","base_url":"http://localhost:8000/"}"#,
        )
        .unwrap();

        assert_eq!(
            stored_sync_base_url(&paths).as_deref(),
            Some("http://localhost:8000")
        );
        assert_eq!(
            stored_openapi_url_default(&paths).as_deref(),
            Some("http://localhost:8000/openapi.json")
        );
    }
}