claudectx 0.2.0

Launch Claude Code with different profiles
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
//! End-to-end tests for claudectx CLI
//!
//! These tests run the actual binary in a sandboxed environment using
//! temporary directories as HOME to avoid interfering with real config files.
//!
//! Note: Tests that would launch claude are limited since claude is not
//! installed in the CI environment. We test save/list/delete thoroughly
//! and verify symlink creation works correctly.

use assert_cmd::prelude::*;
use predicates::prelude::*;
use serde_json::json;
use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;

/// Create a test environment with a temporary HOME directory
struct TestEnv {
    home_dir: TempDir,
}

impl TestEnv {
    fn new() -> Self {
        let home_dir = TempDir::new().expect("Failed to create temp directory");
        Self { home_dir }
    }

    /// Get the path to the home directory
    fn home_path(&self) -> &Path {
        self.home_dir.path()
    }

    /// Get path to .claude.json in test environment
    fn claude_config_path(&self) -> std::path::PathBuf {
        self.home_dir.path().join(".claude.json")
    }

    /// Get path to .claudectx/ directory in test environment
    fn claudectx_dir(&self) -> std::path::PathBuf {
        self.home_dir.path().join(".claudectx")
    }

    /// Get path to a profile file
    fn profile_path(&self, name: &str) -> std::path::PathBuf {
        self.claudectx_dir().join(format!("{}.claude.json", name))
    }

    /// Create a valid .claude.json config file (as a regular file, not a symlink)
    fn create_claude_config(&self, account: &serde_json::Value) {
        let config_path = self.claude_config_path();
        // Remove existing symlink first to avoid writing through it to the target
        if config_path.is_symlink() {
            fs::remove_file(&config_path).expect("Failed to remove existing symlink");
        }
        let config = json!({
            "oauthAccount": account,
            "lastAccountUUID": account["accountUuid"],
            "primaryApiKey": "sk-ant-test-key",
            "hasCompletedOnboarding": true
        });
        fs::write(
            &config_path,
            serde_json::to_string_pretty(&config).expect("serialize"),
        )
        .expect("Failed to write claude config");
    }

    /// Create a profile file directly
    fn create_profile(&self, name: &str, account: &serde_json::Value) {
        fs::create_dir_all(self.claudectx_dir()).expect("Failed to create claudectx dir");
        let config = json!({
            "oauthAccount": account,
            "lastAccountUUID": account["accountUuid"],
            "primaryApiKey": format!("sk-ant-test-key-{}", name),
            "hasCompletedOnboarding": true
        });
        fs::write(
            self.profile_path(name),
            serde_json::to_string_pretty(&config).expect("serialize"),
        )
        .expect("Failed to write profile");
    }

    /// Read a profile file
    fn read_profile(&self, name: &str) -> serde_json::Value {
        let content = fs::read_to_string(self.profile_path(name)).expect("Failed to read profile");
        serde_json::from_str(&content).expect("Failed to parse profile")
    }

    /// List profile files in the claudectx directory
    fn list_profile_files(&self) -> Vec<String> {
        if !self.claudectx_dir().exists() {
            return vec![];
        }
        fs::read_dir(self.claudectx_dir())
            .expect("Failed to read claudectx dir")
            .filter_map(|entry| {
                let entry = entry.ok()?;
                let name = entry.file_name().to_string_lossy().to_string();
                name.strip_suffix(".claude.json").map(String::from)
            })
            .collect()
    }

    /// Check if .claude.json is a symlink pointing to a specific profile
    fn is_symlink_to_profile(&self, profile_name: &str) -> bool {
        let config_path = self.claude_config_path();
        if !config_path.is_symlink() {
            return false;
        }
        let target = fs::read_link(&config_path).ok();
        target
            .map(|t| t == self.profile_path(profile_name))
            .unwrap_or(false)
    }

