chatpack 0.5.1

Prepare chat data for RAG / LLM ingestion. Supports Telegram, WhatsApp, Instagram, Discord.
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
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
//! Property-based tests for chatpack using proptest.
//!
//! These tests generate random inputs to find edge cases and verify invariants.
//! Covers all major parsing functions, transformations, and output formats.

use proptest::prelude::*;
use serde_json::{Value, json};

use chatpack::core::output::{to_csv, to_json, to_jsonl};
use chatpack::core::{FilterConfig, Message, OutputConfig, apply_filters, merge_consecutive};
use chatpack::parsing::discord::{
    DiscordAttachment, DiscordAuthor, DiscordRawMessage, DiscordReference, DiscordSticker,
    parse_discord_message,
};
use chatpack::parsing::instagram::{
    InstagramRawMessage, InstagramShare, fix_mojibake_encoding, parse_instagram_message,
    parse_instagram_message_owned,
};
use chatpack::parsing::telegram::{
    TelegramRawMessage, extract_telegram_text, parse_telegram_message, parse_unix_timestamp,
};
use chatpack::parsing::whatsapp::{
    DateFormat, detect_whatsapp_format, is_whatsapp_system_message, parse_whatsapp_timestamp,
};

// =============================================================================
// STRATEGY DEFINITIONS
// =============================================================================

/// Generate a random Message using fast strategies (no regex!)
fn arb_message() -> impl Strategy<Value = Message> {
    (
        // Fast: select from predefined senders
        prop::sample::select(vec![
            "Alice".to_string(),
            "Bob".to_string(),
            "Charlie".to_string(),
            "User123".to_string(),
            "ะ˜ะฒะฐะฝ".to_string(),
            "Test".to_string(),
            "ๆ—ฅๆœฌ่ชž".to_string(),
            "ู…ุณุชุฎุฏู…".to_string(),
        ]),
        // Fast: select from predefined contents
        prop::sample::select(vec![
            "Hello".to_string(),
            "Hi there!".to_string(),
            "How are you?".to_string(),
            "Good morning".to_string(),
            "Test message 123".to_string(),
            "ะŸั€ะธะฒะตั‚ ะผะธั€".to_string(),
            String::new(),
            "   ".to_string(),
            "Special;chars\"here\nnewline".to_string(),
            "๐ŸŽ‰๐Ÿ”ฅ๐Ÿ’€ emoji".to_string(),
            "ๆ—ฅๆœฌ่ชžใƒ†ใ‚นใƒˆ".to_string(),
            "ู…ุฑุญุจุง ุจุงู„ุนุงู„ู…".to_string(),
            "Mixed ะขะตัั‚ ๆ—ฅๆœฌ ๐ŸŽ‰".to_string(),
            "\t\n\r special whitespace".to_string(),
            "a]b[c{d}e".to_string(),
        ]),
    )
        .prop_map(|(sender, content)| Message {
            sender,
            content,
            timestamp: None,
            id: None,
            reply_to: None,
            edited: None,
        })
}

/// Generate a Message with optional timestamp
fn arb_message_with_timestamp() -> impl Strategy<Value = Message> {
    (
        prop::sample::select(vec!["Alice", "Bob", "Charlie", "User"]),
        prop::sample::select(vec!["Hello", "Test", "Message", ""]),
        prop::option::of(1700000000i64..1800000000i64),
    )
        .prop_map(|(sender, content, ts_opt)| {
            let mut msg = Message::new(sender, content);
            if let Some(ts) = ts_opt {
                msg.timestamp = chrono::DateTime::from_timestamp(ts, 0);
            }
            msg
        })
}

/// Generate a vector of random messages
fn arb_messages(max_len: usize) -> impl Strategy<Value = Vec<Message>> {
    prop::collection::vec(arb_message(), 0..max_len)
}

/// Generate messages with timestamps for filter testing
fn arb_messages_with_ts(max_len: usize) -> impl Strategy<Value = Vec<Message>> {
    prop::collection::vec(arb_message_with_timestamp(), 0..max_len)
}

/// Generate arbitrary JSON values for Telegram text extraction
fn arb_telegram_text_value() -> impl Strategy<Value = Value> {
    prop_oneof![
        // Simple string
        prop::sample::select(vec![
            json!("Hello"),
            json!("Test message"),
            json!("ะŸั€ะธะฒะตั‚ ะผะธั€"),
            json!("๐ŸŽ‰ emoji"),
            json!(""),
            json!("   "),
        ]),
        // Array with strings
        prop::sample::select(vec![
            json!(["Hello", " ", "World"]),
            json!(["Part1", "Part2", "Part3"]),
            json!([]),
        ]),
        // Array with objects (links, mentions, etc.)
        prop::sample::select(vec![
            json!(["Check: ", {"type": "link", "text": "https://example.com"}]),
            json!([{"type": "mention", "text": "@user"}, " said hello"]),
            json!(["Mixed ", {"type": "bold", "text": "bold"}, " text"]),
        ]),
        // Complex nested
        prop::sample::select(vec![
            json!(["A", {"type": "link", "text": "B"}, "C", {"type": "mention", "text": "D"}]),
            json!([{"type": "unknown"}, "text"]), // Object without text field
        ]),
        // Edge cases
        prop::sample::select(vec![
            json!(null),
            json!(123),
            json!(true),
            json!({"text": "object at root"}),
        ]),
    ]
}

/// Generate Unix timestamp strings for testing
fn arb_unix_timestamp_str() -> impl Strategy<Value = String> {
    prop_oneof![
        // Valid timestamps
        (1000000000i64..2000000000i64).prop_map(|ts| ts.to_string()),
        // Edge cases
        Just("0".to_string()),
        Just("1".to_string()),
        Just("-1".to_string()),
        Just("9999999999".to_string()),
        // Invalid
        Just(String::new()),
        Just("not_a_number".to_string()),
        Just("12.34".to_string()),
        Just("123abc".to_string()),
    ]
}

