boko 0.2.0

Fast ebook conversion library for EPUB and Kindle formats
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
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
//! KF8 Index parsing (INDX, TAGX, CNCX)
//!
//! KF8 files use several index tables:
//! - Skeleton index: file entries (HTML parts)
//! - Div index: content chunks to insert into skeletons
//! - NCX index: table of contents
//! - Other index: guide entries (cover, toc, etc.)

use std::collections::HashMap;

use std::io;

/// Variable-width integer decoding (forward)
/// Each byte uses 7 bits for data, high bit indicates continuation
pub fn decint(data: &[u8]) -> (u32, usize) {
    let mut val: u32 = 0;
    let mut consumed = 0;

    for &byte in data {
        consumed += 1;
        val = (val << 7) | ((byte & 0x7F) as u32);
        if byte & 0x80 != 0 {
            break;
        }
    }

    (val, consumed)
}

/// Count number of bits set in a value
fn count_set_bits(mut n: u8) -> u8 {
    let mut count = 0;
    while n > 0 {
        count += n & 1;
        n >>= 1;
    }
    count
}

/// TAGX entry: defines how to interpret index entries
#[derive(Debug, Clone)]
pub struct TagXEntry {
    pub tag: u8,
    pub num_values: u8,
    pub bitmask: u8,
    pub eof: u8,
}

/// Parsed INDX header
#[derive(Debug)]
#[allow(dead_code)] // Fields are part of MOBI format spec
pub struct IndxHeader {
    pub header_type: u32,
    pub idxt_start: u32,
    pub entry_count: u32,
    pub encoding: u32,
    pub total_entries: u32,
    pub ordt_offset: u32,
    pub ligt_offset: u32,
    pub num_ligt: u32,
    pub num_cncx: u32,
    pub tagx_offset: u32,
}

impl IndxHeader {
    pub fn parse(data: &[u8]) -> io::Result<Self> {
        if data.len() < 192 || &data[0..4] != b"INDX" {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Invalid INDX header",
            ));
        }

        let u32_at = |offset: usize| -> u32 {
            u32::from_be_bytes([
                data[offset],
                data[offset + 1],
                data[offset + 2],
                data[offset + 3],
            ])
        };

        Ok(Self {
            header_type: u32_at(8),
            idxt_start: u32_at(20),
            entry_count: u32_at(24),
            encoding: u32_at(28),
            total_entries: u32_at(36),
            ordt_offset: u32_at(40),
            ligt_offset: u32_at(44),
            num_ligt: u32_at(48),
            num_cncx: u32_at(52),
            tagx_offset: u32_at(180),
        })
    }
}

/// Parse TAGX section from index header
pub fn parse_tagx(data: &[u8]) -> io::Result<(u32, Vec<TagXEntry>)> {
    if data.len() < 12 || &data[0..4] != b"TAGX" {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "Invalid TAGX section",
        ));
    }

    let first_entry_offset = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
    let control_byte_count = u32::from_be_bytes([data[8], data[9], data[10], data[11]]);

    let mut tags = Vec::new();
    let mut i = 12;
    while i + 4 <= first_entry_offset as usize && i + 4 <= data.len() {
        tags.push(TagXEntry {
            tag: data[i],
            num_values: data[i + 1],
            bitmask: data[i + 2],
            eof: data[i + 3],
        });
        i += 4;
    }

    Ok((control_byte_count, tags))
}

/// Extract tag values from an index entry
pub fn get_tag_map(
    control_byte_count: u32,
    tagx: &[TagXEntry],
    data: &[u8],
) -> HashMap<u8, Vec<u32>> {
    let mut result: HashMap<u8, Vec<u32>> = HashMap::new();

    if data.len() < control_byte_count as usize {
        return result;
    }

    let control_bytes: Vec<u8> = data[..control_byte_count as usize].to_vec();
    let mut pos = control_byte_count as usize;
    let mut control_idx = 0;

    // First pass: determine which tags are present and their counts
    struct PendingTag {
        tag: u8,
        value_count: Option<u32>,
        value_bytes: Option<u32>,
        num_values: u8,
    }

    let mut pending: Vec<PendingTag> = Vec::new();

    for entry in tagx {
        if entry.eof == 0x01 {
            control_idx += 1;
            continue;
        }

        if control_idx >= control_bytes.len() {
            break;
        }

        let value = control_bytes[control_idx] & entry.bitmask;
        if value != 0 {
            let (value_count, value_bytes) = if value == entry.bitmask {
                if count_set_bits(entry.bitmask) > 1 {
                    // Variable width value follows
                    let (vb, consumed) = decint(&data[pos..]);
                    pos += consumed;
                    (None, Some(vb))
                } else {
                    (Some(1), None)
                }
            } else {
                // Shift to get actual count
                let mut mask = entry.bitmask;
                let mut shifted_value = value;
                while mask & 1 == 0 {
                    mask >>= 1;
                    shifted_value >>= 1;
                }
                (Some(shifted_value as u32), None)
            };

            pending.push(PendingTag {
                tag: entry.tag,
                value_count,
                value_bytes,
                num_values: entry.num_values,
            });
        }
    }

    // Second pass: read actual values
    for p in pending {
        let mut values = Vec::new();

        if let Some(count) = p.value_count {
            for _ in 0..(count * p.num_values as u32) {
                if pos >= data.len() {
                    break;
                }
                let (v, consumed) = decint(&data[pos..]);
                pos += consumed;
                values.push(v);
            }
        } else if let Some(bytes) = p.value_bytes {
            let mut consumed_total = 0;
            while consumed_total < bytes as usize && pos < data.len() {
                let (v, consumed) = decint(&data[pos..]);
                pos += consumed;
                consumed_total += consumed;
                values.push(v);
            }
        }

        result.insert(p.tag, values);
    }

    result
}