    /// Run claudectx command with this test environment
    fn cmd(&self) -> assert_cmd::Command {
        let mut cmd = Command::cargo_bin("claudectx").expect("Failed to find binary");
        // Use CLAUDECTX_HOME for reliable cross-platform home directory override
        // The dirs crate doesn't reliably respect HOME/USERPROFILE when set for child processes
        cmd.env("CLAUDECTX_HOME", self.home_path());
        assert_cmd::Command::from_std(cmd)
    }
}

/// Create a sample OAuth account for testing
fn sample_account(suffix: &str) -> serde_json::Value {
    json!({
        "accountUuid": format!("uuid-{}", suffix),
        "emailAddress": format!("user-{}@example.com", suffix),
        "organizationUuid": format!("org-uuid-{}", suffix),
        "displayName": format!("User {}", suffix),
        "organizationRole": "member",
        "organizationName": format!("Org {}", suffix),
        "hasExtraUsageEnabled": false,
        "workspaceRole": null
    })
}

// =============================================================================
// HELP AND VERSION TESTS
// =============================================================================

#[test]
fn test_help_flag() {
    let env = TestEnv::new();
    env.cmd()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Launch Claude Code with different profiles",
        ))
        .stdout(predicate::str::contains("list"))
        .stdout(predicate::str::contains("save"))
        .stdout(predicate::str::contains("delete"));
}

#[test]
fn test_version_flag() {
    let env = TestEnv::new();
    env.cmd()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains("claudectx"));
}

#[test]
fn test_help_subcommand() {
    let env = TestEnv::new();
    env.cmd()
        .arg("help")
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Launch Claude Code with different profiles",
        ));
}

// =============================================================================
// LIST COMMAND TESTS
// =============================================================================

#[test]
fn test_list_empty_profiles() {
    let env = TestEnv::new();
    let account = sample_account("current");
    env.create_claude_config(&account);
    // No profiles directory

    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains("No profiles found."));
}

#[test]
fn test_list_with_profiles() {
    let env = TestEnv::new();
    let current_account = sample_account("current");
    env.create_claude_config(&current_account);

    // Create profile files directly
    env.create_profile("work", &sample_account("work"));
    env.create_profile("personal", &sample_account("personal"));

    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains("work"))
        .stdout(predicate::str::contains("personal"))
        .stdout(predicate::str::contains("User work"))
        .stdout(predicate::str::contains("User personal"));
}

#[test]
fn test_list_marks_current_profile_with_asterisk() {
    let env = TestEnv::new();

    // Create profiles
    env.create_profile("work", &sample_account("work"));
    env.create_profile("personal", &sample_account("personal"));

    // Create symlink to work profile manually (simulating previous switch)
    let config_path = env.claude_config_path();
    #[cfg(unix)]
    std::os::unix::fs::symlink(env.profile_path("work"), &config_path)
        .expect("Failed to create symlink");
    #[cfg(windows)]
    std::os::windows::fs::symlink_file(env.profile_path("work"), &config_path)
        .expect("Failed to create symlink");

    let output = env.cmd().arg("list").assert().success();

    // The current profile should be marked with *
    let output_str = String::from_utf8_lossy(&output.get_output().stdout);
    assert!(
        output_str.contains("work")
            && output_str
                .lines()
                .any(|l| l.contains("work") && l.contains(" *")),
        "Current profile 'work' should be marked with asterisk"
    );
}

// =============================================================================
// SAVE COMMAND TESTS
// =============================================================================

#[test]
fn test_save_creates_new_profile() {
    let env = TestEnv::new();
    let account = sample_account("alice");
    env.create_claude_config(&account);

    env.cmd()
        .args(["save", "alice-profile"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Saved current config as 'alice-profile'",
        ));

    // Verify profile file was created
    assert!(env.profile_path("alice-profile").exists());
    let profile = env.read_profile("alice-profile");
    assert_eq!(
        profile["oauthAccount"]["emailAddress"],
        "user-alice@example.com"
    );
}