/// Generate WhatsApp format test lines
fn arb_whatsapp_line() -> impl Strategy<Value = String> {
    prop_oneof![
        // US format: [M/D/YY, H:MM:SS AM/PM]
        Just("[1/15/24, 10:30:45 AM] Alice: Hello".to_string()),
        Just("[12/31/23, 11:59:59 PM] Bob: Bye".to_string()),
        // EU Dot Bracketed: [DD.MM.YY, HH:MM:SS]
        Just("[15.01.24, 10:30:45] Alice: Hello".to_string()),
        Just("[31.12.23, 23:59:59] Bob: Bye".to_string()),
        // EU Dot No Bracket: DD.MM.YYYY, HH:MM -
        Just("15.01.2024, 10:30 - Alice: Hello".to_string()),
        Just("26.10.2025, 20:40 - Bob: Test".to_string()),
        // EU Slash: DD/MM/YYYY, HH:MM -
        Just("15/01/2024, 10:30 - Alice: Hello".to_string()),
        Just("31/12/2023, 23:59 - Bob: Bye".to_string()),
        // EU Slash Bracketed: [DD/MM/YYYY, HH:MM:SS]
        Just("[15/01/2024, 10:30:45] Alice: Hello".to_string()),
        // Invalid/continuation lines
        Just("This is a continuation".to_string()),
        Just("No date format here".to_string()),
        Just(String::new()),
    ]
}

/// Generate sender names for system message testing
fn arb_sender() -> impl Strategy<Value = String> {
    prop::sample::select(vec![
        "Alice".to_string(),
        "Bob".to_string(),
        "WhatsApp".to_string(),
        "System".to_string(),
        String::new(),
        "   ".to_string(),
        "ะ˜ะฒะฐะฝ".to_string(),
        "user123".to_string(),
    ])
}

/// Generate content for system message testing
fn arb_content_for_system_check() -> impl Strategy<Value = String> {
    prop::sample::select(vec![
        "created group \"Test\"".to_string(),
        "added Charlie to the group".to_string(),
        "removed Dave from the group".to_string(),
        "changed the subject to \"New Name\"".to_string(),
        "security code changed".to_string(),
        "You're now an admin".to_string(),
        "ะกะพะพะฑั‰ะตะฝะธั ะธ ะทะฒะพะฝะบะธ ะทะฐั‰ะธั‰ะตะฝั‹ ัะบะฒะพะทะฝั‹ะผ ัˆะธั„ั€ะพะฒะฐะฝะธะตะผ".to_string(),
        "ัะพะทะดะฐะป(ะฐ) ะณั€ัƒะฟะฟัƒ".to_string(),
    ])
}

/// Generate strings for mojibake testing
fn arb_mojibake_input() -> impl Strategy<Value = String> {
    prop::sample::select(vec![
        // ASCII (should pass through)
        "Hello World".to_string(),
        "Test 123".to_string(),
        String::new(),
        // Non-ASCII that might be mojibake
        "ะŸั€ะธะฒะตั‚".to_string(),
        "ๆ—ฅๆœฌ่ชž".to_string(),
        "๐ŸŽ‰๐Ÿ”ฅ".to_string(),
        "ู…ุฑุญุจุง".to_string(),
        // Mixed
        "Hello ะŸั€ะธะฒะตั‚ ๆ—ฅๆœฌ".to_string(),
    ])
}

/// Generate Discord messages for testing
fn arb_discord_raw_message() -> impl Strategy<Value = DiscordRawMessage> {
    (
        prop::sample::select(vec!["123", "456789", "999999999999999999"]),
        prop::sample::select(vec![
            "2024-01-15T10:30:00+00:00",
            "2024-12-31T23:59:59+00:00",
            "2020-01-01T00:00:00Z",
        ]),
        prop::option::of(prop::sample::select(vec![
            "2024-01-15T11:00:00+00:00",
            "2024-12-31T23:59:59+00:00",
        ])),
        prop::sample::select(vec![
            "Hello".to_string(),
            "Test message".to_string(),
            String::new(),
            "   ".to_string(),
            "ะŸั€ะธะฒะตั‚ ๐ŸŽ‰".to_string(),
        ]),
        prop::sample::select(vec!["alice", "bob123", "ะขะตัั‚"]),
        prop::option::of(prop::sample::select(vec!["Alice", "Bob Display", "ะะธะบ"])),
        prop::option::of(prop::sample::select(vec!["111", "222"])),
        prop::bool::ANY,
        prop::bool::ANY,
    )
        .prop_map(
            |(id, ts, ts_edited, content, name, nickname, ref_id, has_attach, has_sticker)| {
                DiscordRawMessage {
                    id: id.to_string(),
                    timestamp: ts.to_string(),
                    timestamp_edited: ts_edited.map(|s| s.to_string()),
                    content,
                    author: DiscordAuthor {
                        name: name.to_string(),
                        nickname: nickname.map(|s| s.to_string()),
                    },
                    reference: ref_id.map(|id| DiscordReference {
                        message_id: Some(id.to_string()),
                    }),
                    attachments: if has_attach {
                        Some(vec![DiscordAttachment {
                            file_name: "test.png".to_string(),
                        }])
                    } else {
                        None
                    },
                    stickers: if has_sticker {
                        Some(vec![DiscordSticker {
                            name: "TestSticker".to_string(),
                        }])
                    } else {
                        None
                    },
                }
            },
        )
}