/// Decode a length-prefixed string
pub fn decode_string(data: &[u8], codec: &str) -> (String, usize) {
    if data.is_empty() {
        return (String::new(), 0);
    }

    let length = data[0] as usize;
    if length == 0 || data.len() < length + 1 {
        return (String::new(), 1);
    }

    let bytes = &data[1..1 + length];
    let s = crate::util::decode_text(bytes, Some(codec)).into_owned();

    (s, length + 1)
}

/// CNCX (Compiled NCX) - string table for index entries
#[derive(Debug, Default)]
pub struct Cncx {
    pub strings: HashMap<u32, String>,
}

impl Cncx {
    pub fn new() -> Self {
        Self::default()
    }

    /// Parse CNCX records
    pub fn parse(records: &[Vec<u8>], codec: &str) -> Self {
        let mut strings = HashMap::new();
        let mut record_offset: u32 = 0;

        for raw in records {
            let mut pos = 0;
            while pos < raw.len() {
                let (length, consumed) = decint(&raw[pos..]);
                if length > 0 && pos + consumed + length as usize <= raw.len() {
                    let bytes = &raw[pos + consumed..pos + consumed + length as usize];
                    let s = match codec {
                        "utf-8" | "UTF-8" => String::from_utf8_lossy(bytes).to_string(),
                        _ => String::from_utf8_lossy(bytes).to_string(),
                    };
                    strings.insert((pos as u32) + record_offset, s);
                }
                pos += consumed + length as usize;
            }
            record_offset += 0x10000;
        }

        Self { strings }
    }

    pub fn get(&self, offset: u32) -> Option<&String> {
        self.strings.get(&offset)
    }
}

/// Index table entry (generic)
#[derive(Debug, Clone)]
pub struct IndexEntry {
    pub name: String,
    pub tags: HashMap<u8, Vec<u32>>,
}

/// Read a complete index table
pub fn read_index(
    read_record: &mut dyn FnMut(usize) -> io::Result<Vec<u8>>,
    index_record: usize,
    codec: &str,
) -> io::Result<(Vec<IndexEntry>, Cncx)> {
    let header_data = read_record(index_record)?;
    let header = IndxHeader::parse(&header_data)?;

    // Find TAGX section
    let tagx_start = if header.tagx_offset > 0 && header.tagx_offset < header_data.len() as u32 {
        header.tagx_offset as usize
    } else {
        // Search for TAGX
        header_data
            .windows(4)
            .position(|w| w == b"TAGX")
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "TAGX not found"))?
    };

    let (control_byte_count, tagx) = parse_tagx(&header_data[tagx_start..])?;

    // Parse CNCX records if present
    let cncx = if header.num_cncx > 0 {
        let cncx_start = index_record + header.entry_count as usize + 1;
        let mut cncx_records = Vec::new();
        for i in 0..header.num_cncx as usize {
            if let Ok(rec) = read_record(cncx_start + i) {
                cncx_records.push(rec);
            }
        }
        Cncx::parse(&cncx_records, codec)
    } else {
        Cncx::new()
    };

    // Parse index entries from subsequent records
    let mut entries = Vec::new();

    for i in 0..header.entry_count as usize {
        let rec_data = read_record(index_record + 1 + i)?;
        let rec_header = IndxHeader::parse(&rec_data)?;

        // Find IDXT position table
        let idxt_pos = rec_header.idxt_start as usize;
        if idxt_pos + 4 > rec_data.len() || &rec_data[idxt_pos..idxt_pos + 4] != b"IDXT" {
            continue;
        }

        // Read entry positions
        let mut positions: Vec<usize> = Vec::new();
        for j in 0..rec_header.entry_count as usize {
            let off = idxt_pos + 4 + j * 2;
            if off + 2 <= rec_data.len() {
                let pos = u16::from_be_bytes([rec_data[off], rec_data[off + 1]]) as usize;
                positions.push(pos);
            }
        }
        positions.push(idxt_pos); // Last entry ends at IDXT

        // Parse each entry
        for j in 0..positions.len().saturating_sub(1) {
            let start = positions[j];
            let end = positions[j + 1];
            if start >= end || start >= rec_data.len() {
                continue;
            }

            let entry_data = &rec_data[start..end];
            let (name, consumed) = decode_string(entry_data, codec);
            let tag_data = &entry_data[consumed..];
            let tags = get_tag_map(control_byte_count, &tagx, tag_data);

            entries.push(IndexEntry { name, tags });
        }
    }

    Ok((entries, cncx))
}

