micropdf 0.17.0

A pure Rust PDF library - A pure Rust PDF library with fz_/pdf_ API compatibility
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
//! CBZ/CBR (Comic Book Archives) FFI Module
//!
//! Provides support for comic book archive formats, including ZIP-based CBZ
//! and RAR-based CBR, with image sequence handling and ComicInfo.xml metadata.

use crate::ffi::document::Document;
use crate::ffi::{DOCUMENTS, Handle, HandleStore, STREAMS};
use crate::fitz::archive::Archive;
use std::collections::HashMap;
use std::ffi::{CStr, CString, c_char};
use std::ptr;
use std::sync::LazyLock;

// ============================================================================
// Type Aliases
// ============================================================================

type ContextHandle = Handle;
type StreamHandle = Handle;
type ArchiveHandle = Handle;

// ============================================================================
// CBZ Format Constants
// ============================================================================

/// CBZ (ZIP-based) format
pub const CBZ_FORMAT_CBZ: i32 = 0;
/// CBR (RAR-based) format
pub const CBZ_FORMAT_CBR: i32 = 1;
/// CB7 (7z-based) format
pub const CBZ_FORMAT_CB7: i32 = 2;
/// CBT (TAR-based) format
pub const CBZ_FORMAT_CBT: i32 = 3;

// ============================================================================
// Image Format Constants
// ============================================================================

/// JPEG image
pub const CBZ_IMAGE_JPEG: i32 = 0;
/// PNG image
pub const CBZ_IMAGE_PNG: i32 = 1;
/// GIF image
pub const CBZ_IMAGE_GIF: i32 = 2;
/// BMP image
pub const CBZ_IMAGE_BMP: i32 = 3;
/// TIFF image
pub const CBZ_IMAGE_TIFF: i32 = 4;
/// WebP image
pub const CBZ_IMAGE_WEBP: i32 = 5;
/// JPEG 2000 image
pub const CBZ_IMAGE_JP2: i32 = 6;
/// Unknown image format
pub const CBZ_IMAGE_UNKNOWN: i32 = 99;

// ============================================================================
// Reading Direction Constants
// ============================================================================

/// Left-to-right reading (Western comics)
pub const CBZ_READ_LTR: i32 = 0;
/// Right-to-left reading (Manga)
pub const CBZ_READ_RTL: i32 = 1;

// ============================================================================
// Manga Constants (Yes/No/Unknown)
// ============================================================================

/// Unknown manga status
pub const CBZ_MANGA_UNKNOWN: i32 = 0;
/// Is manga (right-to-left)
pub const CBZ_MANGA_YES: i32 = 1;
/// Not manga (left-to-right)
pub const CBZ_MANGA_NO: i32 = 2;
/// Manga with right-to-left and left-to-right mixed
pub const CBZ_MANGA_YES_RTL: i32 = 3;

// ============================================================================
// Supported Image Extensions
// ============================================================================

const SUPPORTED_EXTENSIONS: &[&str] = &[
    ".bmp", ".gif", ".hdp", ".j2k", ".jb2", ".jbig2", ".jp2", ".jpeg", ".jpg", ".jpx", ".jxr",
    ".pam", ".pbm", ".pgm", ".pkm", ".png", ".pnm", ".ppm", ".tif", ".tiff", ".wdp", ".webp",
];

// ============================================================================
// ComicInfo Metadata
// ============================================================================

/// ComicInfo.xml metadata structure
#[derive(Debug, Clone, Default)]
pub struct ComicInfo {
    /// Title of the comic
    pub title: Option<String>,
    /// Series name
    pub series: Option<String>,
    /// Issue number
    pub number: Option<String>,
    /// Volume number
    pub volume: Option<i32>,
    /// Alternate series
    pub alternate_series: Option<String>,
    /// Alternate number
    pub alternate_number: Option<String>,
    /// Story arc
    pub story_arc: Option<String>,
    /// Series group
    pub series_group: Option<String>,
    /// Summary/description
    pub summary: Option<String>,
    /// Notes
    pub notes: Option<String>,
    /// Year of publication
    pub year: Option<i32>,
    /// Month of publication
    pub month: Option<i32>,
    /// Day of publication
    pub day: Option<i32>,
    /// Writer(s)
    pub writer: Option<String>,
    /// Penciller(s)
    pub penciller: Option<String>,
    /// Inker(s)
    pub inker: Option<String>,
    /// Colorist(s)
    pub colorist: Option<String>,
    /// Letterer(s)
    pub letterer: Option<String>,
    /// Cover artist(s)
    pub cover_artist: Option<String>,
    /// Editor(s)
    pub editor: Option<String>,
    /// Publisher
    pub publisher: Option<String>,
    /// Imprint
    pub imprint: Option<String>,
    /// Genre(s)
    pub genre: Option<String>,
    /// Tags
    pub tags: Option<String>,
    /// Web link
    pub web: Option<String>,
    /// Page count
    pub page_count: Option<i32>,
    /// Language (ISO code)
    pub language_iso: Option<String>,
    /// Format (e.g., "Trade Paperback")
    pub format: Option<String>,
    /// Black and white (true/false)
    pub black_and_white: bool,
    /// Manga reading direction
    pub manga: i32,
    /// Characters
    pub characters: Option<String>,
    /// Teams
    pub teams: Option<String>,
    /// Locations
    pub locations: Option<String>,
    /// Age rating
    pub age_rating: Option<String>,
    /// Community rating (0-5)
    pub community_rating: Option<f32>,
    /// Scan information
    pub scan_information: Option<String>,
}