/// Generate Instagram raw messages for testing
fn arb_instagram_raw_message() -> impl Strategy<Value = InstagramRawMessage> {
    (
        prop::sample::select(vec!["user_one", "user_two", "ะขะตัั‚", "ๆ—ฅๆœฌ"]),
        1700000000000i64..1800000000000i64,
        prop::option::of(prop::sample::select(vec![
            "Hello!".to_string(),
            "ะŸั€ะธะฒะตั‚".to_string(),
            String::new(),
            "   ".to_string(),
            "๐ŸŽ‰ emoji".to_string(),
        ])),
        prop::bool::ANY,
    )
        .prop_map(|(sender, ts, content, has_share)| InstagramRawMessage {
            sender_name: sender.to_string(),
            timestamp_ms: ts,
            content,
            share: if has_share {
                Some(InstagramShare {
                    share_text: Some("Shared content".to_string()),
                    link: Some("https://example.com".to_string()),
                })
            } else {
                None
            },
            photos: None,
            videos: None,
            audio_files: None,
        })
}

/// Generate date strings for filter testing
fn arb_date_string() -> impl Strategy<Value = String> {
    prop_oneof![
        // Valid YYYY-MM-DD
        Just("2024-01-15".to_string()),
        Just("2024-12-31".to_string()),
        Just("2000-01-01".to_string()),
        Just("2099-12-31".to_string()),
        // Leap year
        Just("2024-02-29".to_string()),
        // Invalid formats
        Just("01-15-2024".to_string()),
        Just("15/01/2024".to_string()),
        Just("2024/01/15".to_string()),
        Just("not-a-date".to_string()),
        Just(String::new()),
        // Invalid dates
        Just("2023-02-29".to_string()), // Not a leap year
        Just("2024-13-01".to_string()), // Invalid month
        Just("2024-01-32".to_string()), // Invalid day
    ]
}

// =============================================================================
// MERGE PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(200))]

    /// Merge never increases message count
    #[test]
    fn merge_never_increases_count(messages in arb_messages(30)) {
        let original_len = messages.len();
        let merged = merge_consecutive(messages);
        prop_assert!(merged.len() <= original_len);
    }

    /// Empty input produces empty output
    #[test]
    fn merge_empty_is_empty(_dummy in Just(())) {
        let result = merge_consecutive(vec![]);
        prop_assert!(result.is_empty());
    }

    /// Single message stays single
    #[test]
    fn merge_single_stays_single(msg in arb_message()) {
        let result = merge_consecutive(vec![msg]);
        prop_assert_eq!(result.len(), 1);
    }

    /// Merge with same sender produces exactly one message
    #[test]
    fn merge_same_sender_produces_one(n in 1usize..10) {
        let messages: Vec<Message> = (0..n)
            .map(|i| Message {
                sender: "Alice".to_string(),
                content: format!("Message {}", i),
                timestamp: None,
                id: None,
                reply_to: None,
                edited: None,
            })
            .collect();
        let merged = merge_consecutive(messages);
        prop_assert_eq!(merged.len(), 1);
    }

    /// Merge preserves total content
    #[test]
    fn merge_preserves_content_parts(n in 1usize..5) {
        let messages: Vec<Message> = (0..n)
            .map(|i| Message {
                sender: "Alice".to_string(),
                content: format!("part{}", i),
                timestamp: None,
                id: None,
                reply_to: None,
                edited: None,
            })
            .collect();
        let merged = merge_consecutive(messages);
        for i in 0..n {
            let expected = format!("part{}", i);
            prop_assert!(merged[0].content.contains(&expected), "Missing part{}", i);
        }
    }

    /// Merge is idempotent: merge(merge(x)) == merge(x)
    #[test]
    fn merge_is_idempotent(messages in arb_messages(20)) {
        let first_merge = merge_consecutive(messages.clone());
        let second_merge = merge_consecutive(first_merge.clone());

        prop_assert_eq!(first_merge.len(), second_merge.len());
        for (m1, m2) in first_merge.iter().zip(second_merge.iter()) {
            prop_assert_eq!(&m1.sender, &m2.sender);
            prop_assert_eq!(&m1.content, &m2.content);
        }
    }

    /// Alternating senders produce same count
    #[test]
    fn merge_alternating_preserves_count(n in 1usize..10) {
        let messages: Vec<Message> = (0..n)
            .map(|i| Message {
                sender: if i % 2 == 0 { "Alice" } else { "Bob" }.to_string(),
                content: format!("Msg {}", i),
                timestamp: None,
                id: None,
                reply_to: None,
                edited: None,
            })
            .collect();
        let merged = merge_consecutive(messages.clone());
        prop_assert_eq!(merged.len(), messages.len());
    }
}