/// Skeleton file entry from skel index
#[derive(Debug, Clone)]
#[allow(dead_code)] // Fields are part of MOBI format spec
pub struct SkeletonFile {
    pub file_number: usize,
    pub name: String,
    pub div_count: u32,
    pub start_pos: u32,
    pub length: u32,
}

/// Div element entry from div index
#[derive(Debug, Clone)]
#[allow(dead_code)] // Fields are part of MOBI format spec
pub struct DivElement {
    pub insert_pos: u32,
    pub toc_text: Option<String>,
    pub file_number: u32,
    pub sequence_number: u32,
    pub start_pos: u32,
    pub length: u32,
}

/// NCX entry for table of contents
#[derive(Debug, Clone)]
#[allow(dead_code)] // Fields are part of MOBI format spec
pub struct NcxEntry {
    pub name: String,
    pub text: String,
    pub pos: u32,
    pub length: u32,
    pub level: i32,
    pub parent: i32,
    pub pos_fid: Option<(u32, u32)>,
}

/// Parse skeleton index into file entries
pub fn parse_skel_index(entries: &[IndexEntry]) -> Vec<SkeletonFile> {
    let mut files = Vec::new();

    for (i, entry) in entries.iter().enumerate() {
        // Tag 1 = div count, Tag 6 = [start_pos, length]
        let div_count = entry
            .tags
            .get(&1)
            .and_then(|v| v.first())
            .copied()
            .unwrap_or(0);
        let (start_pos, length) = entry
            .tags
            .get(&6)
            .map(|v| {
                (
                    v.first().copied().unwrap_or(0),
                    v.get(1).copied().unwrap_or(0),
                )
            })
            .unwrap_or((0, 0));

        files.push(SkeletonFile {
            file_number: i,
            name: entry.name.clone(),
            div_count,
            start_pos,
            length,
        });
    }

    files
}

/// Parse div index into element entries
pub fn parse_div_index(entries: &[IndexEntry], cncx: &Cncx) -> Vec<DivElement> {
    let mut elems = Vec::new();

    for entry in entries {
        // Parse insert_pos from entry name (it's the numeric identifier)
        let insert_pos: u32 = entry.name.parse().unwrap_or(0);

        // Tag 2 = cncx offset for toc text
        let toc_text = entry
            .tags
            .get(&2)
            .and_then(|v| v.first())
            .and_then(|&off| cncx.get(off).cloned());

        // Tag 3 = file number
        let file_number = entry
            .tags
            .get(&3)
            .and_then(|v| v.first())
            .copied()
            .unwrap_or(0);

        // Tag 4 = sequence number
        let sequence_number = entry
            .tags
            .get(&4)
            .and_then(|v| v.first())
            .copied()
            .unwrap_or(0);

        // Tag 6 = [start_pos, length]
        let (start_pos, length) = entry
            .tags
            .get(&6)
            .map(|v| {
                (
                    v.first().copied().unwrap_or(0),
                    v.get(1).copied().unwrap_or(0),
                )
            })
            .unwrap_or((0, 0));

        elems.push(DivElement {
            insert_pos,
            toc_text,
            file_number,
            sequence_number,
            start_pos,
            length,
        });
    }

    elems
}

/// Parse NCX index into TOC entries
pub fn parse_ncx_index(entries: &[IndexEntry], cncx: &Cncx) -> Vec<NcxEntry> {
    let mut ncx_entries = Vec::new();

    for entry in entries {
        // Tag 1 = position
        let pos = entry
            .tags
            .get(&1)
            .and_then(|v| v.first())
            .copied()
            .unwrap_or(0);

        // Tag 2 = length
        let length = entry
            .tags
            .get(&2)
            .and_then(|v| v.first())
            .copied()
            .unwrap_or(0);

        // Tag 3 = cncx offset for text
        let text = entry
            .tags
            .get(&3)
            .and_then(|v| v.first())
            .and_then(|&off| cncx.get(off).cloned())
            .unwrap_or_else(|| entry.name.clone());

        // Tag 4 = hierarchy level
        let level = entry
            .tags
            .get(&4)
            .and_then(|v| v.first())
            .map(|&v| v as i32)
            .unwrap_or(-1);

        // Tag 6 = pos_fid (file index, offset)
        let pos_fid = entry.tags.get(&6).map(|v| {
            (
                v.first().copied().unwrap_or(0),
                v.get(1).copied().unwrap_or(0),
            )
        });

        // Tag 21 = parent index
        let parent = entry
            .tags
            .get(&21)
            .and_then(|v| v.first())
            .map(|&v| v as i32)
            .unwrap_or(-1);

        ncx_entries.push(NcxEntry {
            name: entry.name.clone(),
            text,
            pos,
            length,
            level,
            parent,
            pos_fid,
        });
    }

    ncx_entries
}

// ============================================================================
// INDX Record Generation (for writing KF8 files)
// ============================================================================

/// Encode a variable-width integer (forward encoding, high bit set on last byte)
pub fn encint(val: u32) -> Vec<u8> {
    if val == 0 {
        return vec![0x80];
    }

    let mut result = Vec::new();
    let mut v = val;
    while v > 0 {
        result.push((v & 0x7F) as u8);
        v >>= 7;
    }

    // Set high bit on first byte (which becomes last after reverse)
    if let Some(first) = result.first_mut() {
        *first |= 0x80;
    }

    result.reverse();
    result
}