#[test]
fn test_save_slugifies_profile_name() {
    let env = TestEnv::new();
    let account = sample_account("test");
    env.create_claude_config(&account);

    env.cmd()
        .args(["save", "My Work Profile"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Saved current config as 'my-work-profile'",
        ));

    // Verify slugified filename
    assert!(env.profile_path("my-work-profile").exists());
}

#[test]
fn test_save_slugifies_special_characters() {
    let env = TestEnv::new();
    let account = sample_account("test");
    env.create_claude_config(&account);

    env.cmd()
        .args(["save", "FG@Company"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Saved current config as 'fg-company'",
        ));

    assert!(env.profile_path("fg-company").exists());
}

#[test]
fn test_save_fails_without_claude_config() {
    let env = TestEnv::new();
    // No .claude.json

    env.cmd()
        .args(["save", "myprofile"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("Failed to read Claude config"));
}

#[test]
fn test_save_multiple_profiles() {
    let env = TestEnv::new();

    // Save first profile
    let account1 = sample_account("first");
    env.create_claude_config(&account1);
    env.cmd().args(["save", "profile1"]).assert().success();

    // Save second profile
    let account2 = sample_account("second");
    env.create_claude_config(&account2);
    env.cmd().args(["save", "profile2"]).assert().success();

    // Verify both profiles exist
    let profiles = env.list_profile_files();
    assert!(profiles.contains(&"profile1".to_string()));
    assert!(profiles.contains(&"profile2".to_string()));
}

// =============================================================================
// DELETE COMMAND TESTS
// =============================================================================

#[test]
fn test_delete_removes_profile() {
    let env = TestEnv::new();
    let account = sample_account("current");
    env.create_claude_config(&account);

    env.create_profile("to-delete", &sample_account("delete-me"));
    env.create_profile("to-keep", &sample_account("keep-me"));

    env.cmd()
        .args(["delete", "to-delete"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Deleted profile 'to-delete'"));

    // Verify profile was deleted
    assert!(!env.profile_path("to-delete").exists());
    assert!(env.profile_path("to-keep").exists());
}

#[test]
fn test_delete_nonexistent_profile_panics() {
    let env = TestEnv::new();
    let account = sample_account("current");
    env.create_claude_config(&account);

    env.cmd()
        .args(["delete", "nonexistent"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("Profile 'nonexistent' not found"));
}

// =============================================================================
// NO-ARGS (INTERACTIVE MODE) TESTS
// =============================================================================

#[test]
fn test_no_args_first_launch_no_profiles() {
    let env = TestEnv::new();
    let account = sample_account("firstuser");
    env.create_claude_config(&account);
    // No profiles

    env.cmd()
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Current account: User firstuser @ Org firstuser",
        ))
        .stdout(predicate::str::contains("No profiles saved yet"))
        .stdout(predicate::str::contains("claudectx save"));
}

#[test]
fn test_no_args_fails_without_claude_config() {
    let env = TestEnv::new();
    // No .claude.json, no profiles - should try interactive mode and fail

    env.cmd()
        .assert()
        .failure()
        .stderr(predicate::str::contains("Failed to read Claude config"));
}

// =============================================================================
// LAUNCH PROFILE TESTS (symlink + claude launch)
// =============================================================================

#[test]
fn test_launch_nonexistent_profile_panics() {
    let env = TestEnv::new();

    // Create a config file
    let account = sample_account("current");
    env.create_claude_config(&account);

    // Try to launch nonexistent profile (will prompt to create)
    // Since we can't interact with prompts in tests, this should fail
    // The test binary runs without a TTY so dialoguer will fail
    env.cmd().arg("nonexistent").assert().failure();
}

#[test]
fn test_launch_creates_symlink_then_attempts_claude() {
    let env = TestEnv::new();
    let account = sample_account("current");
    env.create_claude_config(&account);

    // Create a profile
    env.create_profile("work", &sample_account("work"));

    // Launch - this should:
    // 1. Create symlink ~/.claude.json -> ~/.claudectx/work.claude.json
    // 2. Try to launch claude (which will fail in CI since claude isn't installed)
    let output = env.cmd().arg("work").assert();

    // The symlink should have been created before attempting to launch claude
    assert!(
        env.is_symlink_to_profile("work"),
        "Symlink should point to work profile"
    );

    // The profile file should still exist
    assert!(env.profile_path("work").exists());

    // We don't assert success/failure because:
    // - In CI: claude isn't installed, so launch fails
    // - Locally: claude may be installed and actually launch
    let _ = output;
}

#[test]
fn test_launch_switches_symlink_between_profiles() {
    let env = TestEnv::new();

    // Create profiles
    env.create_profile("work", &sample_account("work"));
    env.create_profile("personal", &sample_account("personal"));

    // Create initial config
    let account = sample_account("initial");
    env.create_claude_config(&account);

    // Launch work profile - creates symlink
    let _ = env.cmd().arg("work").assert();
    assert!(
        env.is_symlink_to_profile("work"),
        "Should symlink to work profile"
    );

    // Launch personal profile - switches symlink
    let _ = env.cmd().arg("personal").assert();
    assert!(
        env.is_symlink_to_profile("personal"),
        "Should symlink to personal profile"
    );
}

// =============================================================================
// EDGE CASES AND ERROR HANDLING
// =============================================================================

#[test]
fn test_malformed_profile_panics() {
    let env = TestEnv::new();
    // Write invalid JSON to profile
    fs::create_dir_all(env.claudectx_dir()).expect("Failed to create dir");
    fs::write(env.profile_path("bad"), "not valid json {{{")
        .expect("Failed to write invalid profile");

    env.cmd()
        .arg("list")
        .assert()
        .failure()
        .stderr(predicate::str::contains("Failed to parse profile"));
}

// =============================================================================
// INTEGRATION TESTS - FULL WORKFLOWS
// =============================================================================

#[test]
fn test_workflow_save_list_launch_delete() {
    let env = TestEnv::new();
    let account = sample_account("workflow");
    env.create_claude_config(&account);

    // 1. Save a profile
    env.cmd().args(["save", "test-profile"]).assert().success();

    // 2. List profiles - should show the saved profile
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains("test-profile"))
        .stdout(predicate::str::contains("User workflow"));

    // 3. Launch the profile (creates symlink)
    let _ = env.cmd().arg("test-profile").assert();
    assert!(env.is_symlink_to_profile("test-profile"));

    // 4. List again - test-profile should be marked with *
    let output = env.cmd().arg("list").assert().success();
    let stdout = String::from_utf8_lossy(&output.get_output().stdout);
    assert!(stdout
        .lines()
        .any(|l| l.contains("test-profile") && l.contains(" *")));

    // 5. Delete the profile
    env.cmd()
        .args(["delete", "test-profile"])
        .assert()
        .success();

    // 6. List again - should be empty
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains("No profiles found."));
}