// =============================================================================
// FILTER PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(200))]

    /// Filter never increases message count
    #[test]
    fn filter_never_increases_count(messages in arb_messages(30)) {
        let original_len = messages.len();
        let config = FilterConfig::new();
        let filtered = apply_filters(messages, &config);
        prop_assert!(filtered.len() <= original_len);
    }

    /// No filter means passthrough
    #[test]
    fn no_filter_is_passthrough(messages in arb_messages(30)) {
        let original_len = messages.len();
        let config = FilterConfig::new();
        let filtered = apply_filters(messages, &config);
        prop_assert_eq!(filtered.len(), original_len);
    }

    /// User filter only keeps matching users (case insensitive)
    #[test]
    fn user_filter_only_keeps_matching(messages in arb_messages(30)) {
        let config = FilterConfig::new().with_user("Alice".to_string());
        let filtered = apply_filters(messages, &config);

        for msg in &filtered {
            prop_assert!(
                msg.sender.eq_ignore_ascii_case("Alice"),
                "Found non-matching sender: {}", msg.sender
            );
        }
    }

    /// Filter results are always subset of input
    #[test]
    fn filter_is_subset(messages in arb_messages_with_ts(20)) {
        let config = FilterConfig::new().with_user("Alice".to_string());
        let original_senders: Vec<_> = messages.iter().map(|m| m.sender.clone()).collect();
        let filtered = apply_filters(messages, &config);

        for msg in &filtered {
            prop_assert!(original_senders.contains(&msg.sender));
        }
    }

    /// Filter with non-existent user returns empty
    #[test]
    fn filter_nonexistent_user_empty(messages in arb_messages(20)) {
        let config = FilterConfig::new().with_user("NonExistentUser12345".to_string());
        let filtered = apply_filters(messages, &config);
        prop_assert!(filtered.is_empty());
    }

    /// Date filter excludes messages without timestamps
    #[test]
    fn date_filter_excludes_no_timestamp(messages in arb_messages(20)) {
        if let Ok(config) = FilterConfig::new().after_date("2024-01-01") {
            let filtered = apply_filters(messages, &config);
            // All filtered messages should have timestamps (or be empty)
            for msg in &filtered {
                prop_assert!(msg.timestamp.is_some() || filtered.is_empty());
            }
        }
    }
}

// =============================================================================
// ROBUSTNESS PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(300))]

    /// Merge never panics on any input
    #[test]
    fn merge_never_panics(messages in arb_messages(50)) {
        let _ = merge_consecutive(messages);
    }

    /// Filter never panics on any input
    #[test]
    fn filter_never_panics(messages in arb_messages(50)) {
        let config = FilterConfig::new().with_user("Test".to_string());
        let _ = apply_filters(messages, &config);
    }

    /// Messages with special characters don't break merge
    #[test]
    fn special_chars_dont_break_merge(sender in prop::sample::select(vec!["A", "B", "C"])) {
        let msg = Message {
            sender: sender.to_string(),
            content: "test;with\"special\nchars\ttab\r\n\0null".to_string(),
            timestamp: None,
            id: None,
            reply_to: None,
            edited: None,
        };
        let _ = merge_consecutive(vec![msg.clone(), msg]);
    }

    /// Unicode content is handled correctly
    #[test]
    fn unicode_content_preserved(idx in 0usize..7) {
        let contents = [
            "ะŸั€ะธะฒะตั‚",
            "ใ“ใ‚“ใซใกใฏ",
            "ู…ุฑุญุจุง",
            "๐ŸŽ‰๐Ÿ”ฅ๐Ÿ’€",
            "Mixed ะขะตัั‚ ๆ—ฅๆœฌ",
            "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ",  // ZWJ sequence
            "e\u{0301}", // Combining accent
        ];
        let content = contents[idx].to_string();
        let msg = Message {
            sender: "User".to_string(),
            content: content.clone(),
            timestamp: None,
            id: None,
            reply_to: None,
            edited: None,
        };
        let merged = merge_consecutive(vec![msg]);
        prop_assert_eq!(&merged[0].content, &content);
    }
}

// =============================================================================
// SERDE ROUNDTRIP PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(200))]

    /// Message serialization roundtrip
    #[test]
    fn message_serde_roundtrip(msg in arb_message()) {
        let json = serde_json::to_string(&msg).expect("serialize");
        let parsed: Message = serde_json::from_str(&json).expect("deserialize");
        prop_assert_eq!(msg.sender, parsed.sender);
        prop_assert_eq!(msg.content, parsed.content);
    }

    /// Message with all fields roundtrip
    #[test]
    fn message_full_serde_roundtrip(
        sender in prop::sample::select(vec!["Alice", "Bob"]),
        content in prop::sample::select(vec!["Hello", "Test"]),
        ts in 1700000000i64..1800000000i64,
        id in 1u64..1000u64,
        reply in prop::option::of(1u64..1000u64)
    ) {
        let msg = Message {
            sender: sender.to_string(),
            content: content.to_string(),
            timestamp: chrono::DateTime::from_timestamp(ts, 0),
            id: Some(id),
            reply_to: reply,
            edited: None,
        };

        let json = serde_json::to_string(&msg).expect("serialize");
        let parsed: Message = serde_json::from_str(&json).expect("deserialize");

        prop_assert_eq!(msg.sender, parsed.sender);
        prop_assert_eq!(msg.content, parsed.content);
        prop_assert_eq!(msg.id, parsed.id);
        prop_assert_eq!(msg.reply_to, parsed.reply_to);
    }
}