/// Tag definition for TAGX section
#[derive(Debug, Clone, Copy)]
pub struct TagDef {
    pub tag: u8,
    pub values_per_entry: u8,
    pub bitmask: u8,
    pub eof: u8,
}

/// INDX record builder
pub struct IndxBuilder {
    entries: Vec<(String, Vec<u8>)>, // (name, encoded_data)
    tagx: Vec<TagDef>,
    control_byte_count: u8,
    num_cncx: u32,
}

impl IndxBuilder {
    pub fn new(tagx: Vec<TagDef>, control_byte_count: u8) -> Self {
        Self {
            entries: Vec::new(),
            tagx,
            control_byte_count,
            num_cncx: 0,
        }
    }

    pub fn set_cncx_count(&mut self, count: u32) {
        self.num_cncx = count;
    }

    /// Add an entry with pre-encoded tag data
    pub fn add_entry(&mut self, name: String, tag_data: Vec<u8>) {
        self.entries.push((name, tag_data));
    }

    /// Build the INDX record(s)
    pub fn build(&self) -> Vec<Vec<u8>> {
        if self.entries.is_empty() {
            return vec![self.build_header_record(0, 0)];
        }

        // For simplicity, put all entries in one record (works for small indices)
        let (entry_data, idxt_offsets) = self.build_entries();
        let idxt = self.build_idxt(&idxt_offsets, entry_data.len());

        // Build the single data record
        let data_record = self.build_data_record(&entry_data, &idxt);

        // Build header record
        let header_record = self.build_header_record(self.entries.len() as u32, 1);

        vec![header_record, data_record]
    }

    fn build_header_record(&self, total_entries: u32, num_records: u32) -> Vec<u8> {
        let mut record = Vec::new();

        // INDX signature (offset 0)
        record.extend_from_slice(b"INDX");

        // len: Header length (offset 4)
        record.extend_from_slice(&192u32.to_be_bytes());

        // nul1: Unknown/zero (offset 8)
        record.extend_from_slice(&0u32.to_be_bytes());

        // type: Index type (offset 12) - 2 = inflection/KF8
        record.extend_from_slice(&2u32.to_be_bytes());

        // gen: Generation/unknown (offset 16)
        record.extend_from_slice(&0u32.to_be_bytes());

        // start: IDXT offset (offset 20) - 0 for header record
        record.extend_from_slice(&0u32.to_be_bytes());

        // count: Number of data records (offset 24)
        record.extend_from_slice(&num_records.to_be_bytes());

        // code: Encoding (offset 28) - 65001 = UTF-8
        record.extend_from_slice(&65001u32.to_be_bytes());

        // lng: Language (offset 32)
        record.extend_from_slice(&0u32.to_be_bytes());

        // total: Total entries across all records (offset 36)
        record.extend_from_slice(&total_entries.to_be_bytes());

        // ordt: ORDT offset (offset 40)
        record.extend_from_slice(&0u32.to_be_bytes());

        // ligt: LIGT offset (offset 44)
        record.extend_from_slice(&0u32.to_be_bytes());

        // nligt: Number of LIGT entries (offset 48)
        record.extend_from_slice(&0u32.to_be_bytes());

        // ncncx: Number of CNCX records (offset 52)
        record.extend_from_slice(&self.num_cncx.to_be_bytes());

        // Unknown fields (27 u32s = 108 bytes) (offset 56-163)
        record.extend_from_slice(&[0u8; 108]);

        // ocnt (offset 164)
        record.extend_from_slice(&0u32.to_be_bytes());

        // oentries (offset 168)
        record.extend_from_slice(&0u32.to_be_bytes());

        // ordt1 (offset 172)
        record.extend_from_slice(&0u32.to_be_bytes());

        // ordt2 (offset 176)
        record.extend_from_slice(&0u32.to_be_bytes());

        // tagx: TAGX offset (offset 180) - points to TAGX after header
        record.extend_from_slice(&192u32.to_be_bytes());

        // Padding to reach 192 bytes (offsets 184-191)
        record.extend_from_slice(&[0u8; 8]);

        // TAGX section (after 192-byte header)
        record.extend_from_slice(&self.build_tagx());

        record
    }

