oxidize-pdf 2.5.1

A pure Rust PDF generation and manipulation library with zero external dependencies
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
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
//! PDF Document wrapper - High-level interface for PDF parsing and manipulation
//!
//! This module provides a robust, high-level interface for working with PDF documents.
//! It solves Rust's borrow checker challenges through careful use of interior mutability
//! (RefCell) and separation of concerns between parsing, caching, and page access.
//!
//! # Architecture
//!
//! The module uses a layered architecture:
//! - **PdfDocument**: Main entry point with RefCell-based state management
//! - **ResourceManager**: Centralized object caching with interior mutability
//! - **PdfReader**: Low-level file access (wrapped in RefCell)
//! - **PageTree**: Lazy-loaded page navigation
//!
//! # Key Features
//!
//! - **Automatic caching**: Objects are cached after first access
//! - **Resource management**: Shared resources are handled efficiently
//! - **Page navigation**: Fast access to any page in the document
//! - **Reference resolution**: Automatic resolution of indirect references
//! - **Text extraction**: Built-in support for extracting text from pages
//!
//! # Example
//!
//! ```rust,no_run
//! use oxidize_pdf::parser::{PdfDocument, PdfReader};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Open a PDF document
//! let reader = PdfReader::open("document.pdf")?;
//! let document = PdfDocument::new(reader);
//!
//! // Get document information
//! let page_count = document.page_count()?;
//! let metadata = document.metadata()?;
//! println!("Title: {:?}", metadata.title);
//! println!("Pages: {}", page_count);
//!
//! // Access a specific page
//! let page = document.get_page(0)?;
//! println!("Page size: {}x{}", page.width(), page.height());
//!
//! // Extract text from all pages
//! let extracted_text = document.extract_text()?;
//! for (i, page_text) in extracted_text.iter().enumerate() {
//!     println!("Page {}: {}", i + 1, page_text.text);
//! }
//! # Ok(())
//! # }
//! ```

#[cfg(test)]
use super::objects::{PdfArray, PdfName};
use super::objects::{PdfDictionary, PdfObject};
use super::page_tree::{PageTree, ParsedPage};
use super::reader::PdfReader;
use super::{ParseError, ParseOptions, ParseResult};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Seek};
use std::path::Path;
use std::rc::Rc;

/// Resource manager for efficient PDF object caching.
///
/// The ResourceManager provides centralized caching of PDF objects to avoid
/// repeated parsing and to share resources between different parts of the document.
/// It uses RefCell for interior mutability, allowing multiple immutable references
/// to the document while still being able to update the cache.
///
/// # Caching Strategy
///
/// - Objects are cached on first access
/// - Cache persists for the lifetime of the document
/// - Manual cache clearing is supported for memory management
///
/// # Example
///
/// ```rust,no_run
/// use oxidize_pdf::parser::document::ResourceManager;
///
/// let resources = ResourceManager::new();
///
/// // Objects are cached automatically when accessed through PdfDocument
/// // Manual cache management:
/// resources.clear_cache(); // Free memory when needed
/// ```
pub struct ResourceManager {
    /// Cached objects indexed by (object_number, generation_number)
    object_cache: RefCell<HashMap<(u32, u16), PdfObject>>,
}

impl Default for ResourceManager {
    fn default() -> Self {
        Self::new()
    }
}

impl ResourceManager {
    /// Create a new resource manager
    pub fn new() -> Self {
        Self {
            object_cache: RefCell::new(HashMap::new()),
        }
    }

    /// Get an object from cache if available.
    ///
    /// # Arguments
    ///
    /// * `obj_ref` - Object reference (object_number, generation_number)
    ///
    /// # Returns
    ///
    /// Cloned object if cached, None otherwise.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::document::ResourceManager;
    /// # let resources = ResourceManager::new();
    /// if let Some(obj) = resources.get_cached((10, 0)) {
    ///     println!("Object 10 0 R found in cache");
    /// }
    /// ```
    pub fn get_cached(&self, obj_ref: (u32, u16)) -> Option<PdfObject> {
        self.object_cache.borrow().get(&obj_ref).cloned()
    }

    /// Cache an object for future access.
    ///
    /// # Arguments
    ///
    /// * `obj_ref` - Object reference (object_number, generation_number)
    /// * `obj` - The PDF object to cache
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::document::ResourceManager;
    /// # use oxidize_pdf::parser::objects::PdfObject;
    /// # let resources = ResourceManager::new();
    /// resources.cache_object((10, 0), PdfObject::Integer(42));
    /// ```
    pub fn cache_object(&self, obj_ref: (u32, u16), obj: PdfObject) {
        self.object_cache.borrow_mut().insert(obj_ref, obj);
    }

    /// Clear all cached objects to free memory.
    ///
    /// Use this when processing large documents to manage memory usage.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::document::ResourceManager;
    /// # let resources = ResourceManager::new();
    /// // After processing many pages
    /// resources.clear_cache();
    /// println!("Cache cleared to free memory");
    /// ```
    pub fn clear_cache(&self) {
        self.object_cache.borrow_mut().clear();
    }
}

/// High-level PDF document interface for parsing and manipulation.
///
/// `PdfDocument` provides a clean, safe API for working with PDF files.
/// It handles the complexity of PDF structure, object references, and resource
/// management behind a simple interface.
///
/// # Type Parameter
///
/// * `R` - The reader type (must implement Read + Seek)
///
/// # Architecture Benefits
///
/// - **RefCell Usage**: Allows multiple parts of the API to access the document
/// - **Lazy Loading**: Pages and resources are loaded on demand
/// - **Automatic Caching**: Frequently accessed objects are cached
/// - **Safe API**: Borrow checker issues are handled internally
///
/// # Example
///
/// ```rust,no_run
/// use oxidize_pdf::parser::{PdfDocument, PdfReader};
/// use std::fs::File;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // From a file
/// let reader = PdfReader::open("document.pdf")?;
/// let document = PdfDocument::new(reader);
///
/// // From any Read + Seek source
/// let file = File::open("document.pdf")?;
/// let reader = PdfReader::new(file)?;
/// let document = PdfDocument::new(reader);
///
/// // Use the document
/// let page_count = document.page_count()?;
/// for i in 0..page_count {
///     let page = document.get_page(i)?;
///     // Process page...
/// }
/// # Ok(())
/// # }
/// ```
pub struct PdfDocument<R: Read + Seek> {
    /// The underlying PDF reader wrapped for interior mutability
    reader: RefCell<PdfReader<R>>,
    /// Page tree navigator (lazily initialized)
    page_tree: RefCell<Option<PageTree>>,
    /// Shared resource manager for object caching
    resources: Rc<ResourceManager>,
    /// Cached document metadata to avoid repeated parsing
    metadata_cache: RefCell<Option<super::reader::DocumentMetadata>>,
}

impl<R: Read + Seek> PdfDocument<R> {
    /// Create a new PDF document from a reader
    pub fn new(reader: PdfReader<R>) -> Self {
        Self {
            reader: RefCell::new(reader),
            page_tree: RefCell::new(None),
            resources: Rc::new(ResourceManager::new()),
            metadata_cache: RefCell::new(None),
        }
    }

    /// Get the PDF version of the document.
    ///
    /// # Returns
    ///
    /// PDF version string (e.g., "1.4", "1.7", "2.0")
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// let version = document.version()?;
    /// println!("PDF version: {}", version);
    /// # Ok(())
    /// # }
    /// ```
    pub fn version(&self) -> ParseResult<String> {
        Ok(self.reader.borrow().version().to_string())
    }

    /// Get the parse options
    pub fn options(&self) -> ParseOptions {
        self.reader.borrow().options().clone()
    }

    /// Get the total number of pages in the document.
    ///
    /// # Returns
    ///
    /// The page count as an unsigned 32-bit integer.
    ///
    /// # Errors
    ///
    /// Returns an error if the page tree is malformed or missing.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// let count = document.page_count()?;
    /// println!("Document has {} pages", count);
    ///
    /// // Iterate through all pages
    /// for i in 0..count {
    ///     let page = document.get_page(i)?;
    ///     // Process page...
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn page_count(&self) -> ParseResult<u32> {
        self.ensure_page_tree()?;
        if let Some(pt) = self.page_tree.borrow().as_ref() {
            Ok(pt.page_count())
        } else {
            // Fallback: should never reach here since ensure_page_tree() just ran
            self.reader.borrow_mut().page_count()
        }
    }

    /// Get document metadata including title, author, creation date, etc.
    ///
    /// Metadata is cached after first access for performance.
    ///
    /// # Returns
    ///
    /// A `DocumentMetadata` struct containing all available metadata fields.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// let metadata = document.metadata()?;
    ///
    /// if let Some(title) = &metadata.title {
    ///     println!("Title: {}", title);
    /// }
    /// if let Some(author) = &metadata.author {
    ///     println!("Author: {}", author);
    /// }
    /// if let Some(creation_date) = &metadata.creation_date {
    ///     println!("Created: {}", creation_date);
    /// }
    /// println!("PDF Version: {}", metadata.version);
    /// # Ok(())
    /// # }
    /// ```
    pub fn metadata(&self) -> ParseResult<super::reader::DocumentMetadata> {
        // Check cache first
        if let Some(metadata) = self.metadata_cache.borrow().as_ref() {
            return Ok(metadata.clone());
        }

        // Load metadata
        let metadata = self.reader.borrow_mut().metadata()?;
        self.metadata_cache.borrow_mut().replace(metadata.clone());
        Ok(metadata)
    }