// =============================================================================
// TELEGRAM PARSING PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(200))]

    /// extract_telegram_text never panics
    #[test]
    fn telegram_extract_never_panics(value in arb_telegram_text_value()) {
        let _ = extract_telegram_text(&value);
    }

    /// extract_telegram_text returns valid UTF-8
    #[test]
    fn telegram_extract_valid_utf8(value in arb_telegram_text_value()) {
        let result = extract_telegram_text(&value);
        // Result is String, so it's always valid UTF-8
        prop_assert!(result.len() <= result.len()); // trivial, ensures no panic
    }

    /// Simple string extraction preserves content
    #[test]
    fn telegram_extract_string_identity(s in "[a-zA-Z0-9 ]{0,50}") {
        let value = json!(s);
        let result = extract_telegram_text(&value);
        prop_assert_eq!(result, s);
    }

    /// Array extraction concatenates all strings
    #[test]
    fn telegram_extract_array_concat(parts in prop::collection::vec("[a-zA-Z]{1,10}", 1..5)) {
        let value = Value::Array(parts.iter().map(|s| json!(s)).collect());
        let result = extract_telegram_text(&value);
        let expected: String = parts.concat();
        prop_assert_eq!(result, expected);
    }

    /// parse_unix_timestamp never panics
    #[test]
    fn telegram_parse_ts_never_panics(ts_str in arb_unix_timestamp_str()) {
        let _ = parse_unix_timestamp(&ts_str);
    }

    /// Valid timestamps parse successfully
    #[test]
    fn telegram_valid_ts_parses(ts in 1000000000i64..2000000000i64) {
        let ts_str = ts.to_string();
        let result = parse_unix_timestamp(&ts_str);
        prop_assert!(result.is_some());
        prop_assert_eq!(result.unwrap().timestamp(), ts);
    }

    /// parse_telegram_message never panics
    #[test]
    fn telegram_parse_message_never_panics(
        msg_type in prop::sample::select(vec!["message", "service", "other"]),
        sender in prop::option::of(prop::sample::select(vec!["Alice", "Bob"])),
        text_value in arb_telegram_text_value(),
        ts in prop::option::of(1700000000i64..1800000000i64)
    ) {
        let msg = TelegramRawMessage {
            id: Some(123),
            msg_type: msg_type.to_string(),
            date_unixtime: ts.map(|t| t.to_string()),
            from: sender.map(|s| s.to_string()),
            text: Some(text_value),
            reply_to_message_id: None,
            edited_unixtime: None,
        };
        let _ = parse_telegram_message(&msg);
    }

    /// Non-message types are skipped
    #[test]
    fn telegram_skip_service_messages(
        msg_type in prop::sample::select(vec!["service", "action", "unknown"])
    ) {
        let msg = TelegramRawMessage {
            id: Some(123),
            msg_type: msg_type.to_string(),
            date_unixtime: Some("1700000000".to_string()),
            from: Some("Alice".to_string()),
            text: Some(json!("Hello")),
            reply_to_message_id: None,
            edited_unixtime: None,
        };
        let result = parse_telegram_message(&msg);
        prop_assert!(result.is_none());
    }
}

// =============================================================================
// WHATSAPP PARSING PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(200))]

    /// detect_whatsapp_format never panics
    #[test]
    fn whatsapp_detect_never_panics(lines in prop::collection::vec(arb_whatsapp_line(), 0..20)) {
        let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
        let _ = detect_whatsapp_format(&refs);
    }

    /// Empty input returns None
    #[test]
    fn whatsapp_detect_empty_is_none(_dummy in Just(())) {
        let result = detect_whatsapp_format(&[]);
        prop_assert!(result.is_none());
    }

    /// Detection is deterministic
    #[test]
    fn whatsapp_detect_deterministic(lines in prop::collection::vec(arb_whatsapp_line(), 1..10)) {
        let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
        let result1 = detect_whatsapp_format(&refs);
        let result2 = detect_whatsapp_format(&refs);
        prop_assert_eq!(result1, result2);
    }

    /// US format lines detected correctly
    #[test]
    fn whatsapp_detect_us_format(_dummy in Just(())) {
        let lines = vec![
            "[1/15/24, 10:30:45 AM] Alice: Hello",
            "[12/31/23, 11:59:59 PM] Bob: Bye",
        ];
        let result = detect_whatsapp_format(&lines);
        prop_assert_eq!(result, Some(DateFormat::US));
    }

    /// is_whatsapp_system_message never panics
    #[test]
    fn whatsapp_system_check_never_panics(
        sender in arb_sender(),
        content in arb_content_for_system_check()
    ) {
        let _ = is_whatsapp_system_message(&sender, &content);
    }

    /// Empty/whitespace sender is system
    #[test]
    fn whatsapp_empty_sender_is_system(content in arb_content_for_system_check()) {
        prop_assert!(is_whatsapp_system_message("", &content));
        prop_assert!(is_whatsapp_system_message("   ", &content));
    }

    /// WhatsApp/System sender is system
    #[test]
    fn whatsapp_system_sender_is_system(content in prop::sample::select(vec!["Hello", "Test"])) {
        prop_assert!(is_whatsapp_system_message("WhatsApp", content));
        prop_assert!(is_whatsapp_system_message("whatsapp", content));
        prop_assert!(is_whatsapp_system_message("System", content));
        prop_assert!(is_whatsapp_system_message("SYSTEM", content));
    }

    /// parse_whatsapp_timestamp never panics
    #[test]
    fn whatsapp_parse_ts_never_panics(
        date in prop::sample::select(vec!["1/15/24", "15.01.24", "15/01/2024", "invalid"]),
        time in prop::sample::select(vec!["10:30:45 AM", "23:59:59", "10:30", "invalid"]),
        format in prop::sample::select(vec![
            DateFormat::US,
            DateFormat::EuDotBracketed,
            DateFormat::EuSlash,
        ])
    ) {
        let _ = parse_whatsapp_timestamp(date, time, format);
    }

    /// Valid US format parses
    #[test]
    fn whatsapp_valid_us_ts_parses(
        month in 1u32..=12,
        day in 1u32..=28,
        hour in 1u32..=12
    ) {
        let date = format!("{}/{}/24", month, day);
        let time = format!("{}:30:00 AM", hour);
        let result = parse_whatsapp_timestamp(&date, &time, DateFormat::US);
        prop_assert!(result.is_some());
    }
}