    fn build_data_record(&self, entry_data: &[u8], idxt: &[u8]) -> Vec<u8> {
        let mut record = Vec::new();

        // Calculate IDXT offset
        let idxt_offset = 192 + entry_data.len();

        // INDX signature (offset 0)
        record.extend_from_slice(b"INDX");

        // len: Header length (offset 4)
        record.extend_from_slice(&192u32.to_be_bytes());

        // nul1: Unknown/zero (offset 8)
        record.extend_from_slice(&0u32.to_be_bytes());

        // type: Index type (offset 12)
        record.extend_from_slice(&2u32.to_be_bytes());

        // gen: Generation/unknown (offset 16)
        record.extend_from_slice(&0u32.to_be_bytes());

        // start: IDXT offset (offset 20)
        record.extend_from_slice(&(idxt_offset as u32).to_be_bytes());

        // count: Number of entries in this record (offset 24)
        record.extend_from_slice(&(self.entries.len() as u32).to_be_bytes());

        // code: Encoding (offset 28) - 65001 = UTF-8
        record.extend_from_slice(&65001u32.to_be_bytes());

        // lng: Language (offset 32)
        record.extend_from_slice(&0u32.to_be_bytes());

        // total: Total entries (offset 36)
        record.extend_from_slice(&(self.entries.len() as u32).to_be_bytes());

        // ordt: ORDT offset (offset 40)
        record.extend_from_slice(&0u32.to_be_bytes());

        // ligt: LIGT offset (offset 44)
        record.extend_from_slice(&0u32.to_be_bytes());

        // nligt: Number of LIGT entries (offset 48)
        record.extend_from_slice(&0u32.to_be_bytes());

        // ncncx: Number of CNCX records (offset 52)
        record.extend_from_slice(&self.num_cncx.to_be_bytes());

        // Unknown fields (27 u32s = 108 bytes) (offset 56-163)
        record.extend_from_slice(&[0u8; 108]);

        // ocnt (offset 164)
        record.extend_from_slice(&0u32.to_be_bytes());

        // oentries (offset 168)
        record.extend_from_slice(&0u32.to_be_bytes());

        // ordt1 (offset 172)
        record.extend_from_slice(&0u32.to_be_bytes());

        // ordt2 (offset 176)
        record.extend_from_slice(&0u32.to_be_bytes());

        // tagx: TAGX offset (offset 180) - 0 for data records
        record.extend_from_slice(&0u32.to_be_bytes());

        // Padding to reach 192 bytes (offsets 184-191)
        record.extend_from_slice(&[0u8; 8]);

        // Entry data
        record.extend_from_slice(entry_data);

        // IDXT
        record.extend_from_slice(idxt);

        // Pad to 4-byte boundary
        while !record.len().is_multiple_of(4) {
            record.push(0);
        }

        record
    }

    fn build_tagx(&self) -> Vec<u8> {
        let mut tagx = Vec::new();

        // TAGX signature
        tagx.extend_from_slice(b"TAGX");

        // Block size: 12 + (4 * num_tags)
        let size = 12 + (4 * self.tagx.len()) as u32;
        tagx.extend_from_slice(&size.to_be_bytes());

        // Control byte count
        tagx.extend_from_slice(&(self.control_byte_count as u32).to_be_bytes());

        // Tag definitions
        for tag in &self.tagx {
            tagx.push(tag.tag);
            tagx.push(tag.values_per_entry);
            tagx.push(tag.bitmask);
            tagx.push(tag.eof);
        }

        tagx
    }

    fn build_entries(&self) -> (Vec<u8>, Vec<u16>) {
        let mut data = Vec::new();
        let mut offsets = Vec::new();

        for (name, tag_data) in &self.entries {
            offsets.push((192 + data.len()) as u16);

            let name_bytes = name.as_bytes();
            data.push(name_bytes.len() as u8);
            data.extend_from_slice(name_bytes);
            data.extend_from_slice(tag_data);
        }

        (data, offsets)
    }

    fn build_idxt(&self, offsets: &[u16], entry_data_len: usize) -> Vec<u8> {
        let mut idxt = Vec::new();

        // IDXT signature
        idxt.extend_from_slice(b"IDXT");

        // Entry offsets (2 bytes each, big-endian)
        for &offset in offsets {
            idxt.extend_from_slice(&offset.to_be_bytes());
        }

        // Add end-of-data offset
        let end_offset = (192 + entry_data_len) as u16;
        idxt.extend_from_slice(&end_offset.to_be_bytes());

        // Pad to 4-byte boundary
        while !idxt.len().is_multiple_of(4) {
            idxt.push(0);
        }

        idxt
    }
}

// Skeleton index tags
const SKEL_TAG_CHUNK_COUNT: TagDef = TagDef {
    tag: 1,
    values_per_entry: 1,
    bitmask: 0x03,
    eof: 0,
};
const SKEL_TAG_GEOMETRY: TagDef = TagDef {
    tag: 6,
    values_per_entry: 2,
    bitmask: 0x0C,
    eof: 0,
};
const SKEL_TAG_EOF: TagDef = TagDef {
    tag: 0,
    values_per_entry: 0,
    bitmask: 0x00,
    eof: 1,
};

/// Build skeleton index records
pub fn build_skel_indx(skeletons: &[super::skeleton::SkelEntry]) -> Vec<Vec<u8>> {
    let tagx = vec![SKEL_TAG_CHUNK_COUNT, SKEL_TAG_GEOMETRY, SKEL_TAG_EOF];
    let mut builder = IndxBuilder::new(tagx, 1);

    for skel in skeletons {
        // Control byte calculation per Calibre:
        // chunk_count: 2 values / vpe=1 = 2 entries. mask=3, shift=0. 3 & (2 << 0) = 2
        // geometry: 4 values / vpe=2 = 2 entries. mask=12, shift=2. 12 & (2 << 2) = 8
        // Total: 2 | 8 = 10 = 0x0A
        let mut tag_data = vec![0x0A];

        // Chunk count (repeated twice per Calibre implementation)
        tag_data.extend(encint(skel.chunk_count as u32));
        tag_data.extend(encint(skel.chunk_count as u32));

        // Geometry: start_pos, length (repeated twice)
        tag_data.extend(encint(skel.start_pos as u32));
        tag_data.extend(encint(skel.length as u32));
        tag_data.extend(encint(skel.start_pos as u32));
        tag_data.extend(encint(skel.length as u32));

        builder.add_entry(skel.name.clone(), tag_data);
    }

    builder.build()
}