    /// Initialize the page tree if not already done.
    ///
    /// Builds a flat index of all leaf Page references by walking the tree once.
    /// This provides O(1) page access and detects cycles and absurd /Count values.
    fn ensure_page_tree(&self) -> ParseResult<()> {
        if self.page_tree.borrow().is_none() {
            let pages_dict = self.load_pages_dict()?;
            let page_refs = {
                let mut reader = self.reader.borrow_mut();
                PageTree::flatten_page_tree(&mut *reader, &pages_dict)?
            };
            let page_tree = PageTree::new_with_flat_index(pages_dict, page_refs);
            self.page_tree.borrow_mut().replace(page_tree);
        }
        Ok(())
    }

    /// Load the pages dictionary
    fn load_pages_dict(&self) -> ParseResult<PdfDictionary> {
        let mut reader = self.reader.borrow_mut();
        let pages = reader.pages()?;
        Ok(pages.clone())
    }

    /// Get a page by index (0-based).
    ///
    /// Pages are cached after first access. This method handles page tree
    /// traversal and property inheritance automatically.
    ///
    /// # Arguments
    ///
    /// * `index` - Zero-based page index (0 to page_count-1)
    ///
    /// # Returns
    ///
    /// A complete `ParsedPage` with all properties and inherited resources.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Index is out of bounds
    /// - Page tree is malformed
    /// - Required page properties are missing
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// // Get the first page
    /// let page = document.get_page(0)?;
    ///
    /// // Access page properties
    /// println!("Page size: {}x{} points", page.width(), page.height());
    /// println!("Rotation: {}°", page.rotation);
    ///
    /// // Get content streams
    /// let streams = page.content_streams_with_document(&document)?;
    /// println!("Page has {} content streams", streams.len());
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_page(&self, index: u32) -> ParseResult<ParsedPage> {
        self.ensure_page_tree()?;

        // First check if page is already cached
        if let Some(page_tree) = self.page_tree.borrow().as_ref() {
            if let Some(page) = page_tree.get_cached_page(index) {
                return Ok(page.clone());
            }
        }

        // Try flat index O(1) lookup first
        let (page_ref, has_flat_index) = {
            let pt_borrow = self.page_tree.borrow();
            let pt = pt_borrow.as_ref();
            let ref_val = pt.and_then(|pt| pt.get_page_ref(index));
            let has_index = pt.map_or(false, |pt| pt.page_count() > 0 || ref_val.is_some());
            (ref_val, has_index)
        };

        let page = if let Some(page_ref) = page_ref {
            self.load_page_by_ref(page_ref)?
        } else if has_flat_index {
            // Flat index exists but page not found — index is out of range
            return Err(ParseError::SyntaxError {
                position: 0,
                message: format!(
                    "Page index {} out of range (document has {} pages)",
                    index,
                    self.page_tree
                        .borrow()
                        .as_ref()
                        .map_or(0, |pt| pt.page_count())
                ),
            });
        } else {
            // No flat index available — fallback to tree traversal
            self.load_page_at_index(index)?
        };

        // Cache it
        if let Some(page_tree) = self.page_tree.borrow_mut().as_mut() {
            page_tree.cache_page(index, page.clone());
        }

        Ok(page)
    }

    /// Load a specific page by index (legacy tree traversal fallback)
    fn load_page_at_index(&self, index: u32) -> ParseResult<ParsedPage> {
        // Get the pages root
        let pages_dict = self.load_pages_dict()?;

        // Navigate to the specific page
        let page_info = self.find_page_in_tree(&pages_dict, index, 0, None)?;

        Ok(page_info)
    }

    /// Load a page directly by its object reference (O(1) via flat index).
    fn load_page_by_ref(&self, page_ref: (u32, u16)) -> ParseResult<ParsedPage> {
        let obj = self.get_object(page_ref.0, page_ref.1)?;
        let dict = obj.as_dict().ok_or_else(|| ParseError::SyntaxError {
            position: 0,
            message: format!(
                "Page object {} {} R is not a dictionary",
                page_ref.0, page_ref.1
            ),
        })?;

        let inherited = self.collect_inherited_attributes(dict);
        self.create_parsed_page(page_ref, dict, Some(&inherited))
    }

    /// Walk up the /Parent chain to collect inheritable attributes (Resources, MediaBox, CropBox, Rotate).
    /// Uses cycle detection to prevent infinite loops in malformed PDFs.
    fn collect_inherited_attributes(&self, page_dict: &PdfDictionary) -> PdfDictionary {
        let mut inherited = PdfDictionary::new();
        let inheritable_keys = ["Resources", "MediaBox", "CropBox", "Rotate"];

        // Collect from the page's own parent chain
        let mut current_parent_ref = page_dict.get("Parent").and_then(|p| p.as_reference());
        let mut visited: std::collections::HashSet<(u32, u16)> = std::collections::HashSet::new();

        while let Some(parent_ref) = current_parent_ref {
            if !visited.insert(parent_ref) {
                break; // Cycle detected
            }

            match self.get_object(parent_ref.0, parent_ref.1) {
                Ok(obj) => {
                    if let Some(parent_dict) = obj.as_dict() {
                        for key in &inheritable_keys {
                            // Only inherit if the page itself doesn't have it
                            // and we haven't already found it in a closer ancestor
                            if !page_dict.contains_key(key) && !inherited.contains_key(key) {
                                if let Some(val) = parent_dict.get(key) {
                                    inherited.insert((*key).to_string(), val.clone());
                                }
                            }
                        }
                        current_parent_ref =
                            parent_dict.get("Parent").and_then(|p| p.as_reference());
                    } else {
                        break;
                    }
                }
                Err(_) => break,
            }
        }

        inherited
    }

    /// Find a page in the page tree (iterative implementation for stack safety)
    fn find_page_in_tree(
        &self,
        root_node: &PdfDictionary,
        target_index: u32,
        initial_current_index: u32,
        initial_inherited: Option<&PdfDictionary>,
    ) -> ParseResult<ParsedPage> {
        // Work item for the traversal queue
        #[derive(Debug)]
        struct WorkItem {
            node_dict: PdfDictionary,
            node_ref: Option<(u32, u16)>,
            current_index: u32,
            inherited: Option<PdfDictionary>,
        }

        // Initialize work queue with root node
        let mut work_queue = Vec::new();
        work_queue.push(WorkItem {
            node_dict: root_node.clone(),
            node_ref: None,
            current_index: initial_current_index,
            inherited: initial_inherited.cloned(),
        });

        // Iterative traversal
        while let Some(work_item) = work_queue.pop() {
            let WorkItem {
                node_dict,
                node_ref,
                current_index,
                inherited,
            } = work_item;

            let node_type = node_dict
                .get_type()
                .or_else(|| {
                    // If Type is missing, try to infer from content
                    if node_dict.contains_key("Kids") && node_dict.contains_key("Count") {
                        Some("Pages")
                    } else if node_dict.contains_key("Contents")
                        || node_dict.contains_key("MediaBox")
                    {
                        Some("Page")
                    } else {
                        None
                    }
                })
                .or_else(|| {
                    // If Type is missing, try to infer from structure
                    if node_dict.contains_key("Kids") {
                        Some("Pages")
                    } else if node_dict.contains_key("Contents")
                        || (node_dict.contains_key("MediaBox") && !node_dict.contains_key("Kids"))
                    {
                        Some("Page")
                    } else {
                        None
                    }
                })
                .ok_or_else(|| ParseError::MissingKey("Type".to_string()))?;

            match node_type {
                "Pages" => {
                    // This is a page tree node
                    let kids = node_dict
                        .get("Kids")
                        .and_then(|obj| obj.as_array())
                        .or_else(|| {
                            // If Kids is missing, use empty array
                            tracing::debug!(
                                "Warning: Missing Kids array in Pages node, using empty array"
                            );
                            Some(&super::objects::EMPTY_PDF_ARRAY)
                        })
                        .ok_or_else(|| ParseError::MissingKey("Kids".to_string()))?;

                    // Merge inherited attributes
                    let mut merged_inherited = inherited.unwrap_or_else(PdfDictionary::new);

                    // Inheritable attributes
                    for key in ["Resources", "MediaBox", "CropBox", "Rotate"] {
                        if let Some(value) = node_dict.get(key) {
                            if !merged_inherited.contains_key(key) {
                                merged_inherited.insert(key.to_string(), value.clone());
                            }
                        }
                    }

                    // Process kids in reverse order (since we're using a stack/Vec::pop())
                    // This ensures we process them in the correct order
                    let mut current_idx = current_index;
                    let mut pending_kids = Vec::new();

                    for kid_ref in &kids.0 {
                        let kid_ref =
                            kid_ref
                                .as_reference()
                                .ok_or_else(|| ParseError::SyntaxError {
                                    position: 0,
                                    message: "Kids array must contain references".to_string(),
                                })?;

                        // Get the kid object
                        let kid_obj = self.get_object(kid_ref.0, kid_ref.1)?;
                        let kid_dict = match kid_obj.as_dict() {
                            Some(dict) => dict,
                            None => {
                                // Skip invalid page tree nodes in lenient mode
                                tracing::debug!(
                                    "Warning: Page tree node {} {} R is not a dictionary, skipping",
                                    kid_ref.0,
                                    kid_ref.1
                                );
                                current_idx += 1; // Count as processed but skip
                                continue;
                            }
                        };

                        let kid_type = kid_dict
                            .get_type()
                            .or_else(|| {
                                // If Type is missing, try to infer from content
                                if kid_dict.contains_key("Kids") && kid_dict.contains_key("Count") {
                                    Some("Pages")
                                } else if kid_dict.contains_key("Contents")
                                    || kid_dict.contains_key("MediaBox")
                                {
                                    Some("Page")
                                } else {
                                    None
                                }
                            })
                            .ok_or_else(|| ParseError::MissingKey("Type".to_string()))?;

                        let count = if kid_type == "Pages" {
                            kid_dict
                                .get("Count")
                                .and_then(|obj| obj.as_integer())
                                .unwrap_or(1) // Fallback to 1 if Count is missing (defensive)
                                as u32
                        } else {
                            1
                        };

                        if target_index < current_idx + count {
                            // Found the right subtree/page
                            if kid_type == "Page" {
                                // This is the page we want
                                return self.create_parsed_page(
                                    kid_ref,
                                    kid_dict,
                                    Some(&merged_inherited),
                                );
                            } else {
                                // Need to traverse this subtree - add to queue
                                pending_kids.push(WorkItem {
                                    node_dict: kid_dict.clone(),
                                    node_ref: Some(kid_ref),
                                    current_index: current_idx,
                                    inherited: Some(merged_inherited.clone()),
                                });
                                break; // Found our target subtree, no need to continue
                            }
                        }

                        current_idx += count;
                    }

                    // Add pending kids to work queue in reverse order for correct processing
                    work_queue.extend(pending_kids.into_iter().rev());
                }
                "Page" => {
                    // This is a page object
                    if target_index != current_index {
                        return Err(ParseError::SyntaxError {
                            position: 0,
                            message: "Page index mismatch".to_string(),
                        });
                    }

                    // We need the reference for creating the parsed page
                    if let Some(page_ref) = node_ref {
                        return self.create_parsed_page(page_ref, &node_dict, inherited.as_ref());
                    } else {
                        return Err(ParseError::SyntaxError {
                            position: 0,
                            message: "Direct page object without reference".to_string(),
                        });
                    }
                }
                _ => {
                    return Err(ParseError::SyntaxError {
                        position: 0,
                        message: format!("Invalid page tree node type: {node_type}"),
                    });
                }
            }
        }

        // Try fallback: search for the page by direct object scanning
        tracing::debug!(
            "Warning: Page {} not found in tree, attempting direct lookup",
            target_index
        );

        // Scan for Page objects directly (try first few hundred objects)
        for obj_num in 1..500 {
            if let Ok(obj) = self.reader.borrow_mut().get_object(obj_num, 0) {
                if let Some(dict) = obj.as_dict() {
                    if let Some(obj_type) = dict.get("Type").and_then(|t| t.as_name()) {
                        if obj_type.0 == "Page" {
                            // Found a page, check if it's the right index (approximate)
                            return self.create_parsed_page((obj_num, 0), dict, None);
                        }
                    }
                }
            }
        }

        Err(ParseError::SyntaxError {
            position: 0,
            message: format!("Page {} not found in tree or document", target_index),
        })
    }