impl ComicInfo {
    pub fn new() -> Self {
        Self {
            manga: CBZ_MANGA_UNKNOWN,
            ..Default::default()
        }
    }
}

// ============================================================================
// CBZ Page
// ============================================================================

/// A page in the comic book
#[derive(Debug, Clone)]
pub struct CbzPage {
    /// Page index (0-based)
    pub index: i32,
    /// File name within archive
    pub filename: String,
    /// Image format
    pub format: i32,
    /// Image width (pixels)
    pub width: i32,
    /// Image height (pixels)
    pub height: i32,
    /// Image data (raw bytes)
    pub data: Vec<u8>,
    /// Page type (e.g., "FrontCover", "Story")
    pub page_type: Option<String>,
    /// Is double page spread
    pub double_page: bool,
    /// Bookmark name
    pub bookmark: Option<String>,
}

impl CbzPage {
    pub fn new(index: i32, filename: &str) -> Self {
        Self {
            index,
            filename: filename.to_string(),
            format: CBZ_IMAGE_UNKNOWN,
            width: 0,
            height: 0,
            data: Vec::new(),
            page_type: None,
            double_page: false,
            bookmark: None,
        }
    }

    pub fn detect_format(&mut self) {
        let lower = self.filename.to_lowercase();
        self.format = if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
            CBZ_IMAGE_JPEG
        } else if lower.ends_with(".png") {
            CBZ_IMAGE_PNG
        } else if lower.ends_with(".gif") {
            CBZ_IMAGE_GIF
        } else if lower.ends_with(".bmp") {
            CBZ_IMAGE_BMP
        } else if lower.ends_with(".tif") || lower.ends_with(".tiff") {
            CBZ_IMAGE_TIFF
        } else if lower.ends_with(".webp") {
            CBZ_IMAGE_WEBP
        } else if lower.ends_with(".jp2") || lower.ends_with(".j2k") || lower.ends_with(".jpx") {
            CBZ_IMAGE_JP2
        } else {
            CBZ_IMAGE_UNKNOWN
        };
    }
}

// ============================================================================
// CBZ Document
// ============================================================================

/// CBZ/CBR document structure
pub struct CbzDocument {
    /// Context handle
    pub context: ContextHandle,
    /// Archive format
    pub format: i32,
    /// Metadata
    pub info: ComicInfo,
    /// Pages (sorted by natural order)
    pub pages: Vec<CbzPage>,
    /// File entries in archive
    pub entries: Vec<String>,
    /// Raw archive data
    pub archive_data: Vec<u8>,
}

impl CbzDocument {
    pub fn new(context: ContextHandle) -> Self {
        Self {
            context,
            format: CBZ_FORMAT_CBZ,
            info: ComicInfo::new(),
            pages: Vec::new(),
            entries: Vec::new(),
            archive_data: Vec::new(),
        }
    }

    pub fn page_count(&self) -> i32 {
        self.pages.len() as i32
    }

    pub fn get_page(&self, index: i32) -> Option<&CbzPage> {
        self.pages.get(index as usize)
    }

    pub fn add_page(&mut self, page: CbzPage) {
        self.pages.push(page);
    }

    pub fn sort_pages(&mut self) {
        // Natural sort order (like MicroPDF's cbz_strnatcmp)
        self.pages
            .sort_by(|a, b| natural_cmp(&a.filename, &b.filename));
    }

    pub fn is_image_file(name: &str) -> bool {
        let lower = name.to_lowercase();
        SUPPORTED_EXTENSIONS.iter().any(|ext| lower.ends_with(ext))
    }

    pub fn add_entry(&mut self, name: &str) {
        if Self::is_image_file(name) {
            let index = self.pages.len() as i32;
            let mut page = CbzPage::new(index, name);
            page.detect_format();
            self.pages.push(page);
        }
        self.entries.push(name.to_string());
    }
}

// ============================================================================
// Natural Sort Comparison
// ============================================================================

fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
    let mut a_chars = a.chars().peekable();
    let mut b_chars = b.chars().peekable();

    loop {
        match (a_chars.peek(), b_chars.peek()) {
            (None, None) => return std::cmp::Ordering::Equal,
            (None, Some(_)) => return std::cmp::Ordering::Less,
            (Some(_), None) => return std::cmp::Ordering::Greater,
            (Some(&ac), Some(&bc)) => {
                if ac.is_ascii_digit() && bc.is_ascii_digit() {
                    // Parse numbers
                    let mut a_num = 0u64;
                    while let Some(&c) = a_chars.peek() {
                        if c.is_ascii_digit() {
                            a_num = a_num * 10 + c.to_digit(10).unwrap() as u64;
                            a_chars.next();
                        } else {
                            break;
                        }
                    }

                    let mut b_num = 0u64;
                    while let Some(&c) = b_chars.peek() {
                        if c.is_ascii_digit() {
                            b_num = b_num * 10 + c.to_digit(10).unwrap() as u64;
                            b_chars.next();
                        } else {
                            break;
                        }
                    }

                    match a_num.cmp(&b_num) {
                        std::cmp::Ordering::Equal => continue,
                        other => return other,
                    }
                } else {
                    // Compare characters (case-insensitive)
                    let a_upper = ac.to_ascii_uppercase();
                    let b_upper = bc.to_ascii_uppercase();

                    match a_upper.cmp(&b_upper) {
                        std::cmp::Ordering::Equal => {
                            a_chars.next();
                            b_chars.next();
                            continue;
                        }
                        other => return other,
                    }
                }
            }
        }
    }
}

// ============================================================================
// Global Handle Store
// ============================================================================

pub static CBZ_DOCUMENTS: LazyLock<HandleStore<CbzDocument>> = LazyLock::new(HandleStore::new);

// ============================================================================
// FFI Functions - Document Management
// ============================================================================

/// Create a new CBZ document.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_new_document(ctx: ContextHandle) -> Handle {
    let doc = CbzDocument::new(ctx);
    CBZ_DOCUMENTS.insert(doc)
}

/// Drop a CBZ document.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_drop_document(_ctx: ContextHandle, doc: Handle) {
    CBZ_DOCUMENTS.remove(doc);
}

/// Count image entries in ZIP data for page count.
fn count_cbz_image_entries(data: &[u8]) -> i32 {
    const IMAGE_EXTENSIONS: &[&str] = &[
        ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff",
    ];
    if let Ok(archive) = Archive::from_buffer(data.to_vec()) {
        let names = archive.entry_names();
        let count = names
            .iter()
            .filter(|name| {
                let lower = name.to_lowercase();
                IMAGE_EXTENSIONS.iter().any(|ext| lower.ends_with(ext))
            })
            .count();
        return count.max(1) as i32;
    }
    1
}

/// Open a CBZ document from a file path.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_open_document(_ctx: ContextHandle, filename: *const c_char) -> Handle {
    if filename.is_null() {
        return 0;
    }

    let c_str = unsafe { CStr::from_ptr(filename) };
    let path = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return 0,
    };

    match std::fs::read(path) {
        Ok(data) => {
            if data.is_empty() {
                return 0;
            }
            // Validate ZIP magic (PK)
            if data.len() < 2 || data[0] != 0x50 || data[1] != 0x4B {
                return 0;
            }
            let page_count = count_cbz_image_entries(&data);
            let mut doc = Document::new(data);
            doc.format = "cbz".to_string();
            doc.page_count = page_count;
            DOCUMENTS.insert(doc)
        }
        Err(_) => 0,
    }
}

/// Open a CBZ document from a stream.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_open_document_with_stream(
    _ctx: ContextHandle,
    stream: StreamHandle,
) -> Handle {
    if let Some(stream_arc) = STREAMS.get(stream) {
        if let Ok(guard) = stream_arc.lock() {
            let data = guard.data.clone();
            if data.is_empty() {
                return 0;
            }
            if data.len() < 2 || data[0] != 0x50 || data[1] != 0x4B {
                return 0;
            }
            let page_count = count_cbz_image_entries(&data);
            let mut doc = Document::new(data);
            doc.format = "cbz".to_string();
            doc.page_count = page_count;
            return DOCUMENTS.insert(doc);
        }
    }
    0
}

/// Open a CBZ document from an archive.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_open_document_with_archive(
    _ctx: ContextHandle,
    archive: ArchiveHandle,
) -> Handle {
    if let Some(archive_arc) = super::archive::ARCHIVES.get(archive) {
        if let Ok(guard) = archive_arc.lock() {
            if let Some(data) = guard.raw_data() {
                if !data.is_empty() && data.len() >= 2 && data[0] == 0x50 && data[1] == 0x4B {
                    let page_count = count_cbz_image_entries(&data);
                    let mut doc = Document::new(data);
                    doc.format = "cbz".to_string();
                    doc.page_count = page_count;
                    return DOCUMENTS.insert(doc);
                }
            }
        }
    }
    0
}