// Chunk/Fragment index tags
const CHUNK_TAG_CNCX: TagDef = TagDef {
    tag: 2,
    values_per_entry: 1,
    bitmask: 0x01,
    eof: 0,
};
const CHUNK_TAG_FILE_NUM: TagDef = TagDef {
    tag: 3,
    values_per_entry: 1,
    bitmask: 0x02,
    eof: 0,
};
const CHUNK_TAG_SEQ_NUM: TagDef = TagDef {
    tag: 4,
    values_per_entry: 1,
    bitmask: 0x04,
    eof: 0,
};
const CHUNK_TAG_GEOMETRY: TagDef = TagDef {
    tag: 6,
    values_per_entry: 2,
    bitmask: 0x08,
    eof: 0,
};
const CHUNK_TAG_EOF: TagDef = TagDef {
    tag: 0,
    values_per_entry: 0,
    bitmask: 0x00,
    eof: 1,
};

/// Build CNCX record from chunk selectors
pub fn build_cncx(selectors: &[String]) -> Vec<u8> {
    let mut cncx = Vec::new();

    for selector in selectors {
        let bytes = selector.as_bytes();
        cncx.extend(encint(bytes.len() as u32));
        cncx.extend_from_slice(bytes);
    }

    cncx
}

/// Build chunk/fragment index records
pub fn build_chunk_indx(
    chunks: &[super::skeleton::ChunkEntry],
    cncx_offsets: &[u32],
) -> Vec<Vec<u8>> {
    let tagx = vec![
        CHUNK_TAG_CNCX,
        CHUNK_TAG_FILE_NUM,
        CHUNK_TAG_SEQ_NUM,
        CHUNK_TAG_GEOMETRY,
        CHUNK_TAG_EOF,
    ];
    let mut builder = IndxBuilder::new(tagx, 1);

    if !chunks.is_empty() {
        builder.set_cncx_count(1);
    }

    for (i, chunk) in chunks.iter().enumerate() {
        // Control byte: all tags present
        let ctrl = 0x01 | 0x02 | 0x04 | 0x08;
        let mut tag_data = vec![ctrl];

        // CNCX offset (tag 2)
        let cncx_off = cncx_offsets.get(i).copied().unwrap_or(0);
        tag_data.extend(encint(cncx_off));

        // File number (tag 3)
        tag_data.extend(encint(chunk.file_number as u32));

        // Sequence number (tag 4)
        tag_data.extend(encint(chunk.sequence_number as u32));

        // Geometry (tag 6): start_pos, length
        tag_data.extend(encint(chunk.start_pos as u32));
        tag_data.extend(encint(chunk.length as u32));

        // Entry name is insert_pos as string
        let name = format!("{:010}", chunk.insert_pos);
        builder.add_entry(name, tag_data);
    }

    builder.build()
}

/// Calculate CNCX offsets for a list of selectors
pub fn calculate_cncx_offsets(selectors: &[String]) -> Vec<u32> {
    let mut offsets = Vec::new();
    let mut offset: u32 = 0;

    for selector in selectors {
        offsets.push(offset);
        let len_bytes = encint(selector.len() as u32);
        offset += len_bytes.len() as u32 + selector.len() as u32;
    }

    offsets
}

// NCX (Table of Contents) index tags
const NCX_TAG_OFFSET: TagDef = TagDef {
    tag: 1,
    values_per_entry: 1,
    bitmask: 0x01,
    eof: 0,
};
const NCX_TAG_LENGTH: TagDef = TagDef {
    tag: 2,
    values_per_entry: 1,
    bitmask: 0x02,
    eof: 0,
};
const NCX_TAG_LABEL: TagDef = TagDef {
    tag: 3,
    values_per_entry: 1,
    bitmask: 0x04,
    eof: 0,
};
const NCX_TAG_DEPTH: TagDef = TagDef {
    tag: 4,
    values_per_entry: 1,
    bitmask: 0x08,
    eof: 0,
};
const NCX_TAG_PARENT: TagDef = TagDef {
    tag: 21,
    values_per_entry: 1,
    bitmask: 0x10,
    eof: 0,
};
const NCX_TAG_FIRST_CHILD: TagDef = TagDef {
    tag: 22,
    values_per_entry: 1,
    bitmask: 0x20,
    eof: 0,
};
const NCX_TAG_LAST_CHILD: TagDef = TagDef {
    tag: 23,
    values_per_entry: 1,
    bitmask: 0x40,
    eof: 0,
};
const NCX_TAG_EOF: TagDef = TagDef {
    tag: 0,
    values_per_entry: 0,
    bitmask: 0x00,
    eof: 1,
};