    /// Create a ParsedPage from a page dictionary
    fn create_parsed_page(
        &self,
        obj_ref: (u32, u16),
        page_dict: &PdfDictionary,
        inherited: Option<&PdfDictionary>,
    ) -> ParseResult<ParsedPage> {
        // Extract page attributes with fallback for missing MediaBox
        let media_box = match self.get_rectangle(page_dict, inherited, "MediaBox")? {
            Some(mb) => mb,
            None => {
                // Use default Letter size if MediaBox is missing
                #[cfg(debug_assertions)]
                tracing::debug!(
                    "Warning: Page {} {} R missing MediaBox, using default Letter size",
                    obj_ref.0,
                    obj_ref.1
                );
                [0.0, 0.0, 612.0, 792.0]
            }
        };

        let crop_box = self.get_rectangle(page_dict, inherited, "CropBox")?;

        let rotation = self
            .get_integer(page_dict, inherited, "Rotate")?
            .unwrap_or(0) as i32;

        // Get inherited resources
        let inherited_resources = if let Some(inherited) = inherited {
            inherited
                .get("Resources")
                .and_then(|r| r.as_dict())
                .cloned()
        } else {
            None
        };

        // Get annotations if present
        let annotations = page_dict
            .get("Annots")
            .and_then(|obj| obj.as_array())
            .cloned();

        Ok(ParsedPage {
            obj_ref,
            dict: page_dict.clone(),
            inherited_resources,
            media_box,
            crop_box,
            rotation,
            annotations,
        })
    }

    /// Get a rectangle value
    fn get_rectangle(
        &self,
        node: &PdfDictionary,
        inherited: Option<&PdfDictionary>,
        key: &str,
    ) -> ParseResult<Option<[f64; 4]>> {
        let array = node.get(key).or_else(|| inherited.and_then(|i| i.get(key)));

        if let Some(array) = array.and_then(|obj| obj.as_array()) {
            if array.len() != 4 {
                return Err(ParseError::SyntaxError {
                    position: 0,
                    message: format!("{key} must have 4 elements"),
                });
            }

            // After length check, we know array has exactly 4 elements
            // Safe to index directly without unwrap
            let rect = [
                array.0[0].as_real().unwrap_or(0.0),
                array.0[1].as_real().unwrap_or(0.0),
                array.0[2].as_real().unwrap_or(0.0),
                array.0[3].as_real().unwrap_or(0.0),
            ];

            Ok(Some(rect))
        } else {
            Ok(None)
        }
    }

    /// Get an integer value
    fn get_integer(
        &self,
        node: &PdfDictionary,
        inherited: Option<&PdfDictionary>,
        key: &str,
    ) -> ParseResult<Option<i64>> {
        let value = node.get(key).or_else(|| inherited.and_then(|i| i.get(key)));

        Ok(value.and_then(|obj| obj.as_integer()))
    }

    /// Get an object by its reference numbers.
    ///
    /// This method first checks the cache, then loads from the file if needed.
    /// Objects are automatically cached after loading.
    ///
    /// # Arguments
    ///
    /// * `obj_num` - Object number
    /// * `gen_num` - Generation number
    ///
    /// # Returns
    ///
    /// The resolved PDF object.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Object doesn't exist
    /// - Object is part of an encrypted object stream
    /// - File is corrupted
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # use oxidize_pdf::parser::objects::PdfObject;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// // Get object 10 0 R
    /// let obj = document.get_object(10, 0)?;
    ///
    /// // Check object type
    /// match obj {
    ///     PdfObject::Dictionary(dict) => {
    ///         println!("Object is a dictionary with {} entries", dict.0.len());
    ///     }
    ///     PdfObject::Stream(stream) => {
    ///         println!("Object is a stream");
    ///     }
    ///     _ => {}
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_object(&self, obj_num: u32, gen_num: u16) -> ParseResult<PdfObject> {
        // Check resource cache first
        if let Some(obj) = self.resources.get_cached((obj_num, gen_num)) {
            return Ok(obj);
        }

        // Load from reader
        let obj = {
            let mut reader = self.reader.borrow_mut();
            reader.get_object(obj_num, gen_num)?.clone()
        };

        // Cache it
        self.resources.cache_object((obj_num, gen_num), obj.clone());

        Ok(obj)
    }

    /// Resolve a reference to get the actual object.
    ///
    /// If the input is a Reference, fetches the referenced object.
    /// Otherwise returns a clone of the input object.
    ///
    /// # Arguments
    ///
    /// * `obj` - The object to resolve (may be a Reference or direct object)
    ///
    /// # Returns
    ///
    /// The resolved object (never a Reference).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # use oxidize_pdf::parser::objects::PdfObject;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// # let page = document.get_page(0)?;
    /// // Contents might be a reference or direct object
    /// if let Some(contents) = page.dict.get("Contents") {
    ///     let resolved = document.resolve(contents)?;
    ///     match resolved {
    ///         PdfObject::Stream(_) => println!("Single content stream"),
    ///         PdfObject::Array(_) => println!("Multiple content streams"),
    ///         _ => println!("Unexpected content type"),
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn resolve(&self, obj: &PdfObject) -> ParseResult<PdfObject> {
        match obj {
            PdfObject::Reference(obj_num, gen_num) => self.get_object(*obj_num, *gen_num),
            _ => Ok(obj.clone()),
        }
    }