// ============================================================================
// FFI Functions - Document Properties
// ============================================================================

/// Get document format.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_format(_ctx: ContextHandle, doc: Handle) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        return d.format;
    }
    CBZ_FORMAT_CBZ
}

/// Get page count.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_page_count(_ctx: ContextHandle, doc: Handle) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        return d.page_count();
    }
    0
}

/// Add an entry to the document.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_add_entry(_ctx: ContextHandle, doc: Handle, name: *const c_char) -> i32 {
    if name.is_null() {
        return 0;
    }

    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        let entry_name = unsafe { CStr::from_ptr(name).to_string_lossy().to_string() };
        d.add_entry(&entry_name);
        return 1;
    }
    0
}

/// Sort pages by natural order.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_sort_pages(_ctx: ContextHandle, doc: Handle) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        d.sort_pages();
        return 1;
    }
    0
}

// ============================================================================
// FFI Functions - Page Access
// ============================================================================

/// Get page filename.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_page_filename(
    _ctx: ContextHandle,
    doc: Handle,
    page_num: i32,
) -> *mut c_char {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(page) = d.get_page(page_num) {
            if let Ok(cstr) = CString::new(page.filename.clone()) {
                return cstr.into_raw();
            }
        }
    }
    ptr::null_mut()
}

/// Get page image format.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_page_format(_ctx: ContextHandle, doc: Handle, page_num: i32) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(page) = d.get_page(page_num) {
            return page.format;
        }
    }
    CBZ_IMAGE_UNKNOWN
}

/// Get page dimensions.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_page_size(
    _ctx: ContextHandle,
    doc: Handle,
    page_num: i32,
    width: *mut i32,
    height: *mut i32,
) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(page) = d.get_page(page_num) {
            if !width.is_null() {
                unsafe {
                    *width = page.width;
                }
            }
            if !height.is_null() {
                unsafe {
                    *height = page.height;
                }
            }
            return 1;
        }
    }
    0
}

/// Set page dimensions.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_page_size(
    _ctx: ContextHandle,
    doc: Handle,
    page_num: i32,
    width: i32,
    height: i32,
) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        if let Some(page) = d.pages.get_mut(page_num as usize) {
            page.width = width;
            page.height = height;
            return 1;
        }
    }
    0
}

/// Check if page is double-page spread.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_page_is_double(_ctx: ContextHandle, doc: Handle, page_num: i32) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(page) = d.get_page(page_num) {
            return if page.double_page { 1 } else { 0 };
        }
    }
    0
}

/// Set page double-page spread flag.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_page_double(
    _ctx: ContextHandle,
    doc: Handle,
    page_num: i32,
    double: i32,
) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        if let Some(page) = d.pages.get_mut(page_num as usize) {
            page.double_page = double != 0;
            return 1;
        }
    }
    0
}

// ============================================================================
// FFI Functions - ComicInfo Metadata
// ============================================================================

/// Get comic title.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_title(_ctx: ContextHandle, doc: Handle) -> *mut c_char {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(ref title) = d.info.title {
            if let Ok(cstr) = CString::new(title.clone()) {
                return cstr.into_raw();
            }
        }
    }
    ptr::null_mut()
}

/// Set comic title.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_title(_ctx: ContextHandle, doc: Handle, title: *const c_char) -> i32 {
    if title.is_null() {
        return 0;
    }

    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        let t = unsafe { CStr::from_ptr(title).to_string_lossy().to_string() };
        d.info.title = Some(t);
        return 1;
    }
    0
}

/// Get series name.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_series(_ctx: ContextHandle, doc: Handle) -> *mut c_char {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(ref series) = d.info.series {
            if let Ok(cstr) = CString::new(series.clone()) {
                return cstr.into_raw();
            }
        }
    }
    ptr::null_mut()
}

/// Set series name.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_series(_ctx: ContextHandle, doc: Handle, series: *const c_char) -> i32 {
    if series.is_null() {
        return 0;
    }

    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        let s = unsafe { CStr::from_ptr(series).to_string_lossy().to_string() };
        d.info.series = Some(s);
        return 1;
    }
    0
}

/// Get issue number.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_number(_ctx: ContextHandle, doc: Handle) -> *mut c_char {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(ref num) = d.info.number {
            if let Ok(cstr) = CString::new(num.clone()) {
                return cstr.into_raw();
            }
        }
    }
    ptr::null_mut()
}

