chabeau 0.7.3

A full-screen terminal chat interface that connects to various AI APIs for real-time conversations
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
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

use crate::character::{png_text, CharacterCard};
use base64::Engine;

/// Errors that can occur when loading character cards.
#[derive(Debug)]
pub enum CardLoadError {
    /// Character card file could not be found or read from disk.
    FileNotFound(String),

    /// JSON parsing failed (malformed JSON in card file or PNG metadata).
    InvalidJson(String),

    /// PNG image parsing failed (corrupted or invalid PNG file).
    InvalidPng(String),

    /// Required PNG metadata chunk is missing from character card image.
    MissingMetadata(String),

    /// Character card validation failed (invalid or missing required fields).
    ValidationFailed(Vec<String>),
}

impl fmt::Display for CardLoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CardLoadError::FileNotFound(msg) => {
                write!(f, "File not found: {}", msg)
            }
            CardLoadError::InvalidJson(msg) => {
                write!(f, "Invalid JSON: {}", msg)
            }
            CardLoadError::InvalidPng(msg) => {
                write!(f, "Invalid PNG: {}", msg)
            }
            CardLoadError::MissingMetadata(msg) => {
                write!(f, "Missing metadata: {}", msg)
            }
            CardLoadError::ValidationFailed(errors) => {
                writeln!(f, "Card validation failed:")?;
                for error in errors {
                    writeln!(f, "  • {}", error)?;
                }
                Ok(())
            }
        }
    }
}

impl std::error::Error for CardLoadError {}

/// Get the cards directory path
/// Returns the path to the cards directory in the config directory
/// unless `CHABEAU_CARDS_DIR` is set to override it.
pub fn get_cards_dir() -> PathBuf {
    if let Some(override_dir) = std::env::var_os("CHABEAU_CARDS_DIR") {
        return PathBuf::from(override_dir);
    }

    let proj_dirs = directories::ProjectDirs::from("org", "permacommons", "chabeau")
        .expect("Failed to determine config directory");
    proj_dirs.config_dir().join("cards")
}

/// List all available character cards in the cards directory
/// Returns a vector of tuples containing (character_name, file_path)
pub fn list_available_cards() -> Result<Vec<(String, PathBuf)>, Box<dyn std::error::Error>> {
    let cards_dir = get_cards_dir();

    // If the cards directory doesn't exist, return an empty list
    if !cards_dir.exists() {
        return Ok(Vec::new());
    }

    let mut cards = Vec::new();

    // Scan the directory for card files
    for entry in fs::read_dir(cards_dir)? {
        let entry = entry?;
        let path = entry.path();

        // Only process files (not directories)
        if path.is_file() {
            let extension = path
                .extension()
                .and_then(|e| e.to_str())
                .map(|s| s.to_lowercase());

            // Check if it's a JSON or PNG file
            if matches!(extension.as_deref(), Some("json") | Some("png")) {
                // Try to load the card to get its name
                // If loading fails, skip this file (it will be logged elsewhere)
                match load_card(&path) {
                    Ok(card) => {
                        cards.push((card.data.name.clone(), path));
                    }
                    Err(_) => {
                        // Skip invalid cards silently during listing
                        // The error will be shown when the user tries to use the card
                    }
                }
            }
        }
    }

    // Sort by character name for consistent ordering
    cards.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(cards)
}

/// Load a character card from a file (JSON or PNG)
/// Automatically detects the file type based on extension
pub fn load_card<P: AsRef<Path>>(path: P) -> Result<CharacterCard, CardLoadError> {
    let path = path.as_ref();
    let extension = path
        .extension()
        .and_then(|e| e.to_str())
        .map(|s| s.to_lowercase());

    match extension.as_deref() {
        Some("json") => load_json_card(path),
        Some("png") => load_png_card(path),
        _ => Err(CardLoadError::InvalidJson(format!(
            "{}: File must be .json or .png",
            path.display()
        ))),
    }
}