    /// Get content streams for a specific page.
    ///
    /// This method handles both single streams and arrays of streams,
    /// automatically decompressing them according to their filters.
    ///
    /// # Arguments
    ///
    /// * `page` - The page to get content streams from
    ///
    /// # Returns
    ///
    /// Vector of decompressed content stream data ready for parsing.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # use oxidize_pdf::parser::content::ContentParser;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// let page = document.get_page(0)?;
    /// let streams = document.get_page_content_streams(&page)?;
    ///
    /// // Parse content streams
    /// for stream_data in streams {
    ///     let operations = ContentParser::parse(&stream_data)?;
    ///     println!("Stream has {} operations", operations.len());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    /// Get page resources dictionary.
    ///
    /// This method returns the resources dictionary for a page, which may include
    /// fonts, images (XObjects), patterns, color spaces, and other resources.
    ///
    /// # Arguments
    ///
    /// * `page` - The page to get resources from
    ///
    /// # Returns
    ///
    /// Optional resources dictionary if the page has resources.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader, PdfObject, PdfName};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// let page = document.get_page(0)?;
    /// if let Some(resources) = document.get_page_resources(&page)? {
    ///     // Check for images (XObjects)
    ///     if let Some(PdfObject::Dictionary(xobjects)) = resources.0.get(&PdfName("XObject".to_string())) {
    ///         for (name, _) in xobjects.0.iter() {
    ///             println!("Found XObject: {}", name.0);
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_page_resources<'a>(
        &self,
        page: &'a ParsedPage,
    ) -> ParseResult<Option<&'a PdfDictionary>> {
        Ok(page.get_resources())
    }

    pub fn get_page_content_streams(&self, page: &ParsedPage) -> ParseResult<Vec<Vec<u8>>> {
        let mut streams = Vec::new();
        let options = self.options();

        if let Some(contents) = page.dict.get("Contents") {
            let resolved_contents = self.resolve(contents)?;

            match &resolved_contents {
                PdfObject::Stream(stream) => {
                    streams.push(stream.decode(&options)?);
                }
                PdfObject::Array(array) => {
                    for item in &array.0 {
                        let resolved = self.resolve(item)?;
                        if let PdfObject::Stream(stream) = resolved {
                            streams.push(stream.decode(&options)?);
                        }
                    }
                }
                _ => {
                    return Err(ParseError::SyntaxError {
                        position: 0,
                        message: "Contents must be a stream or array of streams".to_string(),
                    })
                }
            }
        }

        Ok(streams)
    }

    /// Extract text from all pages in the document.
    ///
    /// Uses the default text extraction settings. For custom settings,
    /// use `extract_text_with_options`.
    ///
    /// # Returns
    ///
    /// A vector of `ExtractedText`, one for each page in the document.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// let extracted_pages = document.extract_text()?;
    ///
    /// for (page_num, page_text) in extracted_pages.iter().enumerate() {
    ///     println!("=== Page {} ===", page_num + 1);
    ///     println!("{}", page_text.text);
    ///     println!();
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn extract_text(&self) -> ParseResult<Vec<crate::text::ExtractedText>> {
        let mut extractor = crate::text::TextExtractor::new();
        extractor.extract_from_document(self)
    }

    /// Extract text from a specific page.
    ///
    /// # Arguments
    ///
    /// * `page_index` - Zero-based page index
    ///
    /// # Returns
    ///
    /// Extracted text with optional position information.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// // Extract text from first page only
    /// let page_text = document.extract_text_from_page(0)?;
    /// println!("First page text: {}", page_text.text);
    ///
    /// // Access text fragments with positions (if preserved)
    /// for fragment in &page_text.fragments {
    ///     println!("'{}' at ({}, {})", fragment.text, fragment.x, fragment.y);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn extract_text_from_page(
        &self,
        page_index: u32,
    ) -> ParseResult<crate::text::ExtractedText> {
        let mut extractor = crate::text::TextExtractor::new();
        extractor.extract_from_page(self, page_index)
    }

    /// Extract text from a specific page with custom options.
    ///
    /// This method combines the functionality of [`extract_text_from_page`] and
    /// [`extract_text_with_options`], allowing fine control over extraction
    /// behavior for a single page.
    ///
    /// # Arguments
    ///
    /// * `page_index` - Zero-based page index
    /// * `options` - Text extraction configuration
    ///
    /// # Returns
    ///
    /// Extracted text with optional position information.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # use oxidize_pdf::text::ExtractionOptions;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// // Use higher space threshold for PDFs with micro-adjustments
    /// let options = ExtractionOptions {
    ///     space_threshold: 0.4,
    ///     ..Default::default()
    /// };
    ///
    /// let page_text = document.extract_text_from_page_with_options(0, options)?;
    /// println!("Text: {}", page_text.text);
    /// # Ok(())
    /// # }
    /// ```
    pub fn extract_text_from_page_with_options(
        &self,
        page_index: u32,
        options: crate::text::ExtractionOptions,
    ) -> ParseResult<crate::text::ExtractedText> {
        let mut extractor = crate::text::TextExtractor::with_options(options);
        extractor.extract_from_page(self, page_index)
    }

    /// Extract text with custom extraction options.
    ///
    /// Allows fine control over text extraction behavior including
    /// layout preservation, spacing thresholds, and more.
    ///
    /// # Arguments
    ///
    /// * `options` - Text extraction configuration
    ///
    /// # Returns
    ///
    /// A vector of `ExtractedText`, one for each page.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # use oxidize_pdf::text::ExtractionOptions;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// // Configure extraction to preserve layout
    /// let options = ExtractionOptions {
    ///     preserve_layout: true,
    ///     space_threshold: 0.3,
    ///     newline_threshold: 10.0,
    ///     ..Default::default()
    /// };
    ///
    /// let extracted_pages = document.extract_text_with_options(options)?;
    ///
    /// // Text fragments will include position information
    /// for page_text in extracted_pages {
    ///     for fragment in &page_text.fragments {
    ///         println!("{:?}", fragment);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn extract_text_with_options(
        &self,
        options: crate::text::ExtractionOptions,
    ) -> ParseResult<Vec<crate::text::ExtractedText>> {
        let mut extractor = crate::text::TextExtractor::with_options(options);
        extractor.extract_from_document(self)
    }

    /// Get annotations from a specific page.
    ///
    /// Returns a vector of annotation dictionaries for the specified page.
    /// Each annotation dictionary contains properties like Type, Rect, Contents, etc.
    ///
    /// # Arguments
    ///
    /// * `page_index` - Zero-based page index
    ///
    /// # Returns
    ///
    /// A vector of PdfDictionary objects representing annotations, or an empty vector
    /// if the page has no annotations.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// let annotations = document.get_page_annotations(0)?;
    /// for annot in &annotations {
    ///     if let Some(contents) = annot.get("Contents").and_then(|c| c.as_string()) {
    ///         println!("Annotation: {:?}", contents);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_page_annotations(&self, page_index: u32) -> ParseResult<Vec<PdfDictionary>> {
        let page = self.get_page(page_index)?;

        if let Some(annots_array) = page.get_annotations() {
            let mut annotations = Vec::new();
            let mut reader = self.reader.borrow_mut();

            for annot_ref in &annots_array.0 {
                if let Some(ref_nums) = annot_ref.as_reference() {
                    match reader.get_object(ref_nums.0, ref_nums.1) {
                        Ok(obj) => {
                            if let Some(dict) = obj.as_dict() {
                                annotations.push(dict.clone());
                            }
                        }
                        Err(_) => {
                            // Skip annotations that can't be loaded
                            continue;
                        }
                    }
                }
            }

            Ok(annotations)
        } else {
            Ok(Vec::new())
        }
    }

    /// Get all annotations from all pages in the document.
    ///
    /// Returns a vector of tuples containing (page_index, annotations) for each page
    /// that has annotations.
    ///
    /// # Returns
    ///
    /// A vector of tuples where the first element is the page index and the second
    /// is a vector of annotation dictionaries for that page.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let reader = PdfReader::open("document.pdf")?;
    /// # let document = PdfDocument::new(reader);
    /// let all_annotations = document.get_all_annotations()?;
    /// for (page_idx, annotations) in all_annotations {
    ///     println!("Page {} has {} annotations", page_idx, annotations.len());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_all_annotations(&self) -> ParseResult<Vec<(u32, Vec<PdfDictionary>)>> {
        let page_count = self.page_count()?;
        let mut all_annotations = Vec::new();

        for i in 0..page_count {
            let annotations = self.get_page_annotations(i)?;
            if !annotations.is_empty() {
                all_annotations.push((i, annotations));
            }
        }

        Ok(all_annotations)
    }

    // --- VibeCoding Facade Methods ---

    /// Export the document to LLM-optimized Markdown format.
    ///
    /// Delegates to [`crate::ai::export_to_markdown`]. Includes YAML frontmatter
    /// with document metadata followed by extracted text content.
    #[allow(deprecated)]
    pub fn to_markdown(&self) -> crate::error::Result<String> {
        crate::ai::export_to_markdown(self)
    }

    /// Export the document to element-aware Markdown format.
    ///
    /// Unlike [`to_markdown`](Self::to_markdown), this method classifies elements
    /// by type and maps each to its canonical Markdown representation.
    pub fn to_element_markdown(&self) -> ParseResult<String> {
        let elements = self.partition()?;
        let exporter = crate::pipeline::export::ElementMarkdownExporter::default();
        Ok(exporter.export(&elements))
    }

    /// Export the document to a contextual text format for LLM consumption.
    ///
    /// Delegates to [`crate::ai::export_to_contextual`].
    #[allow(deprecated)]
    pub fn to_contextual(&self) -> crate::error::Result<String> {
        crate::ai::export_to_contextual(self)
    }

    /// Export the document to structured JSON format.
    ///
    /// Requires the `semantic` feature. Delegates to [`crate::ai::export_to_json`].
    #[cfg(feature = "semantic")]
    #[allow(deprecated)]
    pub fn to_json(&self) -> crate::error::Result<String> {
        crate::ai::export_to_json(self)
    }

    /// Extract and chunk the document into RAG-ready chunks with full metadata.
    ///
    /// Uses default [`HybridChunkConfig`](crate::pipeline::HybridChunkConfig)
    /// (512 tokens, `AnyInlineContent` merge policy). Returns serializable
    /// [`RagChunk`](crate::pipeline::RagChunk)s with page numbers, bounding boxes,
    /// element types, and heading context — everything a vector store needs.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::parser::{PdfDocument, PdfReader};
    ///
    /// let doc = PdfDocument::open("document.pdf")?;
    /// let chunks = doc.rag_chunks()?;
    /// for chunk in &chunks {
    ///     println!("Chunk {}: pages {:?}, ~{} tokens",
    ///         chunk.chunk_index, chunk.page_numbers, chunk.token_estimate);
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn rag_chunks(&self) -> ParseResult<Vec<crate::pipeline::RagChunk>> {
        self.rag_chunks_with(crate::pipeline::HybridChunkConfig::default())
    }

    /// Extract and chunk the document with a custom chunking configuration.
    ///
    /// Use this when the default 512-token limit is too large or too small for your
    /// vector store or embedding model. All other metadata (pages, bounding boxes,
    /// element types, heading context) is identical to [`rag_chunks()`](Self::rag_chunks).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::parser::{PdfDocument, PdfReader};
    /// use oxidize_pdf::pipeline::HybridChunkConfig;
    ///
    /// let doc = PdfDocument::open("document.pdf")?;
    /// let config = HybridChunkConfig {
    ///     max_tokens: 256,
    ///     ..HybridChunkConfig::default()
    /// };
    /// let chunks = doc.rag_chunks_with(config)?;
    /// println!("Got {} chunks at 256-token limit", chunks.len());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn rag_chunks_with(
        &self,
        config: crate::pipeline::HybridChunkConfig,
    ) -> ParseResult<Vec<crate::pipeline::RagChunk>> {
        let elements = self.partition()?;
        let chunker = crate::pipeline::HybridChunker::new(config);
        let hybrid_chunks = chunker.chunk(&elements);
        let rag_chunks = hybrid_chunks
            .iter()
            .enumerate()
            .map(|(idx, hc)| crate::pipeline::RagChunk::from_hybrid_chunk(idx, hc))
            .collect();
        Ok(rag_chunks)
    }

    /// Extract and chunk the document using a pre-configured extraction profile.
    ///
    /// Combines [`partition_with_profile`](Self::partition_with_profile) with
    /// [`HybridChunker`](crate::pipeline::HybridChunker) using default chunking
    /// settings. Use [`rag_chunks_with`](Self::rag_chunks_with) when you need
    /// to tune `max_tokens` or `overlap_tokens`.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::parser::PdfDocument;
    /// use oxidize_pdf::pipeline::ExtractionProfile;
    ///
    /// let doc = PdfDocument::open("document.pdf")?;
    /// let chunks = doc.rag_chunks_with_profile(ExtractionProfile::Rag)?;
    /// println!("Got {} RAG chunks", chunks.len());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn rag_chunks_with_profile(
        &self,
        profile: crate::pipeline::ExtractionProfile,
    ) -> ParseResult<Vec<crate::pipeline::RagChunk>> {
        let elements = self.partition_with_profile(profile)?;
        let chunker = crate::pipeline::HybridChunker::default();
        let hybrid_chunks = chunker.chunk(&elements);
        let rag_chunks = hybrid_chunks
            .iter()
            .enumerate()
            .map(|(idx, hc)| crate::pipeline::RagChunk::from_hybrid_chunk(idx, hc))
            .collect();
        Ok(rag_chunks)
    }

    /// Combine a pre-configured extraction profile with a custom chunking config.
    ///
    /// Use this when you need both profile-tuned partitioning (e.g. `Rag` with
    /// XYCut reading order) and a non-default chunk size.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::parser::PdfDocument;
    /// use oxidize_pdf::pipeline::{ExtractionProfile, HybridChunkConfig};
    ///
    /// let doc = PdfDocument::open("document.pdf")?;
    /// let config = HybridChunkConfig { max_tokens: 256, ..Default::default() };
    /// let chunks = doc.rag_chunks_with_profile_config(ExtractionProfile::Rag, config)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn rag_chunks_with_profile_config(
        &self,
        profile: crate::pipeline::ExtractionProfile,
        config: crate::pipeline::HybridChunkConfig,
    ) -> ParseResult<Vec<crate::pipeline::RagChunk>> {
        let elements = self.partition_with_profile(profile)?;
        let chunker = crate::pipeline::HybridChunker::new(config);
        let hybrid_chunks = chunker.chunk(&elements);
        Ok(hybrid_chunks
            .iter()
            .enumerate()
            .map(|(idx, hc)| crate::pipeline::RagChunk::from_hybrid_chunk(idx, hc))
            .collect())
    }

    /// Extract chunks as a JSON string ready for vector store ingestion.
    ///
    /// # Feature flags
    ///
    /// Requires the `semantic` feature: `oxidize-pdf = { features = ["semantic"] }`.
    /// Without it this method is not compiled.
    #[cfg(feature = "semantic")]
    pub fn rag_chunks_json(&self) -> ParseResult<String> {
        let chunks = self.rag_chunks()?;
        serde_json::to_string(&chunks).map_err(|e| ParseError::SerializationError(e.to_string()))
    }

    /// Split the document text into chunks of approximately `target_tokens` size.
    ///
    /// Uses a default overlap of 10% of the target token count.
    #[deprecated(
        since = "2.2.0",
        note = "Use rag_chunks() for structure-aware RAG chunking"
    )]
    #[allow(deprecated)]
    pub fn chunk(
        &self,
        target_tokens: usize,
    ) -> crate::error::Result<Vec<crate::ai::DocumentChunk>> {
        let overlap = target_tokens / 10;
        self.chunk_with(target_tokens, overlap)
    }

    /// Split the document text into chunks with explicit size and overlap control.
    #[deprecated(
        since = "2.2.0",
        note = "Use rag_chunks_with() for structure-aware RAG chunking"
    )]
    pub fn chunk_with(
        &self,
        target_tokens: usize,
        overlap: usize,
    ) -> crate::error::Result<Vec<crate::ai::DocumentChunk>> {
        let chunker = crate::ai::DocumentChunker::new(target_tokens, overlap);
        let extracted = self.extract_text()?;
        let page_texts: Vec<(usize, String)> = extracted
            .iter()
            .enumerate()
            .map(|(i, t)| (i + 1, t.text.clone()))
            .collect();
        chunker
            .chunk_text_with_pages(&page_texts)
            .map_err(|e| crate::error::PdfError::InvalidStructure(e.to_string()))
    }

    /// Partition the document into typed elements using default configuration.
    ///
    /// Extracts text with layout preservation, then classifies fragments into
    /// [`Element`](crate::pipeline::Element) variants (Title, Paragraph, Table, etc.).
    pub fn partition(&self) -> ParseResult<Vec<crate::pipeline::Element>> {
        self.partition_with(crate::pipeline::PartitionConfig::default())
    }

    /// Partition the document into typed elements with custom configuration.
    pub fn partition_with(
        &self,
        config: crate::pipeline::PartitionConfig,
    ) -> ParseResult<Vec<crate::pipeline::Element>> {
        let options = crate::text::ExtractionOptions {
            preserve_layout: true,
            ..Default::default()
        };
        self.do_partition_pages(options, config)
    }

    /// Partition the document using a pre-configured extraction profile.
    pub fn partition_with_profile(
        &self,
        profile: crate::pipeline::ExtractionProfile,
    ) -> ParseResult<Vec<crate::pipeline::Element>> {
        let profile_cfg = profile.config();
        let options = crate::text::ExtractionOptions {
            preserve_layout: true,
            space_threshold: profile_cfg.extraction.space_threshold,
            detect_columns: profile_cfg.extraction.detect_columns,
            ..crate::text::ExtractionOptions::default()
        };
        self.do_partition_pages(options, profile_cfg.partition)
    }

    fn do_partition_pages(
        &self,
        options: crate::text::ExtractionOptions,
        config: crate::pipeline::PartitionConfig,
    ) -> ParseResult<Vec<crate::pipeline::Element>> {
        let pages = self.extract_text_with_options(options)?;
        let partitioner = crate::pipeline::Partitioner::new(config);

        let mut all_elements = Vec::new();
        for (page_idx, page_text) in pages.iter().enumerate() {
            let page_idx_u32 = u32::try_from(page_idx).map_err(|_| ParseError::SyntaxError {
                position: 0,
                message: format!("Page index {} exceeds u32 range", page_idx),
            })?;
            let page_height = self
                .get_page(page_idx_u32)
                .map(|p| p.height())
                .unwrap_or(842.0);
            let elements =
                partitioner.partition_fragments(&page_text.fragments, page_idx_u32, page_height);
            all_elements.extend(elements);
        }

        Ok(all_elements)
    }

    /// Partition the document into typed elements and build a relationship graph.
    ///
    /// Returns a tuple of `(elements, graph)` where the graph captures parent/child
    /// and next/prev relationships between elements by index.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::parser::PdfDocument;
    /// use oxidize_pdf::pipeline::PartitionConfig;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let doc = PdfDocument::open("document.pdf")?;
    /// let (elements, graph) = doc.partition_graph(PartitionConfig::default())?;
    ///
    /// for title_idx in graph.top_level_sections() {
    ///     println!("Section: {}", elements[title_idx].text());
    ///     for child_idx in graph.elements_in_section(title_idx) {
    ///         println!("  {}", elements[child_idx].text());
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn partition_graph(
        &self,
        config: crate::pipeline::PartitionConfig,
    ) -> ParseResult<(Vec<crate::pipeline::Element>, crate::pipeline::ElementGraph)> {
        let elements = self.partition_with(config)?;
        let graph = crate::pipeline::ElementGraph::build(&elements);
        Ok((elements, graph))
    }
}