#[test]
fn test_workflow_multiple_accounts() {
    let env = TestEnv::new();

    // Save work account
    let work_account = sample_account("work");
    env.create_claude_config(&work_account);
    env.cmd().args(["save", "work"]).assert().success();

    // Save personal account
    let personal_account = sample_account("personal");
    env.create_claude_config(&personal_account);
    env.cmd().args(["save", "personal"]).assert().success();

    // Save side-project account
    let side_account = sample_account("side");
    env.create_claude_config(&side_account);
    env.cmd().args(["save", "side-project"]).assert().success();

    // Launch work profile
    let _ = env.cmd().arg("work").assert();

    // List all profiles - work should be marked current
    let output = env.cmd().arg("list").assert().success();
    let stdout = String::from_utf8_lossy(&output.get_output().stdout);
    assert!(stdout.contains("work"));
    assert!(stdout.contains("personal"));
    assert!(stdout.contains("side-project"));
    // work should be marked with *
    assert!(stdout
        .lines()
        .any(|l| l.contains("work") && l.contains(" *")));
}

#[test]
fn test_profiles_persistence_across_commands() {
    let env = TestEnv::new();
    let account = sample_account("persist");
    env.create_claude_config(&account);

    // Save profile
    env.cmd()
        .args(["save", "persistent-profile"])
        .assert()
        .success();

    // Verify the file exists
    assert!(env.profile_path("persistent-profile").exists());

    // Run list in a new command invocation
    env.cmd()
        .arg("list")
        .assert()
        .success()
        .stdout(predicate::str::contains("persistent-profile"));
}