/// NCX entry for building table of contents
#[derive(Debug, Clone)]
pub struct NcxBuildEntry {
    /// Position in text (byte offset)
    pub pos: u32,
    /// Length of the section
    pub length: u32,
    /// Label text (for CNCX)
    pub label: String,
    /// Depth level (0 = top level)
    pub depth: u32,
    /// Index of parent entry (-1 for root entries)
    pub parent: i32,
    /// Index of first child (-1 if no children)
    pub first_child: i32,
    /// Index of last child (-1 if no children)
    pub last_child: i32,
}

/// Build NCX index for table of contents
pub fn build_ncx_indx(entries: &[NcxBuildEntry]) -> (Vec<Vec<u8>>, Vec<u8>) {
    let tagx = vec![
        NCX_TAG_OFFSET,
        NCX_TAG_LENGTH,
        NCX_TAG_LABEL,
        NCX_TAG_DEPTH,
        NCX_TAG_PARENT,
        NCX_TAG_FIRST_CHILD,
        NCX_TAG_LAST_CHILD,
        NCX_TAG_EOF,
    ];
    let mut builder = IndxBuilder::new(tagx, 2); // 2 control bytes for NCX

    // Build CNCX with labels
    let labels: Vec<String> = entries.iter().map(|e| e.label.clone()).collect();
    let label_offsets = calculate_cncx_offsets(&labels);
    let cncx = build_cncx(&labels);

    if !entries.is_empty() {
        builder.set_cncx_count(1);
    }

    for (i, entry) in entries.iter().enumerate() {
        // Control byte 0: tags 1-4 and hierarchy tags
        let mut ctrl: u8 = 0x0F; // Tags 1-4 always present

        let has_parent = entry.parent >= 0;
        let has_first_child = entry.first_child >= 0;
        let has_last_child = entry.last_child >= 0;

        if has_parent {
            ctrl |= 0x10;
        }
        if has_first_child {
            ctrl |= 0x20;
        }
        if has_last_child {
            ctrl |= 0x40;
        }

        // Control byte 1 is unused
        let mut tag_data = vec![ctrl, 0x00];

        // Offset (tag 1)
        tag_data.extend(encint(entry.pos));

        // Length (tag 2)
        tag_data.extend(encint(entry.length));

        // Label (tag 3) - CNCX offset
        let label_offset = label_offsets.get(i).copied().unwrap_or(0);
        tag_data.extend(encint(label_offset));

        // Depth (tag 4)
        tag_data.extend(encint(entry.depth));

        // Parent (tag 21)
        if has_parent {
            tag_data.extend(encint(entry.parent as u32));
        }

        // First child (tag 22)
        if has_first_child {
            tag_data.extend(encint(entry.first_child as u32));
        }

        // Last child (tag 23)
        if has_last_child {
            tag_data.extend(encint(entry.last_child as u32));
        }

        let name = format!("{i:04}");
        builder.add_entry(name, tag_data);
    }

    (builder.build(), cncx)
}

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

    #[test]
    fn test_decint() {
        // Single byte (high bit set = end)
        assert_eq!(decint(&[0x85]), (5, 1));
        // Two bytes: 0x01 (continue) 0x80 (end, value 0) = 128
        assert_eq!(decint(&[0x01, 0x80]), (128, 2));
        // Value 127
        assert_eq!(decint(&[0xFF]), (127, 1));
    }

    #[test]
    fn test_count_set_bits() {
        assert_eq!(count_set_bits(0), 0);
        assert_eq!(count_set_bits(1), 1);
        assert_eq!(count_set_bits(0b1010), 2);
        assert_eq!(count_set_bits(0xFF), 8);
    }

    #[test]
    fn test_encint() {
        // 0 encodes to 0x80
        assert_eq!(encint(0), vec![0x80]);
        // 1 encodes to 0x81
        assert_eq!(encint(1), vec![0x81]);
        // 127 encodes to 0xFF
        assert_eq!(encint(127), vec![0xFF]);
        // 128 encodes to 0x01, 0x80
        assert_eq!(encint(128), vec![0x01, 0x80]);
        // 255 encodes to 0x01, 0xFF
        assert_eq!(encint(255), vec![0x01, 0xFF]);
    }

    #[test]
    fn test_cncx_roundtrip() {
        let labels = vec![
            "Chapter 1".to_string(),
            "Chapter 2".to_string(),
            "Simple Text".to_string(),
        ];

        let cncx_bytes = build_cncx(&labels);
        let offsets = calculate_cncx_offsets(&labels);

        let parsed = Cncx::parse(&[cncx_bytes], "utf-8");

        for (i, label) in labels.iter().enumerate() {
            let offset = offsets[i];
            let retrieved = parsed.get(offset);
            assert_eq!(
                retrieved,
                Some(label),
                "Label '{}' at offset {} not found correctly",
                label,
                offset
            );
        }
    }

    #[test]
    fn test_ncx_index_roundtrip() {
        let entries = vec![
            NcxBuildEntry {
                pos: 0,
                length: 1000,
                label: "Chapter 1".to_string(),
                depth: 0,
                parent: -1,
                first_child: -1,
                last_child: -1,
            },
            NcxBuildEntry {
                pos: 1000,
                length: 500,
                label: "Chapter 2".to_string(),
                depth: 0,
                parent: -1,
                first_child: -1,
                last_child: -1,
            },
        ];

        let (ncx_records, ncx_cncx) = build_ncx_indx(&entries);

        // Should have 2 records: header + data
        assert_eq!(ncx_records.len(), 2, "Should have header + data record");

        // Parse the header
        let header = IndxHeader::parse(&ncx_records[0]).expect("Failed to parse header");

        // Find TAGX in header record
        let tagx_start = header.tagx_offset as usize;
        let (control_byte_count, tagx) =
            parse_tagx(&ncx_records[0][tagx_start..]).expect("Failed to parse TAGX");

        // Parse CNCX
        let cncx = Cncx::parse(&[ncx_cncx], "utf-8");

        // Parse the data record
        let data_record = &ncx_records[1];
        let data_header = IndxHeader::parse(data_record).expect("Failed to parse data header");

        // Find IDXT
        let idxt_pos = data_header.idxt_start as usize;
        assert_eq!(
            &data_record[idxt_pos..idxt_pos + 4],
            b"IDXT",
            "IDXT not found"
        );

        // Read entry positions
        let mut positions: Vec<usize> = Vec::new();
        for j in 0..data_header.entry_count as usize {
            let off = idxt_pos + 4 + j * 2;
            let pos = u16::from_be_bytes([data_record[off], data_record[off + 1]]) as usize;
            positions.push(pos);
        }
        positions.push(idxt_pos);

        // Parse each entry
        let mut index_entries = Vec::new();
        for j in 0..positions.len().saturating_sub(1) {
            let start = positions[j];
            let end = positions[j + 1];
            let entry_data = &data_record[start..end];

            let (name, consumed) = decode_string(entry_data, "utf-8");
            let tag_data = &entry_data[consumed..];
            let tags = get_tag_map(control_byte_count, &tagx, tag_data);

            index_entries.push(IndexEntry { name, tags });
        }

        // Parse as NCX entries
        let ncx_entries = parse_ncx_index(&index_entries, &cncx);

        assert_eq!(ncx_entries.len(), 2, "Should have 2 NCX entries");
        assert_eq!(ncx_entries[0].text, "Chapter 1", "First label should match");
        assert_eq!(
            ncx_entries[1].text, "Chapter 2",
            "Second label should match"
        );
    }

    #[test]
    fn test_skel_index_roundtrip() {
        use crate::mobi::skeleton::SkelEntry;

        let entries = vec![
            SkelEntry {
                file_number: 0,
                name: "SKEL0000000000".to_string(),
                chunk_count: 1,
                start_pos: 0,
                length: 1000,
            },
            SkelEntry {
                file_number: 1,
                name: "SKEL0000000001".to_string(),
                chunk_count: 2,
                start_pos: 1000,
                length: 2500,
            },
            SkelEntry {
                file_number: 2,
                name: "SKEL0000000002".to_string(),
                chunk_count: 1,
                start_pos: 3500,
                length: 500,
            },
        ];

        let skel_records = build_skel_indx(&entries);

        // Should have 2 records: header + data
        assert_eq!(skel_records.len(), 2, "Should have header + data record");

        // Parse the header
        let header = IndxHeader::parse(&skel_records[0]).expect("Failed to parse header");

        // Find TAGX in header record
        let tagx_start = header.tagx_offset as usize;
        let (control_byte_count, tagx) =
            parse_tagx(&skel_records[0][tagx_start..]).expect("Failed to parse TAGX");

        // Parse the data record
        let data_record = &skel_records[1];
        let data_header = IndxHeader::parse(data_record).expect("Failed to parse data header");

        // Find IDXT
        let idxt_pos = data_header.idxt_start as usize;
        assert_eq!(
            &data_record[idxt_pos..idxt_pos + 4],
            b"IDXT",
            "IDXT not found"
        );

        // Read entry positions
        let mut positions: Vec<usize> = Vec::new();
        for j in 0..data_header.entry_count as usize {
            let off = idxt_pos + 4 + j * 2;
            let pos = u16::from_be_bytes([data_record[off], data_record[off + 1]]) as usize;
            positions.push(pos);
        }
        positions.push(idxt_pos);

        // Parse each entry
        let mut index_entries = Vec::new();
        for j in 0..positions.len().saturating_sub(1) {
            let start = positions[j];
            let end = positions[j + 1];
            let entry_data = &data_record[start..end];

            let (name, consumed) = decode_string(entry_data, "utf-8");
            let tag_data = &entry_data[consumed..];
            let tags = get_tag_map(control_byte_count, &tagx, tag_data);

            index_entries.push(IndexEntry { name, tags });
        }

        // Parse as skeleton files
        let skel_files = parse_skel_index(&index_entries);

        assert_eq!(skel_files.len(), 3, "Should have 3 skeleton files");

        // Verify first entry
        assert_eq!(skel_files[0].file_number, 0);
        assert_eq!(skel_files[0].start_pos, 0);
        assert_eq!(skel_files[0].length, 1000);

        // Verify second entry
        assert_eq!(skel_files[1].file_number, 1);
        assert_eq!(skel_files[1].start_pos, 1000);
        assert_eq!(skel_files[1].length, 2500);

        // Verify third entry
        assert_eq!(skel_files[2].file_number, 2);
        assert_eq!(skel_files[2].start_pos, 3500);
        assert_eq!(skel_files[2].length, 500);
    }
}