// =============================================================================
// INSTAGRAM PARSING PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(200))]

    /// fix_mojibake_encoding never panics
    #[test]
    fn instagram_mojibake_never_panics(input in arb_mojibake_input()) {
        let _ = fix_mojibake_encoding(&input);
    }

    /// ASCII passes through unchanged
    #[test]
    fn instagram_ascii_passthrough(s in "[a-zA-Z0-9 !?.,]{0,100}") {
        let result = fix_mojibake_encoding(&s);
        prop_assert_eq!(result, s);
    }

    /// Empty string returns empty
    #[test]
    fn instagram_empty_passthrough(_dummy in Just(())) {
        let result = fix_mojibake_encoding("");
        prop_assert_eq!(result, "");
    }

    /// Output is always valid UTF-8 (String guarantees this)
    #[test]
    fn instagram_output_valid_utf8(input in arb_mojibake_input()) {
        let result = fix_mojibake_encoding(&input);
        // String is always valid UTF-8, this just ensures no panic
        // We check that the result is non-negative length (always true for String)
        let _ = result.len();
    }

    /// parse_instagram_message never panics
    #[test]
    fn instagram_parse_never_panics(msg in arb_instagram_raw_message()) {
        let _ = parse_instagram_message(&msg, false);
        let _ = parse_instagram_message(&msg, true);
    }

    /// parse_instagram_message_owned never panics
    #[test]
    fn instagram_parse_owned_never_panics(msg in arb_instagram_raw_message()) {
        let _ = parse_instagram_message_owned(msg, false);
    }

    /// Messages without content return None
    #[test]
    fn instagram_no_content_is_none(sender in prop::sample::select(vec!["user", "test"])) {
        let msg = InstagramRawMessage {
            sender_name: sender.to_string(),
            timestamp_ms: 1700000000000,
            content: None,
            share: None,
            photos: None,
            videos: None,
            audio_files: None,
        };
        let result = parse_instagram_message(&msg, false);
        prop_assert!(result.is_none());
    }

    /// Share content is used when no direct content
    #[test]
    fn instagram_share_fallback(sender in prop::sample::select(vec!["user", "test"])) {
        let msg = InstagramRawMessage {
            sender_name: sender.to_string(),
            timestamp_ms: 1700000000000,
            content: None,
            share: Some(InstagramShare {
                share_text: Some("Shared!".to_string()),
                link: None,
            }),
            photos: None,
            videos: None,
            audio_files: None,
        };
        let result = parse_instagram_message(&msg, false);
        prop_assert!(result.is_some());
        prop_assert_eq!(result.unwrap().content, "Shared!");
    }
}

// =============================================================================
// DISCORD PARSING PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(200))]

    /// parse_discord_message never panics
    #[test]
    fn discord_parse_never_panics(msg in arb_discord_raw_message()) {
        let _ = parse_discord_message(&msg);
    }

    /// Empty content without attachments returns None
    #[test]
    fn discord_empty_is_none(
        id in prop::sample::select(vec!["123", "456"]),
        name in prop::sample::select(vec!["alice", "bob"])
    ) {
        let msg = DiscordRawMessage {
            id: id.to_string(),
            timestamp: "2024-01-15T10:30:00+00:00".to_string(),
            timestamp_edited: None,
            content: String::new(),
            author: DiscordAuthor {
                name: name.to_string(),
                nickname: None,
            },
            reference: None,
            attachments: None,
            stickers: None,
        };
        let result = parse_discord_message(&msg);
        prop_assert!(result.is_none());
    }

    /// Nickname takes priority over name
    #[test]
    fn discord_nickname_priority(
        name in prop::sample::select(vec!["user123", "user456"]),
        nickname in prop::sample::select(vec!["Display Name", "Nick"])
    ) {
        let msg = DiscordRawMessage {
            id: "123".to_string(),
            timestamp: "2024-01-15T10:30:00+00:00".to_string(),
            timestamp_edited: None,
            content: "Test".to_string(),
            author: DiscordAuthor {
                name: name.to_string(),
                nickname: Some(nickname.to_string()),
            },
            reference: None,
            attachments: None,
            stickers: None,
        };
        let result = parse_discord_message(&msg);
        prop_assert!(result.is_some());
        prop_assert_eq!(result.unwrap().sender, nickname);
    }

    /// Attachments are appended to content
    #[test]
    fn discord_attachments_appended(filename in prop::sample::select(vec!["test.png", "file.pdf"])) {
        let msg = DiscordRawMessage {
            id: "123".to_string(),
            timestamp: "2024-01-15T10:30:00+00:00".to_string(),
            timestamp_edited: None,
            content: "Check this".to_string(),
            author: DiscordAuthor {
                name: "alice".to_string(),
                nickname: None,
            },
            reference: None,
            attachments: Some(vec![DiscordAttachment {
                file_name: filename.to_string(),
            }]),
            stickers: None,
        };
        let result = parse_discord_message(&msg);
        prop_assert!(result.is_some());
        let content = result.unwrap().content;
        let expected = format!("[Attachment: {}]", filename);
        prop_assert!(content.contains(&expected), "Missing attachment marker in content");
    }

    /// Stickers are appended to content
    #[test]
    fn discord_stickers_appended(sticker_name in prop::sample::select(vec!["Cool", "Nice"])) {
        let msg = DiscordRawMessage {
            id: "123".to_string(),
            timestamp: "2024-01-15T10:30:00+00:00".to_string(),
            timestamp_edited: None,
            content: "Look".to_string(),
            author: DiscordAuthor {
                name: "bob".to_string(),
                nickname: None,
            },
            reference: None,
            attachments: None,
            stickers: Some(vec![DiscordSticker {
                name: sticker_name.to_string(),
            }]),
        };
        let result = parse_discord_message(&msg);
        prop_assert!(result.is_some());
        let content = result.unwrap().content;
        let expected = format!("[Sticker: {}]", sticker_name);
        prop_assert!(content.contains(&expected), "Missing sticker marker in content");
    }

    /// Attachment-only message is kept
    #[test]
    fn discord_attachment_only_kept(filename in prop::sample::select(vec!["a.jpg", "b.mp4"])) {
        let msg = DiscordRawMessage {
            id: "123".to_string(),
            timestamp: "2024-01-15T10:30:00+00:00".to_string(),
            timestamp_edited: None,
            content: String::new(),
            author: DiscordAuthor {
                name: "user".to_string(),
                nickname: None,
            },
            reference: None,
            attachments: Some(vec![DiscordAttachment {
                file_name: filename.to_string(),
            }]),
            stickers: None,
        };
        let result = parse_discord_message(&msg);
        prop_assert!(result.is_some());
    }
}