/// Load a character card from a JSON file
pub fn load_json_card<P: AsRef<Path>>(path: P) -> Result<CharacterCard, CardLoadError> {
    let path = path.as_ref();

    // Read file contents
    let contents = fs::read_to_string(path)
        .map_err(|e| CardLoadError::FileNotFound(format!("{}: {}", path.display(), e)))?;

    // Parse JSON
    let card: CharacterCard = serde_json::from_str(&contents)
        .map_err(|e| CardLoadError::InvalidJson(format!("{}: {}", path.display(), e)))?;

    // Validate the card
    validate_card(&card)?;

    Ok(card)
}

/// Load a character card from a PNG file with embedded metadata
pub fn load_png_card<P: AsRef<Path>>(path: P) -> Result<CharacterCard, CardLoadError> {
    let path = path.as_ref();

    let data = fs::read(path)
        .map_err(|e| CardLoadError::FileNotFound(format!("{}: {}", path.display(), e)))?;

    let chara_text = match png_text::extract_text(&data, "chara") {
        Ok(text) => text,
        Err(png_text::PngTextError::MissingKeyword(_)) => {
            return Err(CardLoadError::MissingMetadata(format!(
                "{}: PNG does not contain 'chara' metadata in tEXt chunk",
                path.display()
            )))
        }
        Err(err) => {
            return Err(CardLoadError::InvalidPng(format!(
                "{}: {}",
                path.display(),
                err
            )))
        }
    };

    // Base64 decode the chara data
    let decoded = base64::prelude::BASE64_STANDARD
        .decode(chara_text.as_bytes())
        .map_err(|e| {
            CardLoadError::InvalidJson(format!("{}: Base64 decode failed: {}", path.display(), e))
        })?;

    // Convert to UTF-8 string
    let json_str = String::from_utf8(decoded).map_err(|e| {
        CardLoadError::InvalidJson(format!("{}: UTF-8 decode failed: {}", path.display(), e))
    })?;

    // Parse JSON
    let card: CharacterCard = serde_json::from_str(&json_str)
        .map_err(|e| CardLoadError::InvalidJson(format!("{}: {}", path.display(), e)))?;

    // Validate the card
    validate_card(&card)?;

    Ok(card)
}