// =============================================================================
// SUBCOMMAND HELP TESTS
// =============================================================================

#[test]
fn test_save_help() {
    let env = TestEnv::new();
    env.cmd()
        .args(["save", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Save current config as a new profile",
        ))
        .stdout(predicate::str::contains("<NAME>"));
}

#[test]
fn test_delete_help() {
    let env = TestEnv::new();
    env.cmd()
        .args(["delete", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Delete a profile"))
        .stdout(predicate::str::contains("<NAME>"));
}

#[test]
fn test_list_help() {
    let env = TestEnv::new();
    env.cmd()
        .args(["list", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("List all saved profiles"));
}

// =============================================================================
// ARGUMENT VALIDATION TESTS
// =============================================================================

#[test]
fn test_save_requires_name_argument() {
    let env = TestEnv::new();
    env.cmd()
        .arg("save")
        .assert()
        .failure()
        .stderr(predicate::str::contains("required"));
}

#[test]
fn test_delete_requires_name_argument() {
    let env = TestEnv::new();
    env.cmd()
        .arg("delete")
        .assert()
        .failure()
        .stderr(predicate::str::contains("required"));
}

// =============================================================================
// DATA INTEGRITY TESTS
// =============================================================================

#[test]
fn test_saved_profile_preserves_all_config_fields() {
    let env = TestEnv::new();
    let account = json!({
        "accountUuid": "uuid-integrity",
        "emailAddress": "integrity@example.com",
        "organizationUuid": "org-uuid-integrity",
        "displayName": "Integrity User",
        "organizationRole": "admin",
        "organizationName": "Integrity Org",
        "hasExtraUsageEnabled": true,
        "workspaceRole": "owner"
    });

    // Create config with extra fields
    let config = json!({
        "oauthAccount": account,
        "lastAccountUUID": account["accountUuid"],
        "primaryApiKey": "sk-ant-test-key",
        "hasCompletedOnboarding": true,
        "customField": "custom-value",
        "nestedField": {
            "inner": "value"
        }
    });
    fs::write(
        env.claude_config_path(),
        serde_json::to_string_pretty(&config).expect("serialize"),
    )
    .expect("Failed to write config");

    env.cmd()
        .args(["save", "integrity-test"])
        .assert()
        .success();

    let profile = env.read_profile("integrity-test");

    // Verify all fields are preserved (it's now a full copy)
    assert_eq!(profile["oauthAccount"]["accountUuid"], "uuid-integrity");
    assert_eq!(
        profile["oauthAccount"]["emailAddress"],
        "integrity@example.com"
    );
    assert_eq!(profile["customField"], "custom-value");
    assert_eq!(profile["nestedField"]["inner"], "value");
}

// =============================================================================
// SLUGIFY TESTS (via CLI)
// =============================================================================

#[test]
fn test_slugify_uppercase_to_lowercase() {
    let env = TestEnv::new();
    let account = sample_account("test");
    env.create_claude_config(&account);

    env.cmd()
        .args(["save", "UPPERCASE"])
        .assert()
        .success()
        .stdout(predicate::str::contains("'uppercase'"));

    assert!(env.profile_path("uppercase").exists());
}

#[test]
fn test_slugify_handles_multiple_dashes() {
    let env = TestEnv::new();
    let account = sample_account("test");
    env.create_claude_config(&account);

    env.cmd()
        .args(["save", "test---name"])
        .assert()
        .success()
        .stdout(predicate::str::contains("'test-name'"));

    assert!(env.profile_path("test-name").exists());
}

// =============================================================================
// LOGIN COMMAND TESTS
// =============================================================================

#[test]
fn test_login_help() {
    let env = TestEnv::new();
    env.cmd()
        .args(["login", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Login to a new Claude account and save it as a profile",
        ));
}

#[test]
fn test_help_includes_login_command() {
    let env = TestEnv::new();
    env.cmd()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("login"));
}

// =============================================================================
// BACKUP/RESTORE TESTS
// =============================================================================

impl TestEnv {
    /// Get path to .claude.json.bak in test environment
    fn claude_config_backup_path(&self) -> std::path::PathBuf {
        self.home_dir.path().join(".claude.json.bak")
    }
}

#[test]
fn test_backup_file_location() {
    let env = TestEnv::new();
    let account = sample_account("backup-test");
    env.create_claude_config(&account);

    // The backup path should be in the test home directory
    let backup_path = env.claude_config_backup_path();
    assert!(backup_path.starts_with(env.home_path()));
    assert!(backup_path.ends_with(".claude.json.bak"));
}

// =============================================================================
// CURRENT PROFILE DETECTION TESTS
// =============================================================================

#[test]
fn test_list_marks_current_profile_when_config_matches_profile_content() {
    let env = TestEnv::new();

    // Create two profiles directly
    let work_account = sample_account("work");
    let personal_account = sample_account("personal");
    env.create_profile("work", &work_account);
    env.create_profile("personal", &personal_account);

    // Set .claude.json to same content as "work" profile (NOT a symlink)
    env.create_claude_config(&work_account);

    // Verify it's not a symlink
    assert!(
        !env.claude_config_path().is_symlink(),
        ".claude.json should be a regular file, not a symlink"
    );

    // List should show asterisk for "work" profile because content matches
    let output = env.cmd().arg("list").assert().success();
    let stdout = String::from_utf8_lossy(&output.get_output().stdout);

    // The "work" profile should be marked with * because its content matches .claude.json
    assert!(
        stdout
            .lines()
            .any(|l| l.contains("work") && l.contains(" *")),
        "Profile 'work' should be marked with asterisk when config content matches. Output:\n{}",
        stdout
    );

    // The "personal" profile should NOT be marked
    assert!(
        stdout
            .lines()
            .any(|l| l.contains("personal") && !l.contains(" *")),
        "Profile 'personal' should NOT be marked with asterisk. Output:\n{}",
        stdout
    );
}

#[test]
fn test_list_no_asterisk_when_config_matches_no_profile() {
    let env = TestEnv::new();

    // Create two profiles
    env.create_profile("work", &sample_account("work"));
    env.create_profile("personal", &sample_account("personal"));

    // Set .claude.json to different content (doesn't match any profile)
    let different_account = sample_account("different");
    env.create_claude_config(&different_account);

    // List should show NO asterisk for any profile
    let output = env.cmd().arg("list").assert().success();
    let stdout = String::from_utf8_lossy(&output.get_output().stdout);

    // No profile should be marked
    assert!(
        !stdout.contains(" *"),
        "No profile should be marked when config doesn't match any profile. Output:\n{}",
        stdout
    );
}

#[test]
fn test_list_asterisk_symlink_takes_precedence() {
    let env = TestEnv::new();

    // Create two profiles with same accountUuid to test precedence
    let work_account = sample_account("work");
    let personal_account = sample_account("personal");
    env.create_profile("work", &work_account);
    env.create_profile("personal", &personal_account);

    // Create symlink to work profile
    #[cfg(unix)]
    std::os::unix::fs::symlink(env.profile_path("work"), env.claude_config_path())
        .expect("Failed to create symlink");
    #[cfg(windows)]
    std::os::windows::fs::symlink_file(env.profile_path("work"), env.claude_config_path())
        .expect("Failed to create symlink");

    // List should mark "work" because symlink points to it
    let output = env.cmd().arg("list").assert().success();
    let stdout = String::from_utf8_lossy(&output.get_output().stdout);

    assert!(
        stdout
            .lines()
            .any(|l| l.contains("work") && l.contains(" *")),
        "Profile 'work' should be marked via symlink detection. Output:\n{}",
        stdout
    );
}

#[test]
fn test_save_then_list_shows_asterisk_for_saved_profile() {
    let env = TestEnv::new();

    // Create a claude config and save it as "my-profile"
    let account = sample_account("my-account");
    env.create_claude_config(&account);
    env.cmd().args(["save", "my-profile"]).assert().success();

    // .claude.json IS now a symlink after save (auto-symlink feature)
    assert!(
        env.claude_config_path().is_symlink(),
        ".claude.json should be a symlink after save"
    );
    assert!(
        env.is_symlink_to_profile("my-profile"),
        ".claude.json should symlink to the saved profile"
    );

    // List should show asterisk for "my-profile"
    let output = env.cmd().arg("list").assert().success();
    let stdout = String::from_utf8_lossy(&output.get_output().stdout);

    assert!(
        stdout
            .lines()
            .any(|l| l.contains("my-profile") && l.contains(" *")),
        "Just-saved profile should be marked as current. Output:\n{}",
        stdout
    );
}

// =============================================================================
// SAVE AUTO-SYMLINK TESTS
// =============================================================================

#[test]
fn test_save_when_not_symlink_creates_symlink() {
    let env = TestEnv::new();
    let account = sample_account("auto-link");
    env.create_claude_config(&account);

    // .claude.json is a regular file
    assert!(!env.claude_config_path().is_symlink());

    env.cmd().args(["save", "auto-link"]).assert().success();

    // After save, .claude.json should be a symlink to the profile
    assert!(
        env.claude_config_path().is_symlink(),
        ".claude.json should be a symlink after save"
    );
    assert!(
        env.is_symlink_to_profile("auto-link"),
        ".claude.json should symlink to 'auto-link' profile"
    );

    // Profile file should exist and have the correct content
    let profile = env.read_profile("auto-link");
    assert_eq!(profile["oauthAccount"]["accountUuid"], "uuid-auto-link");
}

#[test]
fn test_save_when_already_symlink_does_not_change_symlink_target() {
    let env = TestEnv::new();

    // Create first profile and symlink to it
    let account1 = sample_account("first");
    env.create_profile("first", &account1);

    // Create symlink .claude.json -> first.claude.json
    #[cfg(unix)]
    std::os::unix::fs::symlink(env.profile_path("first"), env.claude_config_path())
        .expect("Failed to create symlink");
    #[cfg(windows)]
    std::os::windows::fs::symlink_file(env.profile_path("first"), env.claude_config_path())
        .expect("Failed to create symlink");

    assert!(env.is_symlink_to_profile("first"));

    // Save as a different profile name — should NOT change symlink target
    env.cmd().args(["save", "second"]).assert().success();

    // Symlink should still point to "first" (not changed to "second")
    assert!(
        env.is_symlink_to_profile("first"),
        "Symlink should still point to 'first' profile after saving as 'second'"
    );

    // But the "second" profile should exist with the same content
    let profile = env.read_profile("second");
    assert_eq!(profile["oauthAccount"]["accountUuid"], "uuid-first");
}

// =============================================================================
// PORTABLE SETTINGS MERGE TESTS
// =============================================================================

#[test]
fn test_switch_merges_portable_settings() {
    let env = TestEnv::new();

    // Create current config with portable settings (e.g. hasCompletedOnboarding, primaryApiKey)
    // and account-specific fields
    let current_config = json!({
        "oauthAccount": sample_account("current"),
        "userID": "current-user-id",
        "hasCompletedOnboarding": true,
        "primaryApiKey": "sk-current-key",
        "customSetting": "my-custom-value",
        "editorTheme": "dark"
    });
    fs::write(
        env.claude_config_path(),
        serde_json::to_string_pretty(&current_config).expect("serialize"),
    )
    .expect("write");

    // Create target profile with different account and different portable settings
    fs::create_dir_all(env.claudectx_dir()).expect("mkdir");
    let target_config = json!({
        "oauthAccount": sample_account("target"),
        "userID": "target-user-id",
        "hasCompletedOnboarding": false,
        "primaryApiKey": "sk-target-key"
    });
    fs::write(
        env.profile_path("target"),
        serde_json::to_string_pretty(&target_config).expect("serialize"),
    )
    .expect("write");

    // Switch to target profile
    let _ = env.cmd().arg("target").assert();

    // Read the target profile after merge
    let merged = env.read_profile("target");

    // Account-specific fields should come from the TARGET (preserved)
    assert_eq!(merged["oauthAccount"]["accountUuid"], "uuid-target");
    assert_eq!(merged["userID"], "target-user-id");

    // Portable settings should come from the CURRENT (merged over)
    assert_eq!(merged["hasCompletedOnboarding"], true);
    assert_eq!(merged["primaryApiKey"], "sk-current-key");
    assert_eq!(merged["customSetting"], "my-custom-value");
    assert_eq!(merged["editorTheme"], "dark");
}

#[test]
fn test_switch_preserves_account_specific_fields_from_target() {
    let env = TestEnv::new();

    // Current config with all account-specific fields
    let current_config = json!({
        "oauthAccount": sample_account("current"),
        "userID": "current-user-id",
        "groveConfigCache": {"current": true},
        "cachedChromeExtensionInstalled": true,
        "subscriptionNoticeCount": 5,
        "s1mAccessCache": {"current": "data"},
        "recommendedSubscription": "pro",
        "hasAvailableSubscription": true,
        "portableSetting": "from-current"
    });
    fs::write(
        env.claude_config_path(),
        serde_json::to_string_pretty(&current_config).expect("serialize"),
    )
    .expect("write");

    // Target profile with its own account-specific fields
    fs::create_dir_all(env.claudectx_dir()).expect("mkdir");
    let target_config = json!({
        "oauthAccount": sample_account("target"),
        "userID": "target-user-id",
        "groveConfigCache": {"target": true},
        "cachedChromeExtensionInstalled": false,
        "subscriptionNoticeCount": 0,
        "s1mAccessCache": {"target": "data"},
        "recommendedSubscription": "free",
        "hasAvailableSubscription": false,
        "portableSetting": "from-target"
    });
    fs::write(
        env.profile_path("target"),
        serde_json::to_string_pretty(&target_config).expect("serialize"),
    )
    .expect("write");

    // Switch to target
    let _ = env.cmd().arg("target").assert();

    let merged = env.read_profile("target");

    // ALL account-specific fields must come from the TARGET
    assert_eq!(merged["oauthAccount"]["accountUuid"], "uuid-target");
    assert_eq!(merged["userID"], "target-user-id");
    assert_eq!(merged["groveConfigCache"]["target"], true);
    assert_eq!(merged["cachedChromeExtensionInstalled"], false);
    assert_eq!(merged["subscriptionNoticeCount"], 0);
    assert_eq!(merged["s1mAccessCache"]["target"], "data");
    assert_eq!(merged["recommendedSubscription"], "free");
    assert_eq!(merged["hasAvailableSubscription"], false);

    // Portable setting should come from CURRENT
    assert_eq!(merged["portableSetting"], "from-current");
}

#[test]
fn test_switch_when_no_current_config_exists() {
    let env = TestEnv::new();

    // No .claude.json exists at all
    assert!(!env.claude_config_path().exists());

    // Create target profile
    env.create_profile("target", &sample_account("target"));

    // Switch should work — no merge needed, just create symlink
    let _ = env.cmd().arg("target").assert();

    assert!(
        env.is_symlink_to_profile("target"),
        "Should create symlink even when no prior config exists"
    );

    // Profile content should be unchanged (no merge happened)
    let profile = env.read_profile("target");
    assert_eq!(profile["oauthAccount"]["accountUuid"], "uuid-target");
}