// =============================================================================
// OUTPUT FORMAT PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(100))]

    /// to_csv never panics
    #[test]
    fn csv_output_never_panics(messages in arb_messages(20)) {
        let config = OutputConfig::default();
        let _ = to_csv(&messages, &config);
    }

    /// CSV output contains header
    #[test]
    fn csv_has_header(messages in arb_messages(10)) {
        let config = OutputConfig::default();
        if let Ok(csv) = to_csv(&messages, &config) {
            prop_assert!(csv.contains("Sender") && csv.contains("Content"));
        }
    }

    /// to_json never panics
    #[test]
    fn json_output_never_panics(messages in arb_messages(20)) {
        let config = OutputConfig::default();
        let _ = to_json(&messages, &config);
    }

    /// JSON output is valid JSON
    #[test]
    fn json_output_valid(messages in arb_messages(10)) {
        let config = OutputConfig::default();
        if let Ok(json_str) = to_json(&messages, &config) {
            let parsed: Result<Value, _> = serde_json::from_str(&json_str);
            prop_assert!(parsed.is_ok(), "Invalid JSON: {}", json_str);
        }
    }

    /// to_jsonl never panics
    #[test]
    fn jsonl_output_never_panics(messages in arb_messages(20)) {
        let config = OutputConfig::default();
        let _ = to_jsonl(&messages, &config);
    }

    /// JSONL output has one valid JSON per line
    #[test]
    fn jsonl_valid_per_line(messages in arb_messages(5)) {
        let config = OutputConfig::default();
        if let Ok(jsonl) = to_jsonl(&messages, &config) {
            for line in jsonl.lines() {
                if !line.is_empty() {
                    let parsed: Result<Value, _> = serde_json::from_str(line);
                    prop_assert!(parsed.is_ok(), "Invalid JSONL line: {}", line);
                }
            }
        }
    }

    /// CSV handles special characters without panic
    #[test]
    fn csv_special_chars_safe(content in prop::sample::select(vec![
        "Normal".to_string(),
        "With;semicolon".to_string(),
        "With\"quote".to_string(),
        "With\nnewline".to_string(),
        "All;\"chars\nhere".to_string(),
        "Tab\there".to_string(),
    ])) {
        let msg = Message::new("User", content);
        let config = OutputConfig::default();
        let result = to_csv(&[msg], &config);
        prop_assert!(result.is_ok());
    }
}

// =============================================================================
// DATE PARSING PROPERTIES
// =============================================================================

proptest! {
    #![proptest_config(ProptestConfig::with_cases(100))]

    /// FilterConfig::after_date never panics
    #[test]
    fn filter_after_date_never_panics(date_str in arb_date_string()) {
        let _ = FilterConfig::new().after_date(&date_str);
    }

    /// FilterConfig::before_date never panics
    #[test]
    fn filter_before_date_never_panics(date_str in arb_date_string()) {
        let _ = FilterConfig::new().before_date(&date_str);
    }

    /// Valid YYYY-MM-DD parses successfully
    #[test]
    fn filter_valid_date_parses(
        year in 2000i32..2100,
        month in 1u32..=12,
        day in 1u32..=28
    ) {
        let date_str = format!("{:04}-{:02}-{:02}", year, month, day);
        let result = FilterConfig::new().after_date(&date_str);
        prop_assert!(result.is_ok(), "Failed to parse: {}", date_str);
    }

    /// Invalid format returns error
    #[test]
    fn filter_invalid_format_errors(
        format in prop::sample::select(vec![
            "01-15-2024",
            "15/01/2024",
            "2024/01/15",
            "not-a-date",
            "",
        ])
    ) {
let result = FilterConfig::new().after_date(format);
        prop_assert!(result.is_err());
    }

    /// Leap year dates handled correctly
    #[test]
    fn filter_leap_year_handled(_dummy in Just(())) {
        // 2024 is a leap year
        let valid = FilterConfig::new().after_date("2024-02-29");
        prop_assert!(valid.is_ok());

        // 2023 is not a leap year
        let invalid = FilterConfig::new().after_date("2023-02-29");
        prop_assert!(invalid.is_err());
    }
}

// =============================================================================
// EDGE CASE TESTS (NON-PROPTEST)
// =============================================================================

#[cfg(test)]
mod edge_cases {
    use super::*;

    #[test]
    fn merge_consecutive_same_sender() {
        let messages = vec![
            Message::new("Alice", "Hello"),
            Message::new("Alice", "World"),
        ];
        let merged = merge_consecutive(messages);
        assert_eq!(merged.len(), 1);
        assert!(merged[0].content.contains("Hello"));
        assert!(merged[0].content.contains("World"));
    }

    #[test]
    fn merge_alternating_senders() {
        let messages = vec![
            Message::new("Alice", "Hi"),
            Message::new("Bob", "Hey"),
            Message::new("Alice", "Bye"),
        ];
        let merged = merge_consecutive(messages);
        assert_eq!(merged.len(), 3);
    }

    #[test]
    fn filter_empty_messages() {
        let messages: Vec<Message> = vec![];
        let config = FilterConfig::new().with_user("Anyone".into());
        let filtered = apply_filters(messages, &config);
        assert!(filtered.is_empty());
    }

    #[test]
    fn merge_with_empty_content() {
        let messages = vec![
            Message::new("Alice", ""),
            Message::new("Alice", "Real message"),
        ];
        let merged = merge_consecutive(messages);
        assert_eq!(merged.len(), 1);
    }