impl PdfDocument<File> {
    /// Open a PDF file by path — the simplest way to start working with a PDF.
    ///
    /// This is a convenience method that combines `PdfReader::open()` and
    /// `PdfDocument::new()` into a single call.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use oxidize_pdf::parser::PdfDocument;
    ///
    /// let doc = PdfDocument::open("report.pdf").unwrap();
    /// let text = doc.extract_text().unwrap();
    /// let markdown = doc.to_markdown().unwrap();
    /// ```
    pub fn open<P: AsRef<Path>>(path: P) -> ParseResult<Self> {
        PdfReader::open_document(path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::objects::{PdfObject, PdfString};
    use std::io::Cursor;

    // Helper function to create a minimal PDF in memory
    fn create_minimal_pdf() -> Vec<u8> {
        let mut pdf = Vec::new();

        // PDF header
        pdf.extend_from_slice(b"%PDF-1.4\n");

        // Catalog object
        pdf.extend_from_slice(b"1 0 obj\n");
        pdf.extend_from_slice(b"<< /Type /Catalog /Pages 2 0 R >>\n");
        pdf.extend_from_slice(b"endobj\n");

        // Pages object
        pdf.extend_from_slice(b"2 0 obj\n");
        pdf.extend_from_slice(b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>\n");
        pdf.extend_from_slice(b"endobj\n");

        // Page object
        pdf.extend_from_slice(b"3 0 obj\n");
        pdf.extend_from_slice(
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>\n",
        );
        pdf.extend_from_slice(b"endobj\n");

        // Cross-reference table
        let xref_pos = pdf.len();
        pdf.extend_from_slice(b"xref\n");
        pdf.extend_from_slice(b"0 4\n");
        pdf.extend_from_slice(b"0000000000 65535 f \n");
        pdf.extend_from_slice(b"0000000009 00000 n \n");
        pdf.extend_from_slice(b"0000000058 00000 n \n");
        pdf.extend_from_slice(b"0000000115 00000 n \n");

        // Trailer
        pdf.extend_from_slice(b"trailer\n");
        pdf.extend_from_slice(b"<< /Size 4 /Root 1 0 R >>\n");
        pdf.extend_from_slice(b"startxref\n");
        pdf.extend_from_slice(format!("{xref_pos}\n").as_bytes());
        pdf.extend_from_slice(b"%%EOF\n");

        pdf
    }

    // Helper to create a PDF with metadata
    fn create_pdf_with_metadata() -> Vec<u8> {
        let mut pdf = Vec::new();

        // PDF header
        pdf.extend_from_slice(b"%PDF-1.5\n");

        // Record positions for xref
        let obj1_pos = pdf.len();

        // Catalog object
        pdf.extend_from_slice(b"1 0 obj\n");
        pdf.extend_from_slice(b"<< /Type /Catalog /Pages 2 0 R >>\n");
        pdf.extend_from_slice(b"endobj\n");

        let obj2_pos = pdf.len();

        // Pages object
        pdf.extend_from_slice(b"2 0 obj\n");
        pdf.extend_from_slice(b"<< /Type /Pages /Kids [] /Count 0 >>\n");
        pdf.extend_from_slice(b"endobj\n");

        let obj3_pos = pdf.len();

        // Info object
        pdf.extend_from_slice(b"3 0 obj\n");
        pdf.extend_from_slice(
            b"<< /Title (Test Document) /Author (Test Author) /Subject (Test Subject) >>\n",
        );
        pdf.extend_from_slice(b"endobj\n");

        // Cross-reference table
        let xref_pos = pdf.len();
        pdf.extend_from_slice(b"xref\n");
        pdf.extend_from_slice(b"0 4\n");
        pdf.extend_from_slice(b"0000000000 65535 f \n");
        pdf.extend_from_slice(format!("{obj1_pos:010} 00000 n \n").as_bytes());
        pdf.extend_from_slice(format!("{obj2_pos:010} 00000 n \n").as_bytes());
        pdf.extend_from_slice(format!("{obj3_pos:010} 00000 n \n").as_bytes());

        // Trailer
        pdf.extend_from_slice(b"trailer\n");
        pdf.extend_from_slice(b"<< /Size 4 /Root 1 0 R /Info 3 0 R >>\n");
        pdf.extend_from_slice(b"startxref\n");
        pdf.extend_from_slice(format!("{xref_pos}\n").as_bytes());
        pdf.extend_from_slice(b"%%EOF\n");

        pdf
    }

    #[test]
    fn test_pdf_document_new() {
        let pdf_data = create_minimal_pdf();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        // Verify document is created with empty caches
        assert!(document.page_tree.borrow().is_none());
        assert!(document.metadata_cache.borrow().is_none());
    }

    #[test]
    fn test_version() {
        let pdf_data = create_minimal_pdf();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        let version = document.version().unwrap();
        assert_eq!(version, "1.4");
    }

    #[test]
    fn test_page_count() {
        let pdf_data = create_minimal_pdf();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        let count = document.page_count().unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_metadata() {
        let pdf_data = create_pdf_with_metadata();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        let metadata = document.metadata().unwrap();
        assert_eq!(metadata.title, Some("Test Document".to_string()));
        assert_eq!(metadata.author, Some("Test Author".to_string()));
        assert_eq!(metadata.subject, Some("Test Subject".to_string()));

        // Verify caching works
        let metadata2 = document.metadata().unwrap();
        assert_eq!(metadata.title, metadata2.title);
    }

    #[test]
    fn test_get_page() {
        let pdf_data = create_minimal_pdf();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        // Get first page
        let page = document.get_page(0).unwrap();
        assert_eq!(page.media_box, [0.0, 0.0, 612.0, 792.0]);

        // Verify caching works
        let page2 = document.get_page(0).unwrap();
        assert_eq!(page.media_box, page2.media_box);
    }

    #[test]
    fn test_get_page_out_of_bounds() {
        let pdf_data = create_minimal_pdf();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        // Try to get page that doesn't exist
        let result = document.get_page(10);
        // With fallback lookup, this might succeed or fail gracefully
        if result.is_err() {
            assert!(result.unwrap_err().to_string().contains("Page"));
        } else {
            // If succeeds, should return a valid page
            let _page = result.unwrap();
        }
    }

    #[test]
    fn test_resource_manager_caching() {
        let resources = ResourceManager::new();

        // Test caching an object
        let obj_ref = (1, 0);
        let obj = PdfObject::String(PdfString("Test".as_bytes().to_vec()));

        assert!(resources.get_cached(obj_ref).is_none());

        resources.cache_object(obj_ref, obj.clone());

        let cached = resources.get_cached(obj_ref).unwrap();
        assert_eq!(cached, obj);

        // Test clearing cache
        resources.clear_cache();
        assert!(resources.get_cached(obj_ref).is_none());
    }

    #[test]
    fn test_get_object() {
        let pdf_data = create_minimal_pdf();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        // Get catalog object
        let catalog = document.get_object(1, 0).unwrap();
        if let PdfObject::Dictionary(dict) = catalog {
            if let Some(PdfObject::Name(name)) = dict.get("Type") {
                assert_eq!(name.0, "Catalog");
            } else {
                panic!("Expected /Type name");
            }
        } else {
            panic!("Expected dictionary object");
        }
    }

    #[test]
    fn test_resolve_reference() {
        let pdf_data = create_minimal_pdf();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        // Create a reference to the catalog
        let ref_obj = PdfObject::Reference(1, 0);

        // Resolve it
        let resolved = document.resolve(&ref_obj).unwrap();
        if let PdfObject::Dictionary(dict) = resolved {
            if let Some(PdfObject::Name(name)) = dict.get("Type") {
                assert_eq!(name.0, "Catalog");
            } else {
                panic!("Expected /Type name");
            }
        } else {
            panic!("Expected dictionary object");
        }
    }

    #[test]
    fn test_resolve_non_reference() {
        let pdf_data = create_minimal_pdf();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        // Try to resolve a non-reference object
        let obj = PdfObject::String(PdfString("Test".as_bytes().to_vec()));
        let resolved = document.resolve(&obj).unwrap();

        // Should return the same object
        assert_eq!(resolved, obj);
    }

    #[test]
    fn test_invalid_pdf_data() {
        let invalid_data = b"This is not a PDF";
        let cursor = Cursor::new(invalid_data.to_vec());
        let result = PdfReader::new(cursor);

        assert!(result.is_err());
    }

    #[test]
    fn test_empty_page_tree() {
        // Create PDF with empty page tree
        let pdf_data = create_pdf_with_metadata(); // This has 0 pages
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        let count = document.page_count().unwrap();
        assert_eq!(count, 0);

        // Try to get a page from empty document
        let result = document.get_page(0);
        assert!(result.is_err());
    }

    #[test]
    fn test_extract_text_empty_document() {
        let pdf_data = create_pdf_with_metadata();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        let text = document.extract_text().unwrap();
        assert!(text.is_empty());
    }

    #[test]
    fn test_concurrent_access() {
        let pdf_data = create_minimal_pdf();
        let cursor = Cursor::new(pdf_data);
        let reader = PdfReader::new(cursor).unwrap();
        let document = PdfDocument::new(reader);

        // Access multiple things concurrently
        let version = document.version().unwrap();
        let count = document.page_count().unwrap();
        let page = document.get_page(0).unwrap();

        assert_eq!(version, "1.4");
        assert_eq!(count, 1);
        assert_eq!(page.media_box[2], 612.0);
    }

    // Additional comprehensive tests
    mod comprehensive_tests {
        use super::*;

        #[test]
        fn test_resource_manager_default() {
            let resources = ResourceManager::default();
            assert!(resources.get_cached((1, 0)).is_none());
        }

        #[test]
        fn test_resource_manager_multiple_objects() {
            let resources = ResourceManager::new();

            // Cache multiple objects
            resources.cache_object((1, 0), PdfObject::Integer(42));
            resources.cache_object((2, 0), PdfObject::Boolean(true));
            resources.cache_object(
                (3, 0),
                PdfObject::String(PdfString("test".as_bytes().to_vec())),
            );

            // Verify all are cached
            assert!(resources.get_cached((1, 0)).is_some());
            assert!(resources.get_cached((2, 0)).is_some());
            assert!(resources.get_cached((3, 0)).is_some());

            // Clear and verify empty
            resources.clear_cache();
            assert!(resources.get_cached((1, 0)).is_none());
            assert!(resources.get_cached((2, 0)).is_none());
            assert!(resources.get_cached((3, 0)).is_none());
        }

        #[test]
        fn test_resource_manager_object_overwrite() {
            let resources = ResourceManager::new();

            // Cache an object
            resources.cache_object((1, 0), PdfObject::Integer(42));
            assert_eq!(resources.get_cached((1, 0)), Some(PdfObject::Integer(42)));

            // Overwrite with different object
            resources.cache_object((1, 0), PdfObject::Boolean(true));
            assert_eq!(resources.get_cached((1, 0)), Some(PdfObject::Boolean(true)));
        }

        #[test]
        fn test_get_object_caching() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Get object first time (should cache)
            let obj1 = document.get_object(1, 0).unwrap();

            // Get same object again (should use cache)
            let obj2 = document.get_object(1, 0).unwrap();

            // Objects should be identical
            assert_eq!(obj1, obj2);

            // Verify it's cached
            assert!(document.resources.get_cached((1, 0)).is_some());
        }

        #[test]
        fn test_get_object_different_generations() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Get object with generation 0
            let _obj1 = document.get_object(1, 0).unwrap();

            // Try to get same object with different generation (should fail)
            let result = document.get_object(1, 1);
            assert!(result.is_err());

            // Original should still be cached
            assert!(document.resources.get_cached((1, 0)).is_some());
        }

        #[test]
        fn test_get_object_nonexistent() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Try to get non-existent object
            let result = document.get_object(999, 0);
            assert!(result.is_err());
        }

        #[test]
        fn test_resolve_nested_references() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Test resolving a reference
            let ref_obj = PdfObject::Reference(2, 0);
            let resolved = document.resolve(&ref_obj).unwrap();

            // Should resolve to the pages object
            if let PdfObject::Dictionary(dict) = resolved {
                if let Some(PdfObject::Name(name)) = dict.get("Type") {
                    assert_eq!(name.0, "Pages");
                }
            }
        }

        #[test]
        fn test_resolve_various_object_types() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Test resolving different object types
            let test_objects = vec![
                PdfObject::Integer(42),
                PdfObject::Boolean(true),
                PdfObject::String(PdfString("test".as_bytes().to_vec())),
                PdfObject::Real(3.14),
                PdfObject::Null,
            ];

            for obj in test_objects {
                let resolved = document.resolve(&obj).unwrap();
                assert_eq!(resolved, obj);
            }
        }