/// Set issue number.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_number(_ctx: ContextHandle, doc: Handle, number: *const c_char) -> i32 {
    if number.is_null() {
        return 0;
    }

    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        let n = unsafe { CStr::from_ptr(number).to_string_lossy().to_string() };
        d.info.number = Some(n);
        return 1;
    }
    0
}

/// Get writer.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_writer(_ctx: ContextHandle, doc: Handle) -> *mut c_char {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(ref writer) = d.info.writer {
            if let Ok(cstr) = CString::new(writer.clone()) {
                return cstr.into_raw();
            }
        }
    }
    ptr::null_mut()
}

/// Set writer.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_writer(_ctx: ContextHandle, doc: Handle, writer: *const c_char) -> i32 {
    if writer.is_null() {
        return 0;
    }

    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        let w = unsafe { CStr::from_ptr(writer).to_string_lossy().to_string() };
        d.info.writer = Some(w);
        return 1;
    }
    0
}

/// Get publisher.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_publisher(_ctx: ContextHandle, doc: Handle) -> *mut c_char {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(ref pub_) = d.info.publisher {
            if let Ok(cstr) = CString::new(pub_.clone()) {
                return cstr.into_raw();
            }
        }
    }
    ptr::null_mut()
}

/// Set publisher.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_publisher(
    _ctx: ContextHandle,
    doc: Handle,
    publisher: *const c_char,
) -> i32 {
    if publisher.is_null() {
        return 0;
    }

    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        let p = unsafe { CStr::from_ptr(publisher).to_string_lossy().to_string() };
        d.info.publisher = Some(p);
        return 1;
    }
    0
}

/// Get year.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_year(_ctx: ContextHandle, doc: Handle) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        return d.info.year.unwrap_or(0);
    }
    0
}

/// Set year.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_year(_ctx: ContextHandle, doc: Handle, year: i32) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        d.info.year = if year > 0 { Some(year) } else { None };
        return 1;
    }
    0
}

/// Get manga reading direction.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_manga(_ctx: ContextHandle, doc: Handle) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        return d.info.manga;
    }
    CBZ_MANGA_UNKNOWN
}

/// Set manga reading direction.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_manga(_ctx: ContextHandle, doc: Handle, manga: i32) -> i32 {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        d.info.manga = manga;
        return 1;
    }
    0
}

/// Get summary.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_get_summary(_ctx: ContextHandle, doc: Handle) -> *mut c_char {
    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let d = d.lock().unwrap();
        if let Some(ref summary) = d.info.summary {
            if let Ok(cstr) = CString::new(summary.clone()) {
                return cstr.into_raw();
            }
        }
    }
    ptr::null_mut()
}

/// Set summary.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_set_summary(_ctx: ContextHandle, doc: Handle, summary: *const c_char) -> i32 {
    if summary.is_null() {
        return 0;
    }

    if let Some(d) = CBZ_DOCUMENTS.get(doc) {
        let mut d = d.lock().unwrap();
        let s = unsafe { CStr::from_ptr(summary).to_string_lossy().to_string() };
        d.info.summary = Some(s);
        return 1;
    }
    0
}

// ============================================================================
// FFI Functions - Utility
// ============================================================================

/// Free a string returned by CBZ functions.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_free_string(s: *mut c_char) {
    if !s.is_null() {
        unsafe {
            drop(CString::from_raw(s));
        }
    }
}

/// Check if filename is a supported image.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_is_image_file(_ctx: ContextHandle, filename: *const c_char) -> i32 {
    if filename.is_null() {
        return 0;
    }

    let name = unsafe { CStr::from_ptr(filename).to_string_lossy() };
    if CbzDocument::is_image_file(&name) {
        1
    } else {
        0
    }
}

/// Get format name string.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_format_name(_ctx: ContextHandle, format: i32) -> *mut c_char {
    let name = match format {
        CBZ_FORMAT_CBZ => "CBZ (ZIP)",
        CBZ_FORMAT_CBR => "CBR (RAR)",
        CBZ_FORMAT_CB7 => "CB7 (7z)",
        CBZ_FORMAT_CBT => "CBT (TAR)",
        _ => "Unknown",
    };

    if let Ok(cstr) = CString::new(name) {
        return cstr.into_raw();
    }
    ptr::null_mut()
}