/// Validate a character card against the v2 specification
pub fn validate_card(card: &CharacterCard) -> Result<(), CardLoadError> {
    let mut errors = Vec::new();

    // Check spec field
    if card.spec != "chara_card_v2" {
        errors.push(format!(
            "Invalid spec field: expected 'chara_card_v2', got '{}'",
            card.spec
        ));
    }

    // Check that name is not empty (this is the most critical field)
    if card.data.name.is_empty() {
        errors.push("Character name is required and cannot be empty".to_string());
    }

    // Note: Other fields (description, personality, scenario, first_mes, mes_example)
    // are required by the struct definition (serde will fail if they're missing),
    // but they can be empty strings in practice. Many real-world character cards
    // have empty values for some of these fields.

    if !errors.is_empty() {
        return Err(CardLoadError::ValidationFailed(errors));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::character::png_text;
    use crate::character::test_helpers::helpers::{create_test_character, create_valid_card_json};
    use crate::utils::test_utils::TestEnvVarGuard;
    use crc32fast::Hasher;
    use std::fs;
    use std::io::Write;
    use tempfile::{Builder, NamedTempFile, TempDir};

    struct CardsDirTestEnv {
        _env_guard: TestEnvVarGuard,
        temp_dir: TempDir,
    }

    impl CardsDirTestEnv {
        fn new() -> Self {
            let temp_dir = TempDir::new().expect("failed to create temp cards dir");
            let mut env_guard = TestEnvVarGuard::new();
            env_guard.set_var("CHABEAU_CARDS_DIR", temp_dir.path().as_os_str());

            Self {
                _env_guard: env_guard,
                temp_dir,
            }
        }

        fn path(&self) -> &std::path::Path {
            self.temp_dir.path()
        }
    }

    fn create_simple_test_card_json() -> String {
        let mut card: CharacterCard = serde_json::from_str(&create_valid_card_json()).unwrap();
        card.data.name = "Simple Test Character".to_string();
        card.data.description = "A simple test character for validation".to_string();
        card.data.scenario = "Testing the character card loader".to_string();
        card.data.mes_example = "{{user}}: Hi
{{char}}: Hello there!"
            .to_string();
        serde_json::to_string(&card).unwrap()
    }

    fn create_invalid_test_card_json() -> String {
        let mut card: CharacterCard = serde_json::from_str(&create_valid_card_json()).unwrap();
        card.spec = "wrong_spec".to_string();
        card.data.name.clear();
        card.data.description = "Invalid card".to_string();
        card.data.personality = "Test".to_string();
        card.data.scenario = "Test".to_string();
        card.data.first_mes = "Test".to_string();
        card.data.mes_example = "Test".to_string();
        serde_json::to_string(&card).unwrap()
    }

    fn write_json_to_tempfile(contents: &str) -> NamedTempFile {
        let mut temp_file = Builder::new()
            .suffix(".json")
            .tempfile()
            .expect("failed to create temp json file");
        temp_file.write_all(contents.as_bytes()).unwrap();
        temp_file.flush().unwrap();
        temp_file
    }

    const IHDR_DATA: [u8; 13] = [
        0x00, 0x00, 0x00, 0x01, // width = 1
        0x00, 0x00, 0x00, 0x01, // height = 1
        0x08, // bit depth
        0x02, // color type (truecolor)
        0x00, // compression method
        0x00, // filter method
        0x00, // interlace method
    ];

    const IDAT_DATA: [u8; 12] = [
        0x78, 0xDA, 0x63, 0x60, 0x60, 0x60, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01,
    ];

    fn png_chunk(chunk_type: [u8; 4], data: &[u8]) -> Vec<u8> {
        let mut chunk = Vec::with_capacity(12 + data.len());
        chunk.extend_from_slice(&(data.len() as u32).to_be_bytes());
        chunk.extend_from_slice(&chunk_type);
        chunk.extend_from_slice(data);
        let mut hasher = Hasher::new();
        hasher.update(&chunk_type);
        hasher.update(data);
        chunk.extend_from_slice(&hasher.finalize().to_be_bytes());
        chunk
    }

    fn assemble_png(chara_payload: Option<&[u8]>) -> Vec<u8> {
        let mut png = Vec::new();
        png.extend_from_slice(&png_text::PNG_SIGNATURE);
        png.extend_from_slice(&png_chunk(*b"IHDR", &IHDR_DATA));
        if let Some(payload) = chara_payload {
            let mut text_data = Vec::with_capacity("chara".len() + 1 + payload.len());
            text_data.extend_from_slice(b"chara");
            text_data.push(0);
            text_data.extend_from_slice(payload);
            png.extend_from_slice(&png_chunk(*b"tEXt", &text_data));
        }
        png.extend_from_slice(&png_chunk(*b"IDAT", &IDAT_DATA));
        png.extend_from_slice(&png_chunk(*b"IEND", &[]));
        png
    }

    fn build_png_with_text(text: &[u8]) -> Vec<u8> {
        assemble_png(Some(text))
    }

    fn build_png_without_text() -> Vec<u8> {
        assemble_png(None)
    }

    #[test]
    fn test_load_valid_json_card() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file
            .write_all(create_valid_card_json().as_bytes())
            .unwrap();
        temp_file.flush().unwrap();

        let result = load_json_card(temp_file.path());
        assert!(result.is_ok());

        let card = result.unwrap();
        assert_eq!(card.spec, "chara_card_v2");
        assert_eq!(card.data.name, "Test Character");
        assert_eq!(card.data.description, "A test character for unit tests");
    }

    #[test]
    fn test_load_json_card_with_optional_fields() {
        let json = serde_json::json!({
            "spec": "chara_card_v2",
            "spec_version": "2.0",
            "data": {
                "name": "Test Character",
                "description": "A test character",
                "personality": "Friendly",
                "scenario": "Testing",
                "first_mes": "Hello!",
                "mes_example": "Example",
                "creator_notes": "Some notes",
                "system_prompt": "You are helpful",
                "post_history_instructions": "Be polite",
                "alternate_greetings": ["Hi!", "Hey!"],
                "tags": ["test", "friendly"],
                "creator": "Test Creator",
                "character_version": "1.0"
            }
        })
        .to_string();

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(json.as_bytes()).unwrap();
        temp_file.flush().unwrap();

        let result = load_json_card(temp_file.path());
        assert!(result.is_ok());

        let card = result.unwrap();
        assert_eq!(card.data.creator_notes, Some("Some notes".to_string()));
        assert_eq!(card.data.system_prompt, Some("You are helpful".to_string()));
        assert_eq!(
            card.data.post_history_instructions,
            Some("Be polite".to_string())
        );
        assert_eq!(card.data.alternate_greetings.as_ref().unwrap().len(), 2);
        assert_eq!(card.data.tags.as_ref().unwrap().len(), 2);
        assert_eq!(card.data.creator, Some("Test Creator".to_string()));
        assert_eq!(card.data.character_version, Some("1.0".to_string()));
    }

    #[test]
    fn test_load_json_card_file_not_found() {
        let result = load_json_card("/nonexistent/path/to/card.json");
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::FileNotFound(msg) => {
                assert!(msg.contains("/nonexistent/path/to/card.json"));
            }
            _ => panic!("Expected FileNotFound error"),
        }
    }

    #[test]
    fn test_load_json_card_invalid_json() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"{ invalid json }").unwrap();
        temp_file.flush().unwrap();

        let result = load_json_card(temp_file.path());
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::InvalidJson(_) => {}
            _ => panic!("Expected InvalidJson error"),
        }
    }

    #[test]
    fn test_load_json_card_missing_required_field() {
        let json = serde_json::json!({
            "spec": "chara_card_v2",
            "spec_version": "2.0",
            "data": {
                "name": "Test Character",
                "description": "A test character",
                "personality": "Friendly",
                "scenario": "Testing",
                // Missing first_mes
                "mes_example": "Example"
            }
        })
        .to_string();

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(json.as_bytes()).unwrap();
        temp_file.flush().unwrap();

        let result = load_json_card(temp_file.path());
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::InvalidJson(_) => {}
            _ => panic!("Expected InvalidJson error for missing required field"),
        }
    }

    #[test]
    fn test_validate_card_valid() {
        let card = create_test_character("Test", "Hello");

        let result = validate_card(&card);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_card_invalid_spec() {
        let mut card = create_test_character("Test", "Hello");
        card.spec = "invalid_spec".to_string();

        let result = validate_card(&card);
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::ValidationFailed(errors) => {
                assert_eq!(errors.len(), 1);
                assert!(errors[0].contains("Invalid spec field"));
            }
            _ => panic!("Expected ValidationFailed error"),
        }
    }

    #[test]
    fn test_validate_card_empty_name() {
        let mut card = create_test_character("Test", "Hello");
        card.data.name.clear();

        let result = validate_card(&card);
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::ValidationFailed(errors) => {
                assert!(errors.iter().any(|e| e.contains("name")));
            }
            _ => panic!("Expected ValidationFailed error"),
        }
    }

    #[test]
    fn test_validate_card_multiple_errors() {
        let mut card = create_test_character("Test", "Hello");
        card.spec = "invalid_spec".to_string();
        card.data.name.clear();
        card.data.description.clear();
        card.data.personality.clear();
        card.data.scenario.clear();
        card.data.first_mes.clear();

        let result = validate_card(&card);
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::ValidationFailed(errors) => {
                assert_eq!(errors.len(), 2); // invalid spec and empty name
            }
            _ => panic!("Expected ValidationFailed error"),
        }
    }

    #[test]
    fn test_validate_card_empty_fields_allowed() {
        // Test that empty strings are allowed for most fields (except name)
        let mut card = create_test_character("Test", "Hello");
        card.data.description.clear();
        card.data.personality.clear();
        card.data.scenario.clear();
        card.data.first_mes.clear();
        card.data.mes_example.clear();

        let result = validate_card(&card);
        assert!(result.is_ok());
    }

    #[test]
    fn test_card_load_error_display() {
        let error = CardLoadError::FileNotFound("test.json: No such file".to_string());
        assert_eq!(
            format!("{}", error),
            "File not found: test.json: No such file"
        );

        let error = CardLoadError::InvalidJson("test.json: Parse error".to_string());
        assert_eq!(format!("{}", error), "Invalid JSON: test.json: Parse error");

        let error =
            CardLoadError::ValidationFailed(vec!["Error 1".to_string(), "Error 2".to_string()]);
        let display = format!("{}", error);
        assert!(display.contains("Card validation failed"));
        assert!(display.contains("Error 1"));
        assert!(display.contains("Error 2"));
    }

    #[test]
    fn test_load_hypatia_json() {
        let hypatia_path = "examples/hypatia.json";
        if std::path::Path::new(hypatia_path).exists() {
            let result = load_json_card(hypatia_path);
            assert!(
                result.is_ok(),
                "Failed to load hypatia.json: {:?}",
                result.err()
            );

            let card = result.unwrap();
            assert_eq!(card.spec, "chara_card_v2");
            assert_eq!(card.data.name, "Hypatia of Alexandria");
            assert!(!card.data.description.is_empty());
            assert!(!card.data.first_mes.is_empty());
            assert_eq!(card.data.creator, Some("Chabeau Examples".to_string()));
            assert!(card.data.tags.is_some());
        }
    }

    #[test]
    fn test_load_simple_test_card() {
        let card_json = create_simple_test_card_json();
        let temp_file = write_json_to_tempfile(&card_json);

        let result = load_json_card(temp_file.path());
        assert!(result.is_ok(), "Failed to load simple test card");

        let card = result.unwrap();
        assert_eq!(card.spec, "chara_card_v2");
        assert_eq!(card.data.name, "Simple Test Character");
        assert_eq!(
            card.data.description,
            "A simple test character for validation"
        );
        assert_eq!(card.data.personality, "Friendly and helpful");
    }

    #[test]
    fn test_load_invalid_test_card() {
        let card_json = create_invalid_test_card_json();
        let temp_file = write_json_to_tempfile(&card_json);

        let result = load_json_card(temp_file.path());
        assert!(result.is_err(), "Expected error loading invalid test card");

        match result.unwrap_err() {
            CardLoadError::ValidationFailed(errors) => {
                assert!(!errors.is_empty());
                assert!(errors
                    .iter()
                    .any(|e| e.contains("spec") || e.contains("name")));
            }
            _ => panic!("Expected ValidationFailed error"),
        }
    }

    // PNG loading tests

    #[test]
    fn test_load_png_card_with_metadata() {
        // Create character card JSON
        let card_json = create_valid_card_json();
        let encoded = base64::prelude::BASE64_STANDARD.encode(card_json.as_bytes());
        let png_bytes = build_png_with_text(encoded.as_bytes());

        let temp_file = NamedTempFile::new().unwrap();
        temp_file.as_file().write_all(&png_bytes).unwrap();

        // Now try to load the PNG card
        let result = load_png_card(temp_file.path());
        assert!(
            result.is_ok(),
            "Failed to load PNG card: {:?}",
            result.err()
        );

        let card = result.unwrap();
        assert_eq!(card.spec, "chara_card_v2");
        assert_eq!(card.data.name, "Test Character");
        assert_eq!(card.data.description, "A test character for unit tests");
    }

    #[test]
    fn test_load_png_card_without_metadata() {
        // Create a PNG without chara metadata
        let png_bytes = build_png_without_text();
        let temp_file = NamedTempFile::new().unwrap();
        temp_file.as_file().write_all(&png_bytes).unwrap();

        // Try to load the PNG card - should fail with MissingMetadata
        let result = load_png_card(temp_file.path());
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::MissingMetadata(msg) => {
                assert!(msg.contains("chara"));
            }
            _ => panic!("Expected MissingMetadata error"),
        }
    }

    #[test]
    fn test_load_png_card_invalid_base64() {
        let png_bytes = build_png_with_text(b"not-valid-base64!!!");
        let temp_file = NamedTempFile::new().unwrap();
        temp_file.as_file().write_all(&png_bytes).unwrap();

        let result = load_png_card(temp_file.path());
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::InvalidJson(msg) => {
                assert!(
                    msg.contains("Base64 decode failed")
                        || msg.contains("UTF-8 decode failed")
                        || msg.contains("expected")
                );
            }
            _ => panic!("Expected InvalidJson error"),
        }
    }

    #[test]
    fn test_load_png_card_invalid_json() {
        // Encode invalid JSON
        let invalid_json = "{ this is not valid json }";
        let encoded = base64::prelude::BASE64_STANDARD.encode(invalid_json.as_bytes());
        let png_bytes = build_png_with_text(encoded.as_bytes());

        let temp_file = NamedTempFile::new().unwrap();
        temp_file.as_file().write_all(&png_bytes).unwrap();

        let result = load_png_card(temp_file.path());
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::InvalidJson(_) => {}
            _ => panic!("Expected InvalidJson error"),
        }
    }

    #[test]
    fn test_load_png_card_file_not_found() {
        let result = load_png_card("/nonexistent/path/to/card.png");
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::FileNotFound(msg) => {
                assert!(msg.contains("/nonexistent/path/to/card.png"));
            }
            _ => panic!("Expected FileNotFound error"),
        }
    }

    #[test]
    fn test_load_png_card_not_a_png() {
        // Try to load a non-PNG file as PNG
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"This is not a PNG file").unwrap();
        temp_file.flush().unwrap();

        let result = load_png_card(temp_file.path());
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::InvalidPng(_) => {}
            _ => panic!("Expected InvalidPng error"),
        }
    }

    #[test]
    fn test_load_hypatia_png() {
        // Test with PNG file if it exists
        let hypatia_path = "examples/hypatia.png";
        if std::path::Path::new(hypatia_path).exists() {
            let result = load_png_card(hypatia_path);
            assert!(
                result.is_ok(),
                "Failed to load hypatia.png: {:?}",
                result.err()
            );

            let card = result.unwrap();
            assert_eq!(card.spec, "chara_card_v2");
            assert_eq!(card.data.name, "Hypatia of Alexandria");
            assert!(!card.data.description.is_empty());
            assert!(!card.data.first_mes.is_empty());
        }
    }

    #[test]
    fn test_load_spec_v2_png_cards() {
        // Test with the spec v2 PNG files if it exists
        let test_cards = ["examples/hypatia.png"];

        for card_path in &test_cards {
            if std::path::Path::new(card_path).exists() {
                let result = load_png_card(card_path);
                assert!(
                    result.is_ok(),
                    "Failed to load {}: {:?}",
                    card_path,
                    result.err()
                );

                let card = result.unwrap();
                assert_eq!(card.spec, "chara_card_v2");
                assert!(!card.data.name.is_empty());
                println!("Successfully loaded: {} ({})", card_path, card.data.name);
            }
        }
    }

    #[test]
    fn test_png_and_json_equivalence() {
        // If both exist, they should have the same data
        let json_path = "examples/hypatia.json";
        let png_path = "examples/hypatia.png";

        if std::path::Path::new(json_path).exists() && std::path::Path::new(png_path).exists() {
            let json_card = load_json_card(json_path).unwrap();
            let png_card = load_png_card(png_path).unwrap();

            assert_eq!(json_card.spec, png_card.spec);
            assert_eq!(json_card.data.name, png_card.data.name);
            assert_eq!(json_card.data.description, png_card.data.description);
            assert_eq!(json_card.data.personality, png_card.data.personality);
            assert_eq!(json_card.data.scenario, png_card.data.scenario);
            assert_eq!(json_card.data.first_mes, png_card.data.first_mes);
        }
    }

    #[test]
    fn test_card_load_error_display_png_errors() {
        let error = CardLoadError::InvalidPng("test.png: Invalid format".to_string());
        assert_eq!(
            format!("{}", error),
            "Invalid PNG: test.png: Invalid format"
        );

        let error = CardLoadError::MissingMetadata("test.png: No chara chunk".to_string());
        assert_eq!(
            format!("{}", error),
            "Missing metadata: test.png: No chara chunk"
        );
    }

    // Card discovery tests

    #[test]
    fn test_get_cards_dir() {
        let mut env_guard = TestEnvVarGuard::new();
        env_guard.remove_var("CHABEAU_CARDS_DIR");

        let cards_dir = get_cards_dir();
        assert!(cards_dir.to_string_lossy().contains("chabeau"));
        assert!(cards_dir.to_string_lossy().contains("cards"));
    }

    #[test]
    fn test_get_cards_dir_env_override() {
        let mut env_guard = TestEnvVarGuard::new();
        let temp_dir = tempfile::tempdir().unwrap();

        env_guard.set_var("CHABEAU_CARDS_DIR", temp_dir.path().as_os_str());

        let cards_dir = get_cards_dir();
        assert_eq!(cards_dir, temp_dir.path());
    }

    #[test]
    fn test_list_available_cards_empty_directory() {
        // Ensure the cards directory is isolated per test
        let _cards_env = CardsDirTestEnv::new();

        let result = list_available_cards();
        assert!(result.is_ok());

        let cards = result.unwrap();
        assert!(cards.is_empty());
    }

    #[test]
    fn test_list_available_cards_with_test_cards() {
        let env = CardsDirTestEnv::new();
        let card_path = env.path().join("sample_card.json");

        let card_json = serde_json::json!({
            "spec": "chara_card_v2",
            "spec_version": "2.0",
            "data": {
                "name": "Temp Tester",
                "description": "Temporary card for list tests",
                "personality": "Curious",
                "scenario": "Running unit tests",
                "first_mes": "Hello from a temp card!",
                "mes_example": "{{user}}: Hi\n{{char}}: Hello!"
            }
        });

        fs::write(
            &card_path,
            serde_json::to_string_pretty(&card_json).unwrap(),
        )
        .unwrap();

        let result = list_available_cards();
        assert!(result.is_ok());

        let cards = result.unwrap();
        assert_eq!(cards.len(), 1);
        assert_eq!(cards[0].0, "Temp Tester");
        assert_eq!(cards[0].1, card_path);
    }

    #[test]
    fn test_load_card_json() {
        let card_json = create_simple_test_card_json();
        let temp_file = write_json_to_tempfile(&card_json);

        let result = load_card(temp_file.path());
        assert!(result.is_ok());

        let card = result.unwrap();
        assert_eq!(card.data.name, "Simple Test Character");
    }

    #[test]
    fn test_load_card_png() {
        // Test loading a PNG card through the load_card function
        let test_path = "examples/hypatia.png";
        if std::path::Path::new(test_path).exists() {
            let result = load_card(test_path);
            assert!(result.is_ok());

            let card = result.unwrap();
            assert_eq!(card.data.name, "Hypatia of Alexandria");
        }
    }

    #[test]
    fn test_load_card_invalid_extension() {
        let mut temp_file = NamedTempFile::with_suffix(".txt").unwrap();
        temp_file.write_all(b"some content").unwrap();
        temp_file.flush().unwrap();

        let result = load_card(temp_file.path());
        assert!(result.is_err());

        match result.unwrap_err() {
            CardLoadError::InvalidJson(msg) => {
                assert!(msg.contains("must be .json or .png"));
            }
            _ => panic!("Expected InvalidJson error for invalid extension"),
        }
    }

    #[test]
    fn test_card_discovery_with_temp_directory() {
        // Create a temporary directory structure to test card discovery
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create a valid JSON card
        let card1_path = temp_path.join("alice.json");
        fs::write(&card1_path, create_valid_card_json()).unwrap();

        // Create another valid JSON card with different name
        let card2_json = serde_json::json!({
            "spec": "chara_card_v2",
            "spec_version": "2.0",
            "data": {
                "name": "Bob",
                "description": "Another test character",
                "personality": "Serious",
                "scenario": "Testing",
                "first_mes": "Hello, I'm Bob.",
                "mes_example": "Example"
            }
        })
        .to_string();
        let card2_path = temp_path.join("bob.json");
        fs::write(&card2_path, card2_json).unwrap();

        // Create an invalid file that should be skipped
        let invalid_path = temp_path.join("invalid.json");
        fs::write(&invalid_path, "not valid json").unwrap();

        // Create a non-card file that should be ignored
        let other_path = temp_path.join("readme.txt");
        fs::write(&other_path, "This is not a card").unwrap();

        // Note: We can't easily test list_available_cards() with a temp directory
        // because it uses the actual config directory. Instead, we test the logic
        // by manually scanning the temp directory using the same pattern.

        let mut cards = Vec::new();
        for entry in fs::read_dir(temp_path).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();

            if path.is_file() {
                let extension = path
                    .extension()
                    .and_then(|e| e.to_str())
                    .map(|s| s.to_lowercase());

                if matches!(extension.as_deref(), Some("json") | Some("png")) {
                    if let Ok(card) = load_card(&path) {
                        cards.push((card.data.name.clone(), path));
                    }
                }
            }
        }

        cards.sort_by(|a, b| a.0.cmp(&b.0));

        // Should have found 2 valid cards (alice and bob), skipped invalid and readme
        assert_eq!(cards.len(), 2);
        assert_eq!(cards[0].0, "Bob");
        assert_eq!(cards[1].0, "Test Character");
    }

    #[test]
    fn test_card_discovery_prefers_json_over_png() {
        // Test that when both .json and .png exist with the same name,
        // the search finds the .json first
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create both JSON and PNG versions
        let json_path = temp_path.join("character.json");
        let png_path = temp_path.join("character.png");

        fs::write(&json_path, create_valid_card_json()).unwrap();
        // Create a dummy PNG file (we're just testing the search order)
        fs::write(&png_path, b"fake png").unwrap();

        // Test the search order logic
        let name = "character";
        let mut found_path = None;

        for ext in &["json", "png"] {
            let path = temp_path.join(format!("{}.{}", name, ext));
            if path.exists() {
                found_path = Some(path);
                break;
            }
        }

        assert!(found_path.is_some());
        assert_eq!(found_path.unwrap(), json_path);
    }

    #[test]
    fn test_list_cards_ignores_subdirectories() {
        // Test that subdirectories are ignored during card discovery
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create a valid card file
        let card_path = temp_path.join("valid.json");
        fs::write(&card_path, create_valid_card_json()).unwrap();

        // Create a subdirectory with a card in it (should be ignored)
        let subdir = temp_path.join("subdir");
        fs::create_dir(&subdir).unwrap();
        let subcard_path = subdir.join("subcard.json");
        fs::write(&subcard_path, create_valid_card_json()).unwrap();

        // Scan the directory (simulating list_available_cards logic)
        let mut cards = Vec::new();
        for entry in fs::read_dir(temp_path).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();

            // Only process files, not directories
            if path.is_file() {
                let extension = path
                    .extension()
                    .and_then(|e| e.to_str())
                    .map(|s| s.to_lowercase());

                if matches!(extension.as_deref(), Some("json") | Some("png")) {
                    if let Ok(card) = load_card(&path) {
                        cards.push((card.data.name.clone(), path));
                    }
                }
            }
        }

        // Should only find the card in the root directory, not the subdirectory
        assert_eq!(cards.len(), 1);
        assert_eq!(cards[0].1, card_path);
    }
}