    #[test]
    fn telegram_extract_null_value() {
        let value = json!(null);
        let result = extract_telegram_text(&value);
        assert_eq!(result, "");
    }

    #[test]
    fn telegram_extract_number_value() {
        let value = json!(12345);
        let result = extract_telegram_text(&value);
        assert_eq!(result, "");
    }

    #[test]
    fn telegram_extract_nested_array() {
        let value = json!([
            "Start ",
            {"type": "link", "text": "http://example.com"},
            " middle ",
            {"type": "bold", "text": "bold text"},
            " end"
        ]);
        let result = extract_telegram_text(&value);
        assert_eq!(result, "Start http://example.com middle bold text end");
    }

    #[test]
    fn whatsapp_all_formats_detected() {
        // US - month/day/year with AM/PM (the AM/PM is key to identifying US format)
        let us_lines = vec!["[1/15/24, 10:30:45 AM] Alice: Hello"];
        assert_eq!(detect_whatsapp_format(&us_lines), Some(DateFormat::US));

        // EU Dot Bracketed - day.month.year with dots (unique separator)
        let eu_dot = vec!["[25.01.24, 10:30:45] Alice: Hello"];
        assert_eq!(
            detect_whatsapp_format(&eu_dot),
            Some(DateFormat::EuDotBracketed)
        );

        // EU Dot No Bracket - day.month.year with " - " separator (unique format)
        let eu_dot_no = vec!["25.01.2024, 10:30 - Alice: Hello"];
        assert_eq!(
            detect_whatsapp_format(&eu_dot_no),
            Some(DateFormat::EuDotNoBracket)
        );

        // EU Slash - day/month/year with " - " separator (no brackets is key)
        let eu_slash = vec!["25/01/2024, 10:30 - Alice: Hello"];
        assert_eq!(detect_whatsapp_format(&eu_slash), Some(DateFormat::EuSlash));

        // Note: EU Slash Bracketed overlaps with US format regex, so we skip
        // testing it with a single line. In practice, detection uses voting
        // across multiple lines.
    }

    #[test]
    fn instagram_mojibake_ascii_only() {
        assert_eq!(
            fix_mojibake_encoding("Hello World 123!"),
            "Hello World 123!"
        );
    }

    #[test]
    fn discord_multiple_attachments() {
        let msg = DiscordRawMessage {
            id: "123".to_string(),
            timestamp: "2024-01-15T10:30:00+00:00".to_string(),
            timestamp_edited: None,
            content: "Files:".to_string(),
            author: DiscordAuthor {
                name: "user".to_string(),
                nickname: None,
            },
            reference: None,
            attachments: Some(vec![
                DiscordAttachment {
                    file_name: "a.png".to_string(),
                },
                DiscordAttachment {
                    file_name: "b.jpg".to_string(),
                },
            ]),
            stickers: None,
        };
        let result = parse_discord_message(&msg).unwrap();
        assert!(result.content.contains("[Attachment: a.png]"));
        assert!(result.content.contains("[Attachment: b.jpg]"));
    }

    #[test]
    fn csv_output_with_all_options() {
        let msg = Message {
            sender: "Alice".to_string(),
            content: "Hello".to_string(),
            timestamp: chrono::DateTime::from_timestamp(1700000000, 0),
            id: Some(123),
            reply_to: Some(100),
            edited: chrono::DateTime::from_timestamp(1700000100, 0),
        };

        let config = OutputConfig {
            include_timestamps: true,
            include_ids: true,
            include_replies: true,
            include_edited: true,
        };

        let csv = to_csv(&[msg], &config).unwrap();
        assert!(csv.contains("ID"));
        assert!(csv.contains("Timestamp"));
        assert!(csv.contains("Sender"));
        assert!(csv.contains("Content"));
        assert!(csv.contains("ReplyTo"));
        assert!(csv.contains("Edited"));
    }

    #[test]
    fn very_long_message() {
        let long_content = "x".repeat(100_000);
        let msg = Message::new("User", &long_content);
        let merged = merge_consecutive(vec![msg.clone()]);
        assert_eq!(merged[0].content.len(), 100_000);

        // Also test serialization
        let json = serde_json::to_string(&msg).unwrap();
        let parsed: Message = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.content.len(), 100_000);
    }

    #[test]
    fn unicode_normalization_edge_cases() {
        // Combining characters
        let combining = "e\u{0301}"; // รฉ as e + combining acute
        let msg = Message::new("User", combining);
        let merged = merge_consecutive(vec![msg]);
        assert_eq!(merged[0].content, combining);

        // ZWJ sequences (family emoji)
        let family = "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ";
        let msg2 = Message::new("User", family);
        let merged2 = merge_consecutive(vec![msg2]);
        assert_eq!(merged2[0].content, family);
    }

    #[test]
    fn filter_date_boundaries() {
        use chrono::TimeZone;

        let messages = vec![
            Message {
                sender: "Alice".to_string(),
                content: "At start".to_string(),
                timestamp: Some(chrono::Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap()),
                id: None,
                reply_to: None,
                edited: None,
            },
            Message {
                sender: "Alice".to_string(),
                content: "At end".to_string(),
                timestamp: Some(
                    chrono::Utc
                        .with_ymd_and_hms(2024, 1, 1, 23, 59, 59)
                        .unwrap(),
                ),
                id: None,
                reply_to: None,
                edited: None,
            },
        ];

        // Filter for exactly 2024-01-01 should include both
        let config = FilterConfig::new()
            .after_date("2024-01-01")
            .unwrap()
            .before_date("2024-01-01")
            .unwrap();

        let filtered = apply_filters(messages, &config);
        assert_eq!(filtered.len(), 2);
    }
}