/// Get image format name string.
#[unsafe(no_mangle)]
pub extern "C" fn cbz_image_format_name(_ctx: ContextHandle, format: i32) -> *mut c_char {
    let name = match format {
        CBZ_IMAGE_JPEG => "JPEG",
        CBZ_IMAGE_PNG => "PNG",
        CBZ_IMAGE_GIF => "GIF",
        CBZ_IMAGE_BMP => "BMP",
        CBZ_IMAGE_TIFF => "TIFF",
        CBZ_IMAGE_WEBP => "WebP",
        CBZ_IMAGE_JP2 => "JPEG 2000",
        _ => "Unknown",
    };

    if let Ok(cstr) = CString::new(name) {
        return cstr.into_raw();
    }
    ptr::null_mut()
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_format_constants() {
        assert_eq!(CBZ_FORMAT_CBZ, 0);
        assert_eq!(CBZ_FORMAT_CBR, 1);
    }

    #[test]
    fn test_image_format_constants() {
        assert_eq!(CBZ_IMAGE_JPEG, 0);
        assert_eq!(CBZ_IMAGE_PNG, 1);
    }

    #[test]
    fn test_manga_constants() {
        assert_eq!(CBZ_MANGA_UNKNOWN, 0);
        assert_eq!(CBZ_MANGA_YES, 1);
        assert_eq!(CBZ_MANGA_NO, 2);
    }

    #[test]
    fn test_natural_sort() {
        assert_eq!(natural_cmp("page1", "page2"), std::cmp::Ordering::Less);
        assert_eq!(natural_cmp("page2", "page10"), std::cmp::Ordering::Less);
        assert_eq!(natural_cmp("page10", "page2"), std::cmp::Ordering::Greater);
        assert_eq!(natural_cmp("Page1", "page1"), std::cmp::Ordering::Equal);
    }

    #[test]
    fn test_is_image_file() {
        assert!(CbzDocument::is_image_file("page001.jpg"));
        assert!(CbzDocument::is_image_file("cover.png"));
        assert!(CbzDocument::is_image_file("IMAGE.JPEG"));
        assert!(!CbzDocument::is_image_file("ComicInfo.xml"));
        assert!(!CbzDocument::is_image_file("readme.txt"));
    }

    #[test]
    fn test_cbz_page() {
        let mut page = CbzPage::new(0, "page001.jpg");
        page.detect_format();
        assert_eq!(page.format, CBZ_IMAGE_JPEG);

        let mut page2 = CbzPage::new(1, "cover.png");
        page2.detect_format();
        assert_eq!(page2.format, CBZ_IMAGE_PNG);
    }

    #[test]
    fn test_comic_info() {
        let mut info = ComicInfo::new();
        info.title = Some("Batman #1".to_string());
        info.series = Some("Batman".to_string());
        info.number = Some("1".to_string());
        info.manga = CBZ_MANGA_NO;

        assert_eq!(info.title, Some("Batman #1".to_string()));
        assert_eq!(info.manga, CBZ_MANGA_NO);
    }

    #[test]
    fn test_cbz_document() {
        let mut doc = CbzDocument::new(0);

        doc.add_entry("page002.jpg");
        doc.add_entry("page001.jpg");
        doc.add_entry("page010.jpg");
        doc.add_entry("ComicInfo.xml"); // Should not be added as page

        assert_eq!(doc.page_count(), 3);

        doc.sort_pages();
        assert_eq!(doc.pages[0].filename, "page001.jpg");
        assert_eq!(doc.pages[1].filename, "page002.jpg");
        assert_eq!(doc.pages[2].filename, "page010.jpg");
    }

    #[test]
    fn test_ffi_document() {
        let ctx = 0;

        let doc = cbz_new_document(ctx);
        assert!(doc > 0);

        assert_eq!(cbz_page_count(ctx, doc), 0);
        assert_eq!(cbz_get_format(ctx, doc), CBZ_FORMAT_CBZ);

        cbz_drop_document(ctx, doc);
    }

    #[test]
    fn test_ffi_entries() {
        let ctx = 0;
        let doc = cbz_new_document(ctx);

        let name1 = CString::new("page001.jpg").unwrap();
        let name2 = CString::new("page002.png").unwrap();

        cbz_add_entry(ctx, doc, name1.as_ptr());
        cbz_add_entry(ctx, doc, name2.as_ptr());

        assert_eq!(cbz_page_count(ctx, doc), 2);

        let filename = cbz_get_page_filename(ctx, doc, 0);
        assert!(!filename.is_null());
        unsafe {
            let s = CStr::from_ptr(filename).to_string_lossy();
            assert_eq!(s, "page001.jpg");
            cbz_free_string(filename);
        }

        assert_eq!(cbz_get_page_format(ctx, doc, 0), CBZ_IMAGE_JPEG);
        assert_eq!(cbz_get_page_format(ctx, doc, 1), CBZ_IMAGE_PNG);

        cbz_drop_document(ctx, doc);
    }

    #[test]
    fn test_ffi_metadata() {
        let ctx = 0;
        let doc = cbz_new_document(ctx);

        let title = CString::new("Spider-Man #1").unwrap();
        cbz_set_title(ctx, doc, title.as_ptr());

        let result = cbz_get_title(ctx, doc);
        assert!(!result.is_null());
        unsafe {
            let s = CStr::from_ptr(result).to_string_lossy();
            assert_eq!(s, "Spider-Man #1");
            cbz_free_string(result);
        }

        cbz_set_year(ctx, doc, 2023);
        assert_eq!(cbz_get_year(ctx, doc), 2023);

        cbz_set_manga(ctx, doc, CBZ_MANGA_YES);
        assert_eq!(cbz_get_manga(ctx, doc), CBZ_MANGA_YES);

        cbz_drop_document(ctx, doc);
    }

    #[test]
    fn test_ffi_page_size() {
        let ctx = 0;
        let doc = cbz_new_document(ctx);

        let name = CString::new("page001.jpg").unwrap();
        cbz_add_entry(ctx, doc, name.as_ptr());

        cbz_set_page_size(ctx, doc, 0, 1920, 2560);

        let mut w: i32 = 0;
        let mut h: i32 = 0;
        cbz_get_page_size(ctx, doc, 0, &mut w, &mut h);
        assert_eq!(w, 1920);
        assert_eq!(h, 2560);

        cbz_drop_document(ctx, doc);
    }

    #[test]
    fn test_ffi_format_names() {
        let ctx = 0;

        let name = cbz_format_name(ctx, CBZ_FORMAT_CBZ);
        unsafe {
            let s = CStr::from_ptr(name).to_string_lossy();
            assert!(s.contains("ZIP"));
            cbz_free_string(name);
        }

        let img_name = cbz_image_format_name(ctx, CBZ_IMAGE_PNG);
        unsafe {
            let s = CStr::from_ptr(img_name).to_string_lossy();
            assert_eq!(s, "PNG");
            cbz_free_string(img_name);
        }
    }

    #[test]
    fn test_ffi_is_image() {
        let ctx = 0;

        let jpg = CString::new("page.jpg").unwrap();
        let xml = CString::new("ComicInfo.xml").unwrap();

        assert_eq!(cbz_is_image_file(ctx, jpg.as_ptr()), 1);
        assert_eq!(cbz_is_image_file(ctx, xml.as_ptr()), 0);
    }

    #[test]
    fn test_ffi_null_handles() {
        let ctx = 0;
        assert_eq!(cbz_open_document(ctx, std::ptr::null()), 0);
        assert_eq!(
            cbz_add_entry(ctx, 0, CString::new("x.jpg").unwrap().as_ptr()),
            0
        );
        assert_eq!(cbz_add_entry(ctx, 1, std::ptr::null()), 0);
        assert_eq!(cbz_page_count(ctx, 0), 0);
        assert_eq!(cbz_get_format(ctx, 0), CBZ_FORMAT_CBZ);
        assert_eq!(cbz_sort_pages(ctx, 0), 0);
        assert!(cbz_get_page_filename(ctx, 0, 0).is_null());
        assert_eq!(cbz_get_page_format(ctx, 0, 0), CBZ_IMAGE_UNKNOWN);
        assert_eq!(cbz_is_image_file(ctx, std::ptr::null()), 0);
    }

    #[test]
    fn test_ffi_page_size_null_ptrs() {
        let ctx = 0;
        let doc = cbz_new_document(ctx);
        let name = CString::new("page.jpg").unwrap();
        cbz_add_entry(ctx, doc, name.as_ptr());
        let mut w: i32 = 0;
        let mut h: i32 = 0;
        cbz_get_page_size(ctx, doc, 0, std::ptr::null_mut(), &mut h);
        cbz_get_page_size(ctx, doc, 0, &mut w, std::ptr::null_mut());
        cbz_drop_document(ctx, doc);
    }

    #[test]
    fn test_ffi_double_page() {
        let ctx = 0;
        let doc = cbz_new_document(ctx);
        let name = CString::new("page.jpg").unwrap();
        cbz_add_entry(ctx, doc, name.as_ptr());
        assert_eq!(cbz_page_is_double(ctx, doc, 0), 0);
        cbz_set_page_double(ctx, doc, 0, 1);
        assert_eq!(cbz_page_is_double(ctx, doc, 0), 1);
        cbz_drop_document(ctx, doc);
    }

    #[test]
    fn test_ffi_metadata_getters_empty() {
        let ctx = 0;
        let doc = cbz_new_document(ctx);
        assert!(cbz_get_title(ctx, doc).is_null());
        assert!(cbz_get_series(ctx, doc).is_null());
        assert!(cbz_get_number(ctx, doc).is_null());
        assert!(cbz_get_writer(ctx, doc).is_null());
        assert!(cbz_get_publisher(ctx, doc).is_null());
        assert!(cbz_get_summary(ctx, doc).is_null());
        assert_eq!(cbz_get_year(ctx, doc), 0);
        assert_eq!(cbz_get_manga(ctx, doc), CBZ_MANGA_UNKNOWN);
        cbz_drop_document(ctx, doc);
    }

    #[test]
    fn test_ffi_metadata_setters_null() {
        let ctx = 0;
        let doc = cbz_new_document(ctx);
        assert_eq!(cbz_set_title(ctx, doc, std::ptr::null()), 0);
        assert_eq!(cbz_set_series(ctx, doc, std::ptr::null()), 0);
        assert_eq!(cbz_set_number(ctx, doc, std::ptr::null()), 0);
        assert_eq!(cbz_set_writer(ctx, doc, std::ptr::null()), 0);
        assert_eq!(cbz_set_publisher(ctx, doc, std::ptr::null()), 0);
        assert_eq!(cbz_set_summary(ctx, doc, std::ptr::null()), 0);
        cbz_drop_document(ctx, doc);
    }

    #[test]
    fn test_ffi_free_string_null() {
        cbz_free_string(std::ptr::null_mut());
    }

    #[test]
    fn test_ffi_format_names_all() {
        let ctx = 0;
        for fmt in [
            CBZ_FORMAT_CBZ,
            CBZ_FORMAT_CBR,
            CBZ_FORMAT_CB7,
            CBZ_FORMAT_CBT,
            99,
        ] {
            let name = cbz_format_name(ctx, fmt);
            assert!(!name.is_null());
            cbz_free_string(name);
        }
    }

    #[test]
    fn test_ffi_image_format_names_all() {
        let ctx = 0;
        for fmt in [
            CBZ_IMAGE_JPEG,
            CBZ_IMAGE_PNG,
            CBZ_IMAGE_GIF,
            CBZ_IMAGE_BMP,
            CBZ_IMAGE_TIFF,
            CBZ_IMAGE_WEBP,
            CBZ_IMAGE_JP2,
            99,
        ] {
            let name = cbz_image_format_name(ctx, fmt);
            assert!(!name.is_null());
            cbz_free_string(name);
        }
    }

    #[test]
    fn test_cbz_page_detect_all_formats() {
        let formats = [
            ("x.gif", CBZ_IMAGE_GIF),
            ("x.bmp", CBZ_IMAGE_BMP),
            ("x.tif", CBZ_IMAGE_TIFF),
            ("x.tiff", CBZ_IMAGE_TIFF),
            ("x.webp", CBZ_IMAGE_WEBP),
            ("x.jp2", CBZ_IMAGE_JP2),
            ("x.j2k", CBZ_IMAGE_JP2),
            ("x.unknown", CBZ_IMAGE_UNKNOWN),
        ];
        for (name, expected) in formats {
            let mut page = CbzPage::new(0, name);
            page.detect_format();
            assert_eq!(page.format, expected, "{}", name);
        }
    }

    #[test]
    fn test_natural_cmp_edge_cases() {
        assert_eq!(natural_cmp("", ""), std::cmp::Ordering::Equal);
        assert_eq!(natural_cmp("a", ""), std::cmp::Ordering::Greater);
        assert_eq!(natural_cmp("", "b"), std::cmp::Ordering::Less);
        assert_eq!(natural_cmp("page1", "page1"), std::cmp::Ordering::Equal);
    }

    #[test]
    fn test_ffi_series_number_writer_publisher() {
        let ctx = 0;
        let doc = cbz_new_document(ctx);
        let s = CString::new("Batman").unwrap();
        cbz_set_series(ctx, doc, s.as_ptr());
        let r = cbz_get_series(ctx, doc);
        assert!(!r.is_null());
        cbz_free_string(r);
        let n = CString::new("1").unwrap();
        cbz_set_number(ctx, doc, n.as_ptr());
        let rn = cbz_get_number(ctx, doc);
        assert!(!rn.is_null());
        cbz_free_string(rn);
        let w = CString::new("Writer").unwrap();
        cbz_set_writer(ctx, doc, w.as_ptr());
        let rw = cbz_get_writer(ctx, doc);
        assert!(!rw.is_null());
        cbz_free_string(rw);
        let p = CString::new("DC").unwrap();
        cbz_set_publisher(ctx, doc, p.as_ptr());
        let rp = cbz_get_publisher(ctx, doc);
        assert!(!rp.is_null());
        cbz_free_string(rp);
        let sum = CString::new("Summary").unwrap();
        cbz_set_summary(ctx, doc, sum.as_ptr());
        let rs = cbz_get_summary(ctx, doc);
        assert!(!rs.is_null());
        cbz_free_string(rs);
        cbz_set_year(ctx, doc, 0);
        assert_eq!(cbz_get_year(ctx, doc), 0);
        cbz_drop_document(ctx, doc);
    }
}