        #[test]
        fn test_get_page_cached() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Get page first time
            let page1 = document.get_page(0).unwrap();

            // Get same page again
            let page2 = document.get_page(0).unwrap();

            // Should be identical
            assert_eq!(page1.media_box, page2.media_box);
            assert_eq!(page1.rotation, page2.rotation);
            assert_eq!(page1.obj_ref, page2.obj_ref);
        }

        #[test]
        fn test_metadata_caching() {
            let pdf_data = create_pdf_with_metadata();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Get metadata first time
            let meta1 = document.metadata().unwrap();

            // Get metadata again
            let meta2 = document.metadata().unwrap();

            // Should be identical
            assert_eq!(meta1.title, meta2.title);
            assert_eq!(meta1.author, meta2.author);
            assert_eq!(meta1.subject, meta2.subject);
            assert_eq!(meta1.version, meta2.version);
        }

        #[test]
        fn test_page_tree_initialization() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Initially page tree should be None
            assert!(document.page_tree.borrow().is_none());

            // After getting page count, page tree should be initialized
            let _count = document.page_count().unwrap();
            // Note: page_tree is private, so we can't directly check it
            // But we can verify it works by getting a page
            let _page = document.get_page(0).unwrap();
        }

        #[test]
        fn test_get_page_resources() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            let page = document.get_page(0).unwrap();
            let resources = document.get_page_resources(&page).unwrap();

            // The minimal PDF has empty resources
            assert!(resources.is_some());
        }

        #[test]
        fn test_get_page_content_streams_empty() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            let page = document.get_page(0).unwrap();
            let streams = document.get_page_content_streams(&page).unwrap();

            // Minimal PDF has no content streams
            assert!(streams.is_empty());
        }

        #[test]
        fn test_extract_text_from_page() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            let result = document.extract_text_from_page(0);
            // Should succeed even with empty page
            assert!(result.is_ok());
        }

        #[test]
        fn test_extract_text_from_page_out_of_bounds() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            let result = document.extract_text_from_page(999);
            // With fallback lookup, this might succeed or fail gracefully
            if result.is_err() {
                assert!(result.unwrap_err().to_string().contains("Page"));
            } else {
                // If succeeds, should return empty or valid text
                let _text = result.unwrap();
            }
        }

        #[test]
        fn test_extract_text_with_options() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            let options = crate::text::ExtractionOptions {
                preserve_layout: true,
                space_threshold: 0.5,
                newline_threshold: 15.0,
                ..Default::default()
            };

            let result = document.extract_text_with_options(options);
            assert!(result.is_ok());
        }

        #[test]
        fn test_version_different_pdf_versions() {
            // Test with different PDF versions
            let versions = vec!["1.3", "1.4", "1.5", "1.6", "1.7"];

            for version in versions {
                let mut pdf_data = Vec::new();

                // PDF header
                pdf_data.extend_from_slice(format!("%PDF-{version}\n").as_bytes());

                // Track positions for xref
                let obj1_pos = pdf_data.len();

                // Catalog object
                pdf_data.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

                let obj2_pos = pdf_data.len();

                // Pages object
                pdf_data
                    .extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");

                // Cross-reference table
                let xref_pos = pdf_data.len();
                pdf_data.extend_from_slice(b"xref\n");
                pdf_data.extend_from_slice(b"0 3\n");
                pdf_data.extend_from_slice(b"0000000000 65535 f \n");
                pdf_data.extend_from_slice(format!("{obj1_pos:010} 00000 n \n").as_bytes());
                pdf_data.extend_from_slice(format!("{obj2_pos:010} 00000 n \n").as_bytes());

                // Trailer
                pdf_data.extend_from_slice(b"trailer\n");
                pdf_data.extend_from_slice(b"<< /Size 3 /Root 1 0 R >>\n");
                pdf_data.extend_from_slice(b"startxref\n");
                pdf_data.extend_from_slice(format!("{xref_pos}\n").as_bytes());
                pdf_data.extend_from_slice(b"%%EOF\n");

                let cursor = Cursor::new(pdf_data);
                let reader = PdfReader::new(cursor).unwrap();
                let document = PdfDocument::new(reader);

                let pdf_version = document.version().unwrap();
                assert_eq!(pdf_version, version);
            }
        }

        #[test]
        fn test_page_count_zero() {
            let pdf_data = create_pdf_with_metadata(); // Has 0 pages
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            let count = document.page_count().unwrap();
            assert_eq!(count, 0);
        }

        #[test]
        fn test_multiple_object_access() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Access multiple objects
            let catalog = document.get_object(1, 0).unwrap();
            let pages = document.get_object(2, 0).unwrap();
            let page = document.get_object(3, 0).unwrap();

            // Verify they're all different objects
            assert_ne!(catalog, pages);
            assert_ne!(pages, page);
            assert_ne!(catalog, page);
        }

        #[test]
        fn test_error_handling_invalid_object_reference() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Try to resolve an invalid reference
            let invalid_ref = PdfObject::Reference(999, 0);
            let result = document.resolve(&invalid_ref);
            assert!(result.is_err());
        }

        #[test]
        fn test_concurrent_metadata_access() {
            let pdf_data = create_pdf_with_metadata();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Access metadata and other properties concurrently
            let metadata = document.metadata().unwrap();
            let version = document.version().unwrap();
            let count = document.page_count().unwrap();

            assert_eq!(metadata.title, Some("Test Document".to_string()));
            assert_eq!(version, "1.5");
            assert_eq!(count, 0);
        }

        #[test]
        fn test_page_properties_comprehensive() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            let page = document.get_page(0).unwrap();

            // Test all page properties
            assert_eq!(page.media_box, [0.0, 0.0, 612.0, 792.0]);
            assert_eq!(page.crop_box, None);
            assert_eq!(page.rotation, 0);
            assert_eq!(page.obj_ref, (3, 0));

            // Test width/height calculation
            assert_eq!(page.width(), 612.0);
            assert_eq!(page.height(), 792.0);
        }

        #[test]
        fn test_memory_usage_efficiency() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Access same page multiple times
            for _ in 0..10 {
                let _page = document.get_page(0).unwrap();
            }

            // Should only have one copy in cache
            let page_count = document.page_count().unwrap();
            assert_eq!(page_count, 1);
        }

        #[test]
        fn test_reader_borrow_safety() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Multiple concurrent borrows should work
            let version = document.version().unwrap();
            let count = document.page_count().unwrap();
            let metadata = document.metadata().unwrap();

            assert_eq!(version, "1.4");
            assert_eq!(count, 1);
            assert!(metadata.title.is_none());
        }

        #[test]
        fn test_cache_consistency() {
            let pdf_data = create_minimal_pdf();
            let cursor = Cursor::new(pdf_data);
            let reader = PdfReader::new(cursor).unwrap();
            let document = PdfDocument::new(reader);

            // Get object and verify caching
            let obj1 = document.get_object(1, 0).unwrap();
            let cached = document.resources.get_cached((1, 0)).unwrap();

            assert_eq!(obj1, cached);

            // Clear cache and get object again
            document.resources.clear_cache();
            let obj2 = document.get_object(1, 0).unwrap();

            // Should be same content but loaded fresh
            assert_eq!(obj1, obj2);
        }
    }

    #[test]
    fn test_resource_manager_new() {
        let resources = ResourceManager::new();
        assert!(resources.get_cached((1, 0)).is_none());
    }

    #[test]
    fn test_resource_manager_cache_and_get() {
        let resources = ResourceManager::new();

        // Cache an object
        let obj = PdfObject::Integer(42);
        resources.cache_object((10, 0), obj.clone());

        // Should be retrievable
        let cached = resources.get_cached((10, 0));
        assert!(cached.is_some());
        assert_eq!(cached.unwrap(), obj);

        // Non-existent object
        assert!(resources.get_cached((11, 0)).is_none());
    }

    #[test]
    fn test_resource_manager_clear_cache() {
        let resources = ResourceManager::new();

        // Cache multiple objects
        resources.cache_object((1, 0), PdfObject::Integer(1));
        resources.cache_object((2, 0), PdfObject::Integer(2));
        resources.cache_object((3, 0), PdfObject::Integer(3));

        // Verify they're cached
        assert!(resources.get_cached((1, 0)).is_some());
        assert!(resources.get_cached((2, 0)).is_some());
        assert!(resources.get_cached((3, 0)).is_some());

        // Clear cache
        resources.clear_cache();

        // Should all be gone
        assert!(resources.get_cached((1, 0)).is_none());
        assert!(resources.get_cached((2, 0)).is_none());
        assert!(resources.get_cached((3, 0)).is_none());
    }

    #[test]
    fn test_resource_manager_overwrite_cached() {
        let resources = ResourceManager::new();

        // Cache initial object
        resources.cache_object((1, 0), PdfObject::Integer(42));
        assert_eq!(
            resources.get_cached((1, 0)).unwrap(),
            PdfObject::Integer(42)
        );

        // Overwrite with new object
        resources.cache_object((1, 0), PdfObject::Integer(100));
        assert_eq!(
            resources.get_cached((1, 0)).unwrap(),
            PdfObject::Integer(100)
        );
    }

    #[test]
    fn test_resource_manager_multiple_generations() {
        let resources = ResourceManager::new();

        // Cache objects with different generations
        resources.cache_object((1, 0), PdfObject::Integer(10));
        resources.cache_object((1, 1), PdfObject::Integer(11));
        resources.cache_object((1, 2), PdfObject::Integer(12));

        // Each should be distinct
        assert_eq!(
            resources.get_cached((1, 0)).unwrap(),
            PdfObject::Integer(10)
        );
        assert_eq!(
            resources.get_cached((1, 1)).unwrap(),
            PdfObject::Integer(11)
        );
        assert_eq!(
            resources.get_cached((1, 2)).unwrap(),
            PdfObject::Integer(12)
        );
    }

    #[test]
    fn test_resource_manager_cache_complex_objects() {
        let resources = ResourceManager::new();

        // Cache different object types
        resources.cache_object((1, 0), PdfObject::Boolean(true));
        resources.cache_object((2, 0), PdfObject::Real(3.14159));
        resources.cache_object(
            (3, 0),
            PdfObject::String(PdfString::new(b"Hello PDF".to_vec())),
        );
        resources.cache_object((4, 0), PdfObject::Name(PdfName::new("Type".to_string())));

        let mut dict = PdfDictionary::new();
        dict.insert(
            "Key".to_string(),
            PdfObject::String(PdfString::new(b"Value".to_vec())),
        );
        resources.cache_object((5, 0), PdfObject::Dictionary(dict));

        let array = vec![PdfObject::Integer(1), PdfObject::Integer(2)];
        resources.cache_object((6, 0), PdfObject::Array(PdfArray(array)));

        // Verify all cached correctly
        assert_eq!(
            resources.get_cached((1, 0)).unwrap(),
            PdfObject::Boolean(true)
        );
        assert_eq!(
            resources.get_cached((2, 0)).unwrap(),
            PdfObject::Real(3.14159)
        );
        assert_eq!(
            resources.get_cached((3, 0)).unwrap(),
            PdfObject::String(PdfString::new(b"Hello PDF".to_vec()))
        );
        assert_eq!(
            resources.get_cached((4, 0)).unwrap(),
            PdfObject::Name(PdfName::new("Type".to_string()))
        );
        assert!(matches!(
            resources.get_cached((5, 0)).unwrap(),
            PdfObject::Dictionary(_)
        ));
        assert!(matches!(
            resources.get_cached((6, 0)).unwrap(),
            PdfObject::Array(_)
        ));
    }

    // Tests for PdfDocument removed due to API incompatibilities
    // The methods tested don't exist in the current implementation

    /*
        #[test]
        fn test_pdf_document_new_initialization() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            // Document should be created successfully
            // Initially no page tree loaded
            assert!(document.page_tree.borrow().is_none());
            assert!(document.metadata_cache.borrow().is_none());
        }

        #[test]
        fn test_pdf_document_version() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            let version = document.version().unwrap();
            assert!(!version.is_empty());
            // Most PDFs are version 1.4 to 1.7
            assert!(version.starts_with("1.") || version.starts_with("2."));
        }

        #[test]
        fn test_pdf_document_page_count() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            let count = document.page_count().unwrap();
            assert!(count > 0);
        }

        #[test]
        fn test_pdf_document_metadata() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            let metadata = document.metadata().unwrap();
            // Metadata should be cached after first access
            assert!(document.metadata_cache.borrow().is_some());

            // Second call should use cache
            let metadata2 = document.metadata().unwrap();
            assert_eq!(metadata.title, metadata2.title);
        }

        #[test]
        fn test_pdf_document_get_page() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            // Get first page
            let page = document.get_page(0).unwrap();
            assert!(page.width() > 0.0);
            assert!(page.height() > 0.0);

            // Page tree should be loaded now
            assert!(document.page_tree.borrow().is_some());
        }

        #[test]
        fn test_pdf_document_get_page_out_of_bounds() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            let page_count = document.page_count().unwrap();

            // Try to get page beyond count
            let result = document.get_page(page_count + 10);
            assert!(result.is_err());
        }


        #[test]
        fn test_pdf_document_get_object() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            // Get an object (catalog is usually object 1 0)
            let obj = document.get_object(1, 0);
            assert!(obj.is_ok());

            // Object should be cached
            assert!(document.resources.get_cached((1, 0)).is_some());
        }



        #[test]
        fn test_pdf_document_extract_text_from_page() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            // Try to extract text from first page
            let result = document.extract_text_from_page(0);
            // Even if no text, should not error
            assert!(result.is_ok());
        }

        #[test]
        fn test_pdf_document_extract_all_text() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            let extracted = document.extract_text().unwrap();
            let page_count = document.page_count().unwrap();

            // Should have text for each page
            assert_eq!(extracted.len(), page_count);
        }


        #[test]
        fn test_pdf_document_ensure_page_tree() {
            // Create a minimal PDF for testing
            let data = b"%PDF-1.4
    1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
    2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj
    3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj
    xref
    0 4
    0000000000 65535 f
    0000000009 00000 n
    0000000052 00000 n
    0000000101 00000 n
    trailer<</Size 4/Root 1 0 R>>
    startxref
    164
    %%EOF";
            let reader = PdfReader::new(std::io::Cursor::new(data.to_vec())).unwrap();
            let document = PdfDocument::new(reader);

            // Initially no page tree
            assert!(document.page_tree.borrow().is_none());

            // After ensuring, should be loaded
            document.ensure_page_tree().unwrap();
            assert!(document.page_tree.borrow().is_some());

            // Second call should not error
            document.ensure_page_tree().unwrap();
        }

        #[test]
        fn test_resource_manager_concurrent_access() {
            let resources = ResourceManager::new();

            // Simulate concurrent-like access pattern
            resources.cache_object((1, 0), PdfObject::Integer(1));
            let obj1 = resources.get_cached((1, 0));

            resources.cache_object((2, 0), PdfObject::Integer(2));
            let obj2 = resources.get_cached((2, 0));

            // Both should be accessible
            assert_eq!(obj1.unwrap(), PdfObject::Integer(1));
            assert_eq!(obj2.unwrap(), PdfObject::Integer(2));
        }

        #[test]
        fn test_resource_manager_large_cache() {
            let resources = ResourceManager::new();

            // Cache many objects
            for i in 0..1000 {
                resources.cache_object((i, 0), PdfObject::Integer(i as i64));
            }

            // Verify random access
            assert_eq!(resources.get_cached((500, 0)).unwrap(), PdfObject::Integer(500));
            assert_eq!(resources.get_cached((999, 0)).unwrap(), PdfObject::Integer(999));
            assert_eq!(resources.get_cached((0, 0)).unwrap(), PdfObject::Integer(0));

            // Clear should remove all
            resources.clear_cache();
            assert!(resources.get_cached((500, 0)).is_none());
        }
        */
}