isis-report-lib 0.2.0

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
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
//! Chromium/CDP PDF backend for `isis-report-lib`.
//!
//! Chromium is reused through a small process-wide worker pool (one browser per
//! worker thread), so consecutive PDFs avoid a browser launch. Pages run with
//! JavaScript disabled, service workers bypassed and outbound http(s) blocked
//! unless `allowed_hosts` is set. PDF options map to CDP's `Page.printToPDF`.

#![forbid(unsafe_code)]

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::Duration;

use chromiumoxide::browser::{Browser, BrowserConfig};
use chromiumoxide::cdp::browser_protocol::emulation::SetScriptExecutionDisabledParams;
use chromiumoxide::cdp::browser_protocol::fetch::{
    ContinueRequestParams, EnableParams as FetchEnableParams, EventRequestPaused, FailRequestParams, RequestPattern,
};
use chromiumoxide::cdp::browser_protocol::network::{BlockPattern, ErrorReason, SetBlockedUrLsParams, SetBypassServiceWorkerParams};
use chromiumoxide::cdp::browser_protocol::page::{CaptureScreenshotFormat, PrintToPdfParams};
use chromiumoxide::cdp::browser_protocol::tracing::{
    EndParams as TracingEndParams, EventDataCollected, EventTracingComplete, StartParams as TracingStartParams, StartTransferMode,
    TraceConfig, TraceConfigRecordMode,
};
use chromiumoxide::page::ScreenshotParams;
use chromiumoxide::Page;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, oneshot};

/// PDF page format.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub enum PageFormat {
    /// ISO A0.
    A0,
    /// ISO A1.
    A1,
    /// ISO A2.
    A2,
    /// ISO A3.
    A3,
    /// ISO A4 (default).
    #[default]
    A4,
    /// ISO A5.
    A5,
    /// ISO A6.
    A6,
    /// US Letter.
    Letter,
    /// US Legal.
    Legal,
    /// US Tabloid.
    Tabloid,
    /// US Ledger (landscape Tabloid).
    Ledger,
    /// Custom CSS lengths.
    Custom {
        /// Page width.
        width: String,
        /// Page height.
        height: String,
    },
}

impl PageFormat {
    fn inches(&self) -> Option<(f64, f64)> {
        match self {
            Self::A0 => Some((33.11, 46.81)),
            Self::A1 => Some((23.39, 33.11)),
            Self::A2 => Some((16.54, 23.39)),
            Self::A3 => Some((11.69, 16.54)),
            Self::A4 => Some((8.27, 11.69)),
            Self::A5 => Some((5.83, 8.27)),
            Self::A6 => Some((4.13, 5.83)),
            Self::Letter => Some((8.5, 11.0)),
            Self::Legal => Some((8.5, 14.0)),
            Self::Tabloid => Some((11.0, 17.0)),
            Self::Ledger => Some((17.0, 11.0)),
            Self::Custom { width, height } => Some((css_inches(width)?, css_inches(height)?)),
        }
    }
}

impl std::str::FromStr for PageFormat {
    type Err = PdfError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let normalized = value.trim().to_ascii_uppercase();
        match normalized.as_str() {
            "A0" => Ok(Self::A0),
            "A1" => Ok(Self::A1),
            "A2" => Ok(Self::A2),
            "A3" => Ok(Self::A3),
            "A4" => Ok(Self::A4),
            "A5" => Ok(Self::A5),
            "A6" => Ok(Self::A6),
            "LETTER" => Ok(Self::Letter),
            "LEGAL" => Ok(Self::Legal),
            "TABLOID" => Ok(Self::Tabloid),
            "LEDGER" => Ok(Self::Ledger),
            _ => Err(PdfError::Message(format!(
                "Invalid PDF page format {value:?} (expected A0-A6, Letter, Legal, Tabloid or Ledger)"
            ))),
        }
    }
}

/// Page margins in CSS lengths (e.g. `.15in`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Margins {
    /// Top margin.
    pub top: String,
    /// Bottom margin.
    pub bottom: String,
    /// Left margin.
    pub left: String,
    /// Right margin.
    pub right: String,
}

impl Default for Margins {
    fn default() -> Self {
        Self {
            top: ".15in".to_string(),
            bottom: ".4in".to_string(),
            left: ".15in".to_string(),
            right: ".15in".to_string(),
        }
    }
}

/// PDF backend selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum PdfBackend {
    /// Built-in Chromium/CDP backend (default).
    #[default]
    Chromium,
    /// External `weasyprint` executable.
    #[serde(rename = "weasyprint")]
    ExternalWeasyPrint,
}

/// Portable PDF options.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PdfOptions {
    /// Backend selection.
    pub backend: PdfBackend,
    /// Page size.
    pub format: PageFormat,
    /// Landscape orientation.
    pub landscape: bool,
    /// Render the header/footer templates.
    pub display_header_footer: bool,
    /// Chromium header template.
    pub header_template: Option<String>,
    /// Chromium footer template.
    pub footer_template: Option<String>,
    /// Page margins.
    pub margin: Margins,
    /// Print CSS backgrounds.
    pub print_background: bool,
    /// Page scale (0.1 to 2.0).
    pub scale: Option<f64>,
    /// Page ranges such as `1-3,5`.
    pub page_ranges: Option<String>,
    /// Custom page width (requires `height`).
    pub width: Option<String>,
    /// Custom page height (requires `width`).
    pub height: Option<String>,
    /// Render timeout in milliseconds.
    pub timeout_ms: Option<u64>,
    /// Emit a PDF outline/bookmark tree.
    pub outline: bool,
    /// Emit tagged/accessible PDF.
    pub tagged: bool,
    /// Prefer CSS `@page` size.
    pub prefer_css_page_size: bool,
    /// Hosts allowed to load external resources; `None` blocks all.
    pub allowed_hosts: Option<Vec<String>>,
    /// Write `report.html`, `report.png` and `trace.json` here.
    pub debug_dir: Option<PathBuf>,
}

impl Default for PdfOptions {
    fn default() -> Self {
        Self {
            backend: PdfBackend::Chromium,
            format: PageFormat::A4,
            landscape: false,
            display_header_footer: true,
            header_template: None,
            footer_template: None,
            margin: Margins::default(),
            print_background: true,
            scale: None,
            page_ranges: None,
            width: None,
            height: None,
            timeout_ms: None,
            outline: false,
            tagged: false,
            prefer_css_page_size: false,
            allowed_hosts: None,
            debug_dir: None,
        }
    }
}

impl PdfOptions {
    /// Validate option ranges before launching a browser.
    pub fn validate(&self) -> Result<(), PdfError> {
        if self.width.is_some() != self.height.is_some() {
            return Err(PdfError::Message("PDF width and height must be provided together".to_string()));
        }
        for size in [self.width.as_deref(), self.height.as_deref()].into_iter().flatten() {
            if css_inches(size).filter(|value| *value > 0.0).is_none() {
                return Err(PdfError::Message(
                    "Invalid PDF width/height (expected a positive CSS length)".to_string(),
                ));
            }
        }
        if let PageFormat::Custom { width, height } = &self.format {
            if css_inches(width).filter(|value| *value > 0.0).is_none() || css_inches(height).filter(|value| *value > 0.0).is_none() {
                return Err(PdfError::Message(
                    "Invalid custom PDF page size (expected positive CSS lengths)".to_string(),
                ));
            }
        }
        if let Some(scale) = self.scale {
            if !(0.1..=2.0).contains(&scale) {
                return Err(PdfError::Message(
                    "Invalid PDF scale (expected a number between 0.1 and 2)".to_string(),
                ));
            }
        }
        if let Some(page_ranges) = &self.page_ranges {
            if page_ranges.trim().is_empty() {
                return Err(PdfError::Message(
                    "Invalid PDF page_ranges (expected a non-empty string such as '1-3,5')".to_string(),
                ));
            }
        }
        if self.timeout_ms == Some(0) {
            return Err(PdfError::Message(
                "Invalid PDF timeout (expected a positive number of milliseconds)".to_string(),
            ));
        }
        for (label, margin) in [
            ("top", &self.margin.top),
            ("bottom", &self.margin.bottom),
            ("left", &self.margin.left),
            ("right", &self.margin.right),
        ] {
            if margin_inches(margin).filter(|value| *value >= 0.0).is_none() {
                return Err(PdfError::Message(format!(
                    "Invalid PDF margin.{label} (expected a non-negative CSS length)"
                )));
            }
        }
        if self.debug_dir.as_ref().is_some_and(|directory| directory.as_os_str().is_empty()) {
            return Err(PdfError::Message("PDF debug directory must be a non-empty path".to_string()));
        }
        Ok(())
    }
}

const DEBUG_MAX_BYTES: u64 = 50 * 1024 * 1024;

#[cfg(feature = "weasyprint-cli")]
struct TempWorkspace(PathBuf);

#[cfg(feature = "weasyprint-cli")]
impl TempWorkspace {
    fn new() -> Result<Self, PdfError> {
        let unique = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|duration| duration.as_nanos())
            .unwrap_or_default();
        let directory = std::env::temp_dir().join(format!("isis-report-{}-{unique}", std::process::id()));
        std::fs::create_dir_all(&directory).map_err(|error| PdfError::Message(format!("Cannot create a temporary directory: {error}")))?;
        Ok(Self(directory))
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

#[cfg(feature = "weasyprint-cli")]
impl Drop for TempWorkspace {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

const FOOTER_STRINGS: [(&str, &str, &str); 2] = [("Impresso em", "Página", "de"), ("Printed on", "Page", "of")];

const FOOTER_LOGO: &str = r##"<svg width="28" height="28" viewBox="0 0 86 86" fill="none" xmlns="http://www.w3.org/2000/svg" style="vertical-align:middle"><path d="M27.3331 25.9999C22.9331 27.8666 18.2665 29.3332 17.0665 29.3332C15.7332 29.3332 14.6665 30.2666 14.6665 31.4666C14.6665 33.9999 19.8665 33.0666 28.5331 29.1999C35.5998 25.9999 44.9331 25.9999 52.133 29.3332C55.733 30.9332 58.533 31.3332 59.1997 30.6666C60.7997 29.0666 60.7997 29.0666 52.3997 25.5999C43.4664 21.8666 37.1997 21.9999 27.3331 25.9999Z" fill="#0A2F46"/><path d="M64.7998 23.8666C62.9331 24.5333 62.6664 25.1999 63.7331 25.8666C64.9331 26.5332 62.9331 29.7332 57.3331 35.9999C50.3998 43.7332 48.7998 45.0665 46.7998 43.7332C44.9332 42.5332 43.1998 43.7332 36.2665 50.5332C28.7999 58.1331 27.5999 58.7998 23.0666 58.3998C18.7999 58.1331 17.8666 57.4665 17.5999 54.6665C17.1999 51.8665 17.3333 51.7332 19.1999 53.1998C21.3333 55.0665 25.3332 54.3998 25.3332 52.1331C25.3332 49.5998 21.3333 46.9332 18.5333 47.5998C15.0666 48.5332 13.3333 53.0665 14.9333 57.3331C16.5333 61.4664 18.2666 62.6664 23.4666 62.6664C27.7332 62.6664 35.3332 57.8665 41.1999 51.4665C44.1332 48.3998 44.6665 48.2665 46.6665 49.9998C48.6665 51.7331 49.7332 50.9332 58.1331 41.3332C63.1998 35.4665 68.2664 30.7999 69.3331 31.0666C70.6664 31.1999 71.4664 29.9999 71.7331 26.9332C72.1331 22.3999 70.3997 21.5999 64.7998 23.8666Z" fill="#0A2F46"/><path d="M27.9998 32.6666C23.9998 34.3999 19.3332 35.8666 17.7332 35.9999C13.7332 35.9999 13.5999 39.9999 17.4665 39.9999C19.0665 39.9999 23.8665 41.5999 28.1331 43.4665C33.0665 45.7332 36.7998 46.6665 38.2664 45.9999C40.2664 45.1999 40.2664 44.9332 38.6664 44.3999C37.5998 43.9999 33.9998 42.5332 30.6665 41.0665L24.6665 38.3999L29.9998 35.8666C35.3331 33.4666 35.3331 33.4666 35.9998 36.2666C37.0664 40.3999 40.6664 42.2665 43.1997 40.1332C44.3997 39.0665 45.3331 37.1999 45.3331 35.8666C45.3331 33.4666 45.5997 33.4666 49.8664 35.1999C54.133 36.9332 55.9997 36.7999 55.9997 34.5332C55.9997 32.7999 45.3331 29.3333 40.2664 29.3333C37.5998 29.4666 31.9998 30.9332 27.9998 32.6666ZM41.5998 36.2666C39.5998 38.2666 38.1331 36.7999 39.1998 33.8666C39.8664 32.1332 40.3998 31.8666 41.5998 33.0666C42.7997 34.2666 42.7997 35.0666 41.5998 36.2666ZM52.133 50.5332C49.3331 54.3998 48.2664 61.3331 50.3997 61.3331C51.5997 61.3331 60.533 50.6665 59.8663 50.2665C59.5997 49.9998 58.3997 49.1998 57.0664 48.2665C55.1997 46.7999 54.533 47.1999 52.133 50.5332Z" fill="#0A2F46"/></svg>"##;

/// Build the PDF page footer: timestamp left, page count center, brand right.
pub fn default_footer(printed_at: Option<&str>, locale: &str) -> String {
    let lang = if locale.replace('_', "-").to_lowercase().starts_with("pt") {
        0
    } else {
        1
    };
    let (printed_label, page_label, of_label) = FOOTER_STRINGS[lang];
    let date_html = printed_at
        .map(|printed_at| format!("<span>{printed_label} {printed_at}</span>"))
        .unwrap_or_else(|| "<span></span>".to_string());
    format!(
        "<div style=\"width:100%;font-size:10px;display:flex;justify-content:space-between;align-items:center;padding:0 .4in;\">{date_html}<span>{page_label} <span class='pageNumber'></span> {of_label} <span class='totalPages'></span></span><span>powered by {FOOTER_LOGO}</span></div>"
    )
}

fn css_inches(value: &str) -> Option<f64> {
    let value = value.trim();
    if value.is_empty() {
        return None;
    }
    let (number, unit) = if let Some(number) = value.strip_suffix("in") {
        (number, "in")
    } else if let Some(number) = value.strip_suffix("cm") {
        (number, "cm")
    } else if let Some(number) = value.strip_suffix("mm") {
        (number, "mm")
    } else if let Some(number) = value.strip_suffix("pt") {
        (number, "pt")
    } else if let Some(number) = value.strip_suffix("pc") {
        (number, "pc")
    } else if let Some(number) = value.strip_suffix("px") {
        (number, "px")
    } else {
        (value, "px")
    };
    let number: f64 = number.trim().parse().ok()?;
    Some(match unit {
        "in" => number,
        "cm" => number / 2.54,
        "mm" => number / 25.4,
        "pt" => number / 72.0,
        "pc" => number / 6.0,
        "px" => number / 96.0,
        _ => number,
    })
}

fn margin_inches(margin: &str) -> Option<f64> {
    css_inches(margin)
}

struct DebugTrace {
    directory: PathBuf,
    events: Arc<Mutex<Vec<serde_json::Value>>>,
    data_task: tokio::task::JoinHandle<()>,
    complete_task: tokio::task::JoinHandle<()>,
    complete_rx: tokio::sync::oneshot::Receiver<()>,
}

impl DebugTrace {
    async fn start(browser: &Browser, directory: &Path, html: &str) -> Result<Self, PdfError> {
        if directory.as_os_str().is_empty() {
            return Err(PdfError::Message("PDF debug directory must be a non-empty path".to_string()));
        }
        if directory.exists() && !directory.is_dir() {
            return Err(PdfError::Message(format!(
                "PDF debug directory is not a directory: {}",
                directory.display()
            )));
        }
        std::fs::create_dir_all(directory).map_err(|error| PdfError::Message(format!("Cannot create the debug directory: {error}")))?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700));
        }
        write_debug_html(directory, html)?;

        let mut data_stream = browser.event_listener::<EventDataCollected>().await.map_err(|error| {
            cleanup_debug_artifacts(directory);
            PdfError::Message(format!("Cannot listen for trace data: {error}"))
        })?;
        let mut complete_stream = browser.event_listener::<EventTracingComplete>().await.map_err(|error| {
            cleanup_debug_artifacts(directory);
            PdfError::Message(format!("Cannot listen for trace completion: {error}"))
        })?;
        let events = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&events);
        let data_task = tokio::spawn(async move {
            while let Some(event) = data_stream.next().await {
                if let Ok(mut collected) = sink.lock() {
                    collected.extend(event.value.iter().cloned());
                }
            }
        });
        let (complete_tx, complete_rx) = tokio::sync::oneshot::channel();
        let complete_task = tokio::spawn(async move {
            if complete_stream.next().await.is_some() {
                let _ = complete_tx.send(());
            }
        });

        let trace_config = TraceConfig::builder()
            .record_mode(TraceConfigRecordMode::RecordAsMuchAsPossible)
            .trace_buffer_size_in_kb(50.0 * 1024.0)
            .included_categories([
                "devtools.timeline",
                "disabled-by-default-devtools.timeline",
                "blink.user_timing",
                "loading",
                "v8",
            ])
            .build();
        let start = TracingStartParams::builder()
            .transfer_mode(StartTransferMode::ReportEvents)
            .trace_config(trace_config)
            .build();
        if let Err(error) = browser.execute(start).await {
            data_task.abort();
            complete_task.abort();
            cleanup_debug_artifacts(directory);
            return Err(PdfError::Message(format!("Cannot start the CDP trace: {error}")));
        }

        Ok(Self {
            directory: directory.to_path_buf(),
            events,
            data_task,
            complete_task,
            complete_rx,
        })
    }

    async fn abort(self, browser: &Browser) {
        let _ = tokio::time::timeout(Duration::from_secs(5), browser.execute(TracingEndParams::default())).await;
        self.data_task.abort();
        self.complete_task.abort();
    }

    async fn finish(self, browser: &Browser) -> Result<(), PdfError> {
        let end = browser.execute(TracingEndParams::default()).await;
        let _ = tokio::time::timeout(Duration::from_secs(5), self.complete_rx).await;
        // Events are queued on the listener task; give it a moment to drain
        // the last dataCollected chunks before writing.
        tokio::time::sleep(Duration::from_millis(100)).await;
        self.data_task.abort();
        self.complete_task.abort();
        end.map_err(|error| PdfError::Message(format!("Cannot stop the CDP trace: {error}")))?;

        let events = self
            .events
            .lock()
            .map_err(|_| PdfError::Message("Trace data lock was poisoned".to_string()))?
            .clone();
        let bytes = serde_json::to_vec(&events).map_err(|error| PdfError::Message(format!("Cannot serialize the CDP trace: {error}")))?;
        write_debug_trace(&self.directory, &bytes)
    }
}

const DEFAULT_MAX_POOL_WORKERS: usize = 4;
const MAX_POOL_WORKERS: usize = 8;
const DEFAULT_IDLE_SECS: u64 = 300;
static BROWSER_LAUNCHES: AtomicUsize = AtomicUsize::new(0);
static PDF_RENDERS: AtomicUsize = AtomicUsize::new(0);
static PDF_IDLE_CLOSES: AtomicUsize = AtomicUsize::new(0);
static PDF_POOL: LazyLock<Mutex<Option<Arc<PdfPool>>>> = LazyLock::new(|| Mutex::new(None));

struct PoolJob {
    html: String,
    options: PdfOptions,
    allowed_hosts: Option<Vec<String>>,
    reply: oneshot::Sender<Result<Vec<u8>, PdfError>>,
}

enum PoolMessage {
    Render(Box<PoolJob>),
    Shutdown,
}

struct WorkerHandle {
    sender: mpsc::UnboundedSender<PoolMessage>,
    in_flight: Arc<AtomicUsize>,
    thread: Mutex<Option<std::thread::JoinHandle<()>>>,
}

struct PdfPool {
    workers: Vec<WorkerHandle>,
}

/// Process-wide PDF pool metrics.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PdfPoolStats {
    /// Number of live worker threads (0 when the pool is not started).
    pub workers: usize,
    /// Workers currently rendering or queued.
    pub active_workers: usize,
    /// Render jobs accepted but not yet completed.
    pub in_flight: usize,
    /// Chromium launches since process start.
    pub browser_launches: usize,
    /// Completed render jobs since process start.
    pub renders: usize,
    /// Browser closes triggered by the idle timeout.
    pub idle_closes: usize,
}

fn pool_worker_count() -> usize {
    std::env::var("ISIS_REPORT_PDF_WORKERS")
        .ok()
        .and_then(|value| value.parse::<usize>().ok())
        .filter(|value| *value > 0)
        .unwrap_or_else(|| {
            std::thread::available_parallelism()
                .map(|value| value.get())
                .unwrap_or(1)
                .clamp(1, DEFAULT_MAX_POOL_WORKERS)
        })
        .min(MAX_POOL_WORKERS)
}

fn pool_idle_timeout() -> Option<Duration> {
    let seconds = std::env::var("ISIS_REPORT_PDF_IDLE_SECS")
        .ok()
        .and_then(|value| value.parse::<u64>().ok())
        .unwrap_or(DEFAULT_IDLE_SECS);
    (seconds > 0).then(|| Duration::from_secs(seconds))
}

impl PdfPool {
    fn new() -> Result<Self, PdfError> {
        let count = pool_worker_count();
        let mut workers = Vec::with_capacity(count);
        for index in 0..count {
            workers.push(spawn_worker(index, pool_idle_timeout())?);
        }
        Ok(Self { workers })
    }

    fn pick(&self) -> &WorkerHandle {
        self.workers
            .iter()
            .min_by_key(|worker| worker.in_flight.load(Ordering::Relaxed))
            .expect("a PDF pool has at least one worker")
    }

    fn shutdown(&self) {
        for worker in &self.workers {
            let _ = worker.sender.send(PoolMessage::Shutdown);
        }
        for worker in &self.workers {
            if let Ok(mut guard) = worker.thread.lock() {
                if let Some(thread) = guard.take() {
                    let _ = thread.join();
                }
            }
        }
    }
}

impl Drop for PdfPool {
    fn drop(&mut self) {
        for worker in &self.workers {
            let _ = worker.sender.send(PoolMessage::Shutdown);
        }
    }
}

fn spawn_worker(index: usize, idle: Option<Duration>) -> Result<WorkerHandle, PdfError> {
    let (sender, mut receiver) = mpsc::unbounded_channel::<PoolMessage>();
    let in_flight = Arc::new(AtomicUsize::new(0));
    let thread = std::thread::Builder::new()
        .name(format!("isis-report-pdf-{index}"))
        .spawn(move || {
            let runtime = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
                Ok(runtime) => runtime,
                Err(error) => {
                    log::error!("Cannot start the PDF worker runtime: {error}");
                    return;
                }
            };
            runtime.block_on(async move {
                let mut state = WorkerState::default();
                loop {
                    let message = match idle {
                        Some(idle) => match tokio::time::timeout(idle, receiver.recv()).await {
                            Ok(Some(message)) => message,
                            Ok(None) => break,
                            Err(_) => {
                                PDF_IDLE_CLOSES.fetch_add(1, Ordering::Relaxed);
                                state.reset().await;
                                continue;
                            }
                        },
                        None => match receiver.recv().await {
                            Some(message) => message,
                            None => break,
                        },
                    };
                    match message {
                        PoolMessage::Render(job) => {
                            PDF_RENDERS.fetch_add(1, Ordering::Relaxed);
                            let job = *job;
                            let result = state.render(&job.html, &job.options, job.allowed_hosts.as_deref()).await;
                            let _ = job.reply.send(result);
                        }
                        PoolMessage::Shutdown => break,
                    }
                }
                state.reset().await;
            });
        })
        .map_err(|error| PdfError::Message(format!("Cannot spawn the PDF worker: {error}")))?;
    Ok(WorkerHandle {
        sender,
        in_flight,
        thread: Mutex::new(Some(thread)),
    })
}

async fn remove_profile(path: PathBuf) {
    for _ in 0..50 {
        if std::fs::remove_dir_all(&path).is_ok() || !path.exists() {
            return;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    let _ = std::fs::remove_dir_all(path);
}

fn create_profile_dir() -> Result<PathBuf, PdfError> {
    let base = std::env::temp_dir();
    for _ in 0..16 {
        let mut bytes = [0u8; 8];
        getrandom::fill(&mut bytes).map_err(|error| PdfError::Message(format!("Cannot generate a Chromium profile name: {error}")))?;
        let path = base.join(format!(
            "isis-report-chromium-{}-{:016x}",
            std::process::id(),
            u64::from_le_bytes(bytes)
        ));
        match std::fs::create_dir(&path) {
            Ok(()) => return Ok(path),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => return Err(PdfError::Message(format!("Cannot create the Chromium profile directory: {error}"))),
        }
    }
    Err(PdfError::Message("Cannot create a unique Chromium profile directory".to_string()))
}

#[derive(Default)]
struct WorkerState {
    browser: Option<Browser>,
    handler: Option<tokio::task::JoinHandle<()>>,
    profile: Option<PathBuf>,
}

impl WorkerState {
    async fn ensure_browser(&mut self) -> Result<(), PdfError> {
        let healthy = match self.browser.as_ref() {
            Some(browser) if !self.handler.as_ref().is_some_and(tokio::task::JoinHandle::is_finished) => browser.version().await.is_ok(),
            _ => false,
        };
        if healthy {
            return Ok(());
        }
        self.reset().await;
        let profile = create_profile_dir()?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = std::fs::set_permissions(&profile, std::fs::Permissions::from_mode(0o700));
        }
        let config = match BrowserConfig::builder().user_data_dir(&profile).build() {
            Ok(config) => config,
            Err(error) => {
                let _ = std::fs::remove_dir_all(&profile);
                return Err(PdfError::Message(format!("Cannot configure Chromium: {error}")));
            }
        };
        let (browser, mut handler) = match Browser::launch(config).await {
            Ok(launched) => launched,
            Err(error) => {
                let _ = std::fs::remove_dir_all(&profile);
                return Err(PdfError::Message(format!("Cannot launch Chromium: {error}")));
            }
        };
        BROWSER_LAUNCHES.fetch_add(1, Ordering::SeqCst);
        self.handler = Some(tokio::spawn(async move {
            while let Some(event) = handler.next().await {
                if event.is_err() {
                    break;
                }
            }
        }));
        self.browser = Some(browser);
        self.profile = Some(profile);
        Ok(())
    }

    async fn reset(&mut self) {
        if let Some(mut browser) = self.browser.take() {
            let _ = tokio::time::timeout(Duration::from_secs(5), browser.close()).await;
        }
        if let Some(handler) = self.handler.take() {
            handler.abort();
        }
        if let Some(profile) = self.profile.take() {
            remove_profile(profile).await;
        }
    }

    async fn render(&mut self, html: &str, options: &PdfOptions, allowed_hosts: Option<&[String]>) -> Result<Vec<u8>, PdfError> {
        self.ensure_browser().await?;
        let result = {
            let browser = self.browser.as_ref().expect("browser was just ensured");
            render_with_browser(browser, html, options, allowed_hosts).await
        };
        if result.is_err() {
            let healthy = match self.browser.as_ref() {
                Some(browser) => browser.version().await.is_ok(),
                None => false,
            };
            if !healthy {
                self.reset().await;
            }
        }
        result
    }
}

fn pool_handle() -> Result<Arc<PdfPool>, PdfError> {
    let mut guard = PDF_POOL
        .lock()
        .map_err(|_| PdfError::Message("PDF pool lock was poisoned".to_string()))?;
    if guard.is_none() {
        *guard = Some(Arc::new(PdfPool::new()?));
    }
    guard
        .as_ref()
        .cloned()
        .ok_or_else(|| PdfError::Message("PDF pool is unavailable".to_string()))
}

fn invalidate_pool(pool: &Arc<PdfPool>) {
    if let Ok(mut guard) = PDF_POOL.lock() {
        if guard.as_ref().is_some_and(|current| Arc::ptr_eq(current, pool)) {
            *guard = None;
        }
    }
}

/// Ask the shared Chromium workers to close their browsers.
///
/// Blocks until every worker has closed its browser and exited. Call this
/// before process shutdown if the process keeps other output pipes open.
pub fn shutdown_pdf_pool() {
    let pool = PDF_POOL.lock().ok().and_then(|mut guard| guard.take());
    if let Some(pool) = pool {
        pool.shutdown();
    }
}

/// Process-wide PDF pool metrics.
pub fn pdf_pool_stats() -> PdfPoolStats {
    let pool = PDF_POOL.lock().ok().and_then(|guard| guard.as_ref().cloned());
    let (workers, active_workers, in_flight) = match pool.as_ref() {
        Some(pool) => {
            let in_flight = pool.workers.iter().map(|worker| worker.in_flight.load(Ordering::Relaxed)).sum();
            let active_workers = pool
                .workers
                .iter()
                .filter(|worker| worker.in_flight.load(Ordering::Relaxed) > 0)
                .count();
            (pool.workers.len(), active_workers, in_flight)
        }
        None => (0, 0, 0),
    };
    PdfPoolStats {
        workers,
        active_workers,
        in_flight,
        browser_launches: BROWSER_LAUNCHES.load(Ordering::Relaxed),
        renders: PDF_RENDERS.load(Ordering::Relaxed),
        idle_closes: PDF_IDLE_CLOSES.load(Ordering::Relaxed),
    }
}

struct InFlightGuard(Arc<AtomicUsize>);

impl InFlightGuard {
    fn new(counter: Arc<AtomicUsize>) -> Self {
        counter.fetch_add(1, Ordering::Relaxed);
        Self(counter)
    }
}

impl Drop for InFlightGuard {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::Relaxed);
    }
}

async fn pool_render(html: &str, options: &PdfOptions, allowed_hosts: Option<Vec<String>>) -> Result<Vec<u8>, PdfError> {
    let mut last_error = None;
    for attempt in 0..2 {
        let pool = pool_handle()?;
        let worker = pool.pick();
        let _guard = InFlightGuard::new(Arc::clone(&worker.in_flight));
        let (reply, response) = oneshot::channel();
        let message = PoolMessage::Render(Box::new(PoolJob {
            html: html.to_string(),
            options: options.clone(),
            allowed_hosts: allowed_hosts.clone(),
            reply,
        }));
        if worker.sender.send(message).is_err() {
            last_error = Some(PdfError::Message("PDF worker is not running".to_string()));
            invalidate_pool(&pool);
            if attempt == 0 {
                continue;
            }
            break;
        }
        match response.await {
            Ok(result) => return result,
            Err(_) => {
                last_error = Some(PdfError::Message("PDF worker dropped the request".to_string()));
                invalidate_pool(&pool);
                if attempt == 0 {
                    continue;
                }
            }
        }
    }
    Err(last_error.unwrap_or_else(|| PdfError::Message("PDF pool is unavailable".to_string())))
}

/// Render HTML to PDF with Chromium (CDP).
pub async fn render_html_to_pdf(html: &str, options: &PdfOptions) -> Result<Vec<u8>, PdfError> {
    options.validate()?;
    if options.backend == PdfBackend::ExternalWeasyPrint {
        return render_weasyprint(html, options).await;
    }
    let allowed_hosts = options.allowed_hosts.as_deref().map(validate_allowed_hosts).transpose()?;
    pool_render(html, options, allowed_hosts).await
}

async fn render_with_browser(
    browser: &Browser,
    html: &str,
    options: &PdfOptions,
    allowed_hosts: Option<&[String]>,
) -> Result<Vec<u8>, PdfError> {
    let trace = match options.debug_dir.as_deref() {
        Some(directory) => Some(DebugTrace::start(browser, directory, html).await?),
        None => None,
    };
    let result = render_page(browser, html, options, allowed_hosts).await;
    if let Some(trace) = trace {
        if result.is_ok() {
            if let Err(error) = trace.finish(browser).await {
                log::warn!("Cannot finish the PDF debug trace: {error}");
            }
        } else {
            trace.abort(browser).await;
            if let Some(directory) = options.debug_dir.as_deref() {
                cleanup_debug_artifacts(directory);
            }
        }
    }
    result
}

async fn render_page(browser: &Browser, html: &str, options: &PdfOptions, allowed_hosts: Option<&[String]>) -> Result<Vec<u8>, PdfError> {
    let page = browser
        .new_page("about:blank")
        .await
        .map_err(|error| PdfError::Message(format!("Cannot open a Chromium page: {error}")))?;
    let operations = async {
        let guard_task = configure_page(&page, allowed_hosts).await?;
        page.set_content(html)
            .await
            .map_err(|error| PdfError::Message(format!("Cannot load the report HTML: {error}")))?;
        if let Some(debug_dir) = &options.debug_dir {
            write_debug_png(
                debug_dir,
                &page
                    .screenshot(
                        ScreenshotParams::builder()
                            .format(CaptureScreenshotFormat::Png)
                            .full_page(true)
                            .build(),
                    )
                    .await
                    .map_err(|error| PdfError::Message(format!("Cannot capture the debug PNG: {error}")))?,
            )?;
        }
        let params = print_params(options);
        let result = page
            .pdf(params)
            .await
            .map_err(|error| PdfError::Message(format!("Chromium printToPDF failed: {error}")));
        guard_task.abort();
        result
    };
    let result = match options.timeout_ms {
        Some(timeout_ms) => tokio::time::timeout(Duration::from_millis(timeout_ms), operations)
            .await
            .map_err(|_| PdfError::Message(format!("PDF generation timed out after {timeout_ms} ms")))?,
        None => operations.await,
    };
    let _ = page.close().await;
    result
}

async fn configure_page(page: &Page, allowed_hosts: Option<&[String]>) -> Result<tokio::task::JoinHandle<()>, PdfError> {
    page.execute(SetScriptExecutionDisabledParams::new(true))
        .await
        .map_err(|error| PdfError::Message(format!("Cannot disable JavaScript: {error}")))?;
    page.execute(SetBypassServiceWorkerParams::new(true))
        .await
        .map_err(|error| PdfError::Message(format!("Cannot bypass service workers: {error}")))?;
    // Fetch does not see WebSockets; block those outright.
    page.execute(
        SetBlockedUrLsParams::builder()
            .url_patterns([BlockPattern::new("ws://*", true), BlockPattern::new("wss://*", true)])
            .build(),
    )
    .await
    .map_err(|error| PdfError::Message(format!("Cannot block WebSockets: {error}")))?;

    let mut intercept = page
        .event_listener::<EventRequestPaused>()
        .await
        .map_err(|error| PdfError::Message(format!("Cannot listen for network requests: {error}")))?;
    let guard_page = page.clone();
    let allowed = allowed_hosts.map(ToOwned::to_owned);
    let guard = tokio::spawn(async move {
        while let Some(event) = intercept.next().await {
            let url = event.request.url.clone();
            if is_host_allowed(&url, allowed.as_deref()) {
                let _ = guard_page.execute(ContinueRequestParams::new(event.request_id.clone())).await;
            } else {
                let host = url::Url::parse(&url)
                    .ok()
                    .and_then(|url| url.host_str().map(ToOwned::to_owned))
                    .unwrap_or_else(|| "?".to_string());
                log::warn!(
                    "Blocked outbound request to {} (not in allowed_hosts).",
                    crate::logging::log_value(&host)
                );
                if let Ok(params) = FailRequestParams::builder()
                    .request_id(event.request_id.clone())
                    .error_reason(ErrorReason::BlockedByClient)
                    .build()
                {
                    let _ = guard_page.execute(params).await;
                }
            }
        }
    });
    page.execute(
        FetchEnableParams::builder()
            .patterns([RequestPattern::builder().url_pattern("*").build()])
            .build(),
    )
    .await
    .map_err(|error| PdfError::Message(format!("Cannot enable network interception: {error}")))?;
    Ok(guard)
}

fn print_params(options: &PdfOptions) -> PrintToPdfParams {
    let mut builder = PrintToPdfParams::builder()
        .landscape(options.landscape)
        .display_header_footer(options.display_header_footer)
        .print_background(options.print_background)
        .prefer_css_page_size(options.prefer_css_page_size)
        .generate_tagged_pdf(options.tagged || options.outline)
        .generate_document_outline(options.outline);
    if let Some(scale) = options.scale {
        builder = builder.scale(scale);
    }
    if let Some(page_ranges) = &options.page_ranges {
        builder = builder.page_ranges(page_ranges.clone());
    }
    let size = match (&options.width, &options.height) {
        (Some(width), Some(height)) => match (css_inches(width), css_inches(height)) {
            (Some(width), Some(height)) => Some((width, height)),
            _ => None,
        },
        _ => options.format.inches(),
    };
    if let Some((width, height)) = size {
        builder = builder.paper_width(width).paper_height(height);
    }
    if let Some(header) = &options.header_template {
        builder = builder.header_template(header.clone());
    }
    if let Some(footer) = &options.footer_template {
        builder = builder.footer_template(footer.clone());
    } else if options.display_header_footer {
        builder = builder.footer_template(default_footer(None, "pt-BR"));
    }
    builder = builder
        .margin_top(margin_inches(&options.margin.top).unwrap_or(0.15))
        .margin_bottom(margin_inches(&options.margin.bottom).unwrap_or(0.4))
        .margin_left(margin_inches(&options.margin.left).unwrap_or(0.15))
        .margin_right(margin_inches(&options.margin.right).unwrap_or(0.15));
    builder.build()
}

/// Validate and normalize an outbound host allow-list (bare hostnames only).
pub fn validate_allowed_hosts(hosts: &[String]) -> Result<Vec<String>, PdfError> {
    let mut cleaned = Vec::with_capacity(hosts.len());
    for entry in hosts {
        let host = entry.trim().to_lowercase();
        let host = host.trim_end_matches('.');
        if host.is_empty()
            || host.starts_with('.')
            || host.contains('*')
            || host.contains('/')
            || host.contains(':')
            || host.contains('@')
            || host.contains('?')
            || host.contains('#')
            || host.chars().any(char::is_whitespace)
        {
            return Err(PdfError::Message(format!(
                "Invalid allowed_hosts entry (bare hostname, no scheme/port/path/wildcard): {entry:?}"
            )));
        }
        cleaned.push(host.to_string());
    }
    Ok(cleaned)
}

/// Pure network policy predicate: only http(s) is gated; other schemes pass.
pub fn is_host_allowed(url: &str, allowed_hosts: Option<&[String]>) -> bool {
    let Ok(parsed) = url::Url::parse(url) else {
        return false;
    };
    if !matches!(parsed.scheme(), "http" | "https") {
        return true;
    }
    let Some(allowed_hosts) = allowed_hosts else {
        return false;
    };
    let Some(host) = parsed.host_str() else {
        return false;
    };
    let host = host.to_lowercase();
    let host = host.trim_end_matches('.');
    !host.is_empty()
        && allowed_hosts
            .iter()
            .any(|allowed| allowed.trim().trim_end_matches('.').eq_ignore_ascii_case(host))
}

fn cleanup_debug_artifacts(directory: &Path) {
    for name in ["report.html", "report.png", "trace.json"] {
        let _ = std::fs::remove_file(directory.join(name));
    }
}

fn write_debug_html(directory: &std::path::Path, html: &str) -> Result<(), PdfError> {
    std::fs::create_dir_all(directory).map_err(|error| PdfError::Message(format!("Cannot create the debug directory: {error}")))?;
    if html.len() as u64 > DEBUG_MAX_BYTES {
        return Err(PdfError::Message(format!(
            "PDF debug HTML artifact exceeds {DEBUG_MAX_BYTES} bytes"
        )));
    }
    std::fs::write(directory.join("report.html"), html).map_err(|error| PdfError::Message(format!("Cannot write the debug HTML: {error}")))
}

fn write_debug_png(directory: &std::path::Path, png: &[u8]) -> Result<(), PdfError> {
    if png.len() as u64 > DEBUG_MAX_BYTES {
        return Err(PdfError::Message(format!("PDF debug PNG artifact exceeds {DEBUG_MAX_BYTES} bytes")));
    }
    std::fs::write(directory.join("report.png"), png).map_err(|error| PdfError::Message(format!("Cannot write the debug PNG: {error}")))
}

fn write_debug_trace(directory: &std::path::Path, trace: &[u8]) -> Result<(), PdfError> {
    if trace.len() as u64 > DEBUG_MAX_BYTES {
        return Err(PdfError::Message(format!(
            "PDF debug trace artifact exceeds {DEBUG_MAX_BYTES} bytes"
        )));
    }
    std::fs::write(directory.join("trace.json"), trace).map_err(|error| PdfError::Message(format!("Cannot write the debug trace: {error}")))
}

async fn render_weasyprint(html: &str, options: &PdfOptions) -> Result<Vec<u8>, PdfError> {
    #[cfg(not(feature = "weasyprint-cli"))]
    {
        let _ = (html, options);
        Err(PdfError::Message(
            "WeasyPrint backend requires the 'weasyprint-cli' feature and a weasyprint binary".to_string(),
        ))
    }
    #[cfg(feature = "weasyprint-cli")]
    {
        if html.to_lowercase().contains("dir=\"rtl\"") || html.to_lowercase().contains("dir='rtl'") {
            return Err(PdfError::Message(
                "WeasyPrint backend does not support right-to-left documents (meta.direction='rtl'); use the Chromium backend".to_string(),
            ));
        }
        if options.allowed_hosts.as_ref().is_some_and(|hosts| !hosts.is_empty()) {
            return Err(PdfError::Message(
                "WeasyPrint backend does not support allowed_hosts; external resources are blocked".to_string(),
            ));
        }
        if options.debug_dir.is_some() {
            return Err(PdfError::Message(
                "WeasyPrint backend does not support debug_dir (Playwright-specific artifacts)".to_string(),
            ));
        }
        if options.page_ranges.is_some() || options.scale.is_some() || options.timeout_ms.is_some() {
            return Err(PdfError::Message(
                "WeasyPrint backend does not support page_ranges, scale or timeout".to_string(),
            ));
        }
        if options.header_template.is_some() || options.footer_template.is_some() {
            return Err(PdfError::Message(
                "WeasyPrint backend does not support header_template/footer_template".to_string(),
            ));
        }
        if options.display_header_footer {
            return Err(PdfError::Message(
                "WeasyPrint backend does not support Playwright header/footer templates".to_string(),
            ));
        }
        if html.contains("http://") || html.contains("https://") {
            return Err(PdfError::Message(
                "WeasyPrint backend blocks external resources; use data URIs".to_string(),
            ));
        }
        let directory = TempWorkspace::new()?;
        let html_path = directory.path().join("report.html");
        let pdf_path = directory.path().join("report.pdf");
        std::fs::write(&html_path, html).map_err(|error| PdfError::Message(format!("Cannot write the temporary HTML: {error}")))?;
        let (width, height) = match (&options.width, &options.height) {
            (Some(width), Some(height)) => (width.clone(), height.clone()),
            _ => match &options.format {
                PageFormat::Custom { width, height } => (width.clone(), height.clone()),
                other => {
                    let (width, height) = other.inches().unwrap_or((8.27, 11.69));
                    (format!("{width}in"), format!("{height}in"))
                }
            },
        };
        let orientation = if options.landscape { " landscape" } else { "" };
        let margin = format!(
            "{} {} {} {}",
            options.margin.top, options.margin.right, options.margin.bottom, options.margin.left
        );
        let css = format!("@page {{ size: {width} {height}{orientation}; margin: {margin}; }}");
        let css_path = directory.path().join("page.css");
        std::fs::write(&css_path, css).map_err(|error| PdfError::Message(format!("Cannot write the temporary CSS: {error}")))?;
        let status = tokio::process::Command::new("weasyprint")
            .arg("-s")
            .arg(&css_path)
            .arg(&html_path)
            .arg(&pdf_path)
            .status()
            .await
            .map_err(|error| PdfError::Message(format!("Cannot run weasyprint: {error}")))?;
        if !status.success() {
            return Err(PdfError::Message(format!("weasyprint exited with status {status}")));
        }
        std::fs::read(&pdf_path).map_err(|error| PdfError::Message(format!("Cannot read the WeasyPrint PDF: {error}")))
    }
}

/// PDF backend error.
#[derive(Debug, thiserror::Error)]
pub enum PdfError {
    /// The backend is not implemented for this build.
    #[error("PDF backend is not implemented yet")]
    NotImplemented,
    /// Backend or option error.
    #[error("PDF backend error: {0}")]
    Message(String),
}

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

    struct PoolCleanup;

    impl Drop for PoolCleanup {
        fn drop(&mut self) {
            shutdown_pdf_pool();
        }
    }

    struct EnvGuard {
        key: &'static str,
        previous: Option<std::ffi::OsString>,
    }

    impl EnvGuard {
        fn set(key: &'static str, value: &str) -> Self {
            let previous = std::env::var_os(key);
            std::env::set_var(key, value);
            Self { key, previous }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            match self.previous.take() {
                Some(value) => std::env::set_var(self.key, value),
                None => std::env::remove_var(self.key),
            }
        }
    }

    fn profile_dirs_for_current_process() -> Vec<PathBuf> {
        let prefix = format!("isis-report-chromium-{}-", std::process::id());
        let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) else {
            return Vec::new();
        };
        entries
            .flatten()
            .map(|entry| entry.path())
            .filter(|path| {
                path.file_name()
                    .and_then(|name| name.to_str())
                    .is_some_and(|name| name.starts_with(&prefix))
            })
            .collect()
    }

    fn page_size(bytes: &[u8]) -> (f32, f32) {
        let document = lopdf::Document::load_mem(bytes).unwrap();
        let page_id = *document.get_pages().values().next().unwrap();
        let page = document.get_object(page_id).unwrap().as_dict().unwrap();
        let media_box = page.get(b"MediaBox").unwrap().as_array().unwrap();
        (media_box[2].as_float().unwrap(), media_box[3].as_float().unwrap())
    }

    #[test]
    fn css_lengths() {
        assert!((css_inches(".15in").unwrap() - 0.15).abs() < 1e-9);
        assert!((css_inches("1cm").unwrap() - 1.0 / 2.54).abs() < 1e-9);
        assert!((css_inches("96px").unwrap() - 1.0).abs() < 1e-9);
        assert_eq!(css_inches(""), None);
    }

    #[test]
    fn default_footer_is_localized() {
        assert!(default_footer(Some("2024-01-01 10:00"), "pt-BR").contains("Impresso em"));
        assert!(default_footer(Some("2024-01-01 10:00"), "en-US").contains("Printed on"));
        assert!(default_footer(None, "en-US").contains("pageNumber"));
    }

    #[test]
    fn page_formats_parse() {
        assert_eq!("A4".parse::<PageFormat>().unwrap(), PageFormat::A4);
        assert_eq!("letter".parse::<PageFormat>().unwrap(), PageFormat::Letter);
        assert!("A9".parse::<PageFormat>().is_err());
    }

    #[test]
    fn validates_options() {
        let mut options = PdfOptions {
            width: Some("8.5in".to_string()),
            ..PdfOptions::default()
        };
        assert!(options.validate().is_err());
        options.height = Some("11in".to_string());
        assert!(options.validate().is_ok());
        options.scale = Some(3.0);
        assert!(options.validate().is_err());
        options.scale = Some(1.0);
        options.page_ranges = Some(" ".to_string());
        assert!(options.validate().is_err());
        options.page_ranges = None;
        options.margin.top = "-1in".to_string();
        assert!(options.validate().is_err());
    }

    #[test]
    fn page_formats_and_css_lengths() {
        let cases = [
            (PageFormat::A0, (33.11, 46.81)),
            (PageFormat::A1, (23.39, 33.11)),
            (PageFormat::A2, (16.54, 23.39)),
            (PageFormat::A3, (11.69, 16.54)),
            (PageFormat::A4, (8.27, 11.69)),
            (PageFormat::A5, (5.83, 8.27)),
            (PageFormat::A6, (4.13, 5.83)),
            (PageFormat::Letter, (8.5, 11.0)),
            (PageFormat::Legal, (8.5, 14.0)),
            (PageFormat::Tabloid, (11.0, 17.0)),
            (PageFormat::Ledger, (17.0, 11.0)),
        ];
        for (format, expected) in cases {
            assert_eq!(format.inches(), Some(expected), "{format:?}");
        }
        assert_eq!(
            PageFormat::Custom {
                width: "1in".to_string(),
                height: "2in".to_string()
            }
            .inches(),
            Some((1.0, 2.0))
        );
        assert!(PageFormat::Custom {
            width: "bad".to_string(),
            height: "2in".to_string()
        }
        .inches()
        .is_none());

        assert!((css_inches("1in").unwrap() - 1.0).abs() < 1e-9);
        assert!((css_inches("2.54cm").unwrap() - 1.0).abs() < 1e-9);
        assert!((css_inches("25.4mm").unwrap() - 1.0).abs() < 1e-9);
        assert!((css_inches("72pt").unwrap() - 1.0).abs() < 1e-9);
        assert!((css_inches("6pc").unwrap() - 1.0).abs() < 1e-9);
        assert!((css_inches("96px").unwrap() - 1.0).abs() < 1e-9);
        assert!((css_inches("96").unwrap() - 1.0).abs() < 1e-9);
        assert!(css_inches("").is_none());
        assert!(css_inches("bad").is_none());
    }

    #[test]
    fn validates_custom_sizes_timeouts_scales_and_margins() {
        let mut options = PdfOptions {
            width: Some("8in".to_string()),
            ..PdfOptions::default()
        };
        assert!(options.validate().is_err());
        options.width = Some("bad".to_string());
        options.height = Some("11in".to_string());
        assert!(options.validate().is_err());
        options.width = None;
        options.height = None;
        options.format = PageFormat::Custom {
            width: "0in".to_string(),
            height: "1in".to_string(),
        };
        assert!(options.validate().is_err());
        options.format = PageFormat::Custom {
            width: "1in".to_string(),
            height: "2in".to_string(),
        };
        assert!(options.validate().is_ok());
        options.timeout_ms = Some(0);
        assert!(options.validate().is_err());
        options.timeout_ms = None;
        options.scale = Some(0.05);
        assert!(options.validate().is_err());
        options.scale = Some(1.0);
        options.margin.bottom = " ".to_string();
        assert!(options.validate().is_err());
        options.margin.bottom = "0in".to_string();
        options.debug_dir = Some(std::path::PathBuf::new());
        assert!(options.validate().is_err());
    }

    #[test]
    fn debug_artifact_size_limits() {
        let directory = tempfile::tempdir().unwrap();
        let oversized = vec![0u8; DEBUG_MAX_BYTES as usize + 1];
        assert!(write_debug_png(directory.path(), &oversized).is_err());
        assert!(write_debug_trace(directory.path(), &oversized).is_err());
    }

    #[cfg(feature = "weasyprint-cli")]
    #[test]
    fn temp_workspace_creates_and_removes() {
        let workspace = TempWorkspace::new().unwrap();
        let path = workspace.path().to_path_buf();
        assert!(path.exists());
        drop(workspace);
        assert!(!path.exists());
    }

    #[test]
    fn debug_dir_validation_and_size_limit() {
        let options = PdfOptions {
            debug_dir: Some(std::path::PathBuf::new()),
            ..PdfOptions::default()
        };
        assert!(options.validate().is_err());

        let directory = tempfile::tempdir().unwrap();
        let file = directory.path().join("not-a-directory");
        std::fs::write(&file, b"x").unwrap();
        assert!(write_debug_html(&file, "<html></html>").is_err());

        let oversized = "x".repeat(DEBUG_MAX_BYTES as usize + 1);
        assert!(write_debug_html(directory.path(), &oversized).is_err());

        write_debug_html(directory.path(), "<html>ok</html>").unwrap();
        assert!(directory.path().join("report.html").exists());
    }

    #[test]
    fn debug_cleanup_removes_only_known_artifacts() {
        let directory = tempfile::tempdir().unwrap();
        for name in ["report.html", "report.png", "trace.json"] {
            std::fs::write(directory.path().join(name), b"x").unwrap();
        }
        std::fs::write(directory.path().join("keep.txt"), b"keep").unwrap();
        cleanup_debug_artifacts(directory.path());
        for name in ["report.html", "report.png", "trace.json"] {
            assert!(!directory.path().join(name).exists(), "{name} was not removed");
        }
        assert!(directory.path().join("keep.txt").exists());
    }

    #[test]
    fn shutdown_without_pool_is_noop() {
        shutdown_pdf_pool();
        let stats = pdf_pool_stats();
        assert_eq!(stats.workers, 0);
        assert_eq!(stats.active_workers, 0);
        assert_eq!(stats.in_flight, 0);
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn pool_reuses_the_browser() {
        let _cleanup = PoolCleanup;
        shutdown_pdf_pool();
        let options = PdfOptions::default();
        render_html_to_pdf("<html><body><p>first</p></body></html>", &options)
            .await
            .unwrap();
        let launches = BROWSER_LAUNCHES.load(Ordering::SeqCst);
        assert!(launches >= 1);
        render_html_to_pdf("<html><body><p>second</p></body></html>", &options)
            .await
            .unwrap();
        assert_eq!(BROWSER_LAUNCHES.load(Ordering::SeqCst), launches);
        let stats = pdf_pool_stats();
        assert!(stats.workers >= 1, "{stats:?}");
        assert!(stats.renders >= 2, "{stats:?}");
        assert_eq!(stats.in_flight, 0, "{stats:?}");
        shutdown_pdf_pool();
        assert_eq!(pdf_pool_stats().workers, 0);
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn pool_handles_concurrent_renders() {
        let _cleanup = PoolCleanup;
        let options = PdfOptions::default();
        let (first, second) = tokio::join!(
            render_html_to_pdf("<html><body><p>A</p></body></html>", &options),
            render_html_to_pdf("<html><body><p>B</p></body></html>", &options)
        );
        assert!(first.unwrap().starts_with(b"%PDF-"));
        assert!(second.unwrap().starts_with(b"%PDF-"));
    }

    #[test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    fn generate_many_uses_the_pool() {
        let _cleanup = PoolCleanup;
        let payloads = vec![
            Value::from_json(serde_json::json!({"meta": {"title": "One"}, "data": [{"a": 1}]})),
            Value::from_json(serde_json::json!({"meta": {"title": "Two"}, "data": [{"a": 2}]})),
        ];
        let pdfs = crate::api::generate_many(&payloads, 2, None).unwrap();
        assert_eq!(pdfs.len(), 2);
        assert!(pdfs.iter().all(|pdf| pdf.starts_with(b"%PDF-")));
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn pool_closes_idle_browsers() {
        let _cleanup = PoolCleanup;
        shutdown_pdf_pool();
        let _idle = EnvGuard::set("ISIS_REPORT_PDF_IDLE_SECS", "1");
        let options = PdfOptions::default();
        render_html_to_pdf("<html><body><p>idle</p></body></html>", &options).await.unwrap();
        let launches = pdf_pool_stats().browser_launches;
        tokio::time::sleep(Duration::from_millis(1600)).await;
        let stats = pdf_pool_stats();
        assert!(stats.idle_closes >= 1, "{stats:?}");
        assert_eq!(stats.in_flight, 0);
        render_html_to_pdf("<html><body><p>after idle</p></body></html>", &options)
            .await
            .unwrap();
        assert!(pdf_pool_stats().browser_launches > launches, "{:?}", pdf_pool_stats());
    }

    #[test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    fn pool_handles_a_batch_under_concurrency() {
        let _cleanup = PoolCleanup;
        shutdown_pdf_pool();
        let before = pdf_pool_stats();
        let payloads: Vec<Value> = (0..12)
            .map(|index| {
                Value::from_json(serde_json::json!({
                    "meta": {"title": format!("Batch {index}"), "locale": "en-US"},
                    "layout": {"name": {"label": "Name", "format_mask": "str"}},
                    "data": [{"name": format!("Item {index}")}]
                }))
            })
            .collect();
        let pdfs = crate::api::generate_many(&payloads, 4, None).unwrap();
        assert_eq!(pdfs.len(), 12);
        assert!(pdfs.iter().all(|pdf| pdf.starts_with(b"%PDF-")));
        let stats = pdf_pool_stats();
        assert_eq!(stats.renders - before.renders, 12, "{stats:?}");
        assert_eq!(stats.in_flight, 0, "{stats:?}");
        assert!(stats.browser_launches - before.browser_launches <= stats.workers, "{stats:?}");
    }

    #[test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    fn pool_respects_the_configured_worker_limit() {
        let _cleanup = PoolCleanup;
        shutdown_pdf_pool();
        let _workers = EnvGuard::set("ISIS_REPORT_PDF_WORKERS", "1");
        let before = pdf_pool_stats();
        let payloads: Vec<Value> = (0..2)
            .map(|index| {
                Value::from_json(serde_json::json!({
                    "meta": {"title": format!("Limited {index}")},
                    "data": [{"a": index}]
                }))
            })
            .collect();
        let pdfs = crate::api::generate_many(&payloads, 2, None).unwrap();
        assert_eq!(pdfs.len(), 2);
        assert!(pdfs.iter().all(|pdf| pdf.starts_with(b"%PDF-")));
        let stats = pdf_pool_stats();
        assert_eq!(stats.workers, 1, "{stats:?}");
        assert_eq!(stats.renders - before.renders, 2, "{stats:?}");
        assert!(stats.browser_launches - before.browser_launches <= 1, "{stats:?}");
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn pool_isolates_page_options() {
        let _cleanup = PoolCleanup;
        shutdown_pdf_pool();
        let html = "<html><body><p>format</p></body></html>";
        let a4 = PdfOptions::default();
        let letter = PdfOptions {
            format: PageFormat::Letter,
            ..PdfOptions::default()
        };
        let landscape = PdfOptions {
            landscape: true,
            ..PdfOptions::default()
        };
        let (a4, letter, landscape) = tokio::join!(
            render_html_to_pdf(html, &a4),
            render_html_to_pdf(html, &letter),
            render_html_to_pdf(html, &landscape)
        );
        let (a4_w, a4_h) = page_size(&a4.unwrap());
        let (letter_w, letter_h) = page_size(&letter.unwrap());
        let (landscape_w, landscape_h) = page_size(&landscape.unwrap());
        assert!((a4_w - 595.0).abs() < 3.0 && (a4_h - 842.0).abs() < 3.0, "{a4_w}x{a4_h}");
        assert!(
            (letter_w - 612.0).abs() < 3.0 && (letter_h - 792.0).abs() < 3.0,
            "{letter_w}x{letter_h}"
        );
        assert!(
            (landscape_w - 842.0).abs() < 3.0 && (landscape_h - 595.0).abs() < 3.0,
            "{landscape_w}x{landscape_h}"
        );
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn pool_recovers_after_a_timeout() {
        let _cleanup = PoolCleanup;
        shutdown_pdf_pool();
        let timeout = PdfOptions {
            timeout_ms: Some(1),
            ..PdfOptions::default()
        };
        let error = render_html_to_pdf("<html><body><p>timeout</p></body></html>", &timeout)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("timed out"), "{error}");
        let launches = pdf_pool_stats().browser_launches;
        let pdf = render_html_to_pdf("<html><body><p>after timeout</p></body></html>", &PdfOptions::default())
            .await
            .unwrap();
        assert!(pdf.starts_with(b"%PDF-"));
        let stats = pdf_pool_stats();
        assert!(stats.browser_launches <= launches + 1, "{stats:?}");
        assert_eq!(stats.in_flight, 0, "{stats:?}");
    }

    #[tokio::test]
    async fn profile_directories_are_removed() {
        let path = create_profile_dir().unwrap();
        std::fs::write(path.join("artifact"), b"x").unwrap();
        remove_profile(path.clone()).await;
        assert!(!path.exists());
        assert!(!profile_dirs_for_current_process().contains(&path));
    }

    #[test]
    fn outbound_policy_is_fail_closed() {
        let hosts = validate_allowed_hosts(&["Example.COM.".to_string()]).unwrap();
        assert_eq!(hosts, vec!["example.com".to_string()]);
        assert!(is_host_allowed("https://example.com/a.png", Some(&hosts)));
        assert!(!is_host_allowed("https://evil.example.com/a.png", Some(&hosts)));
        assert!(!is_host_allowed("http://example.com/a.png", None));
        assert!(is_host_allowed("data:image/png;base64,AA==", None));
        assert!(is_host_allowed("mailto:user@example.com", None));
        assert!(!is_host_allowed("not a url", None));
        assert!(validate_allowed_hosts(&["https://example.com".to_string()]).is_err());
        assert!(validate_allowed_hosts(&["*.example.com".to_string()]).is_err());
    }

    #[cfg(feature = "weasyprint-cli")]
    #[tokio::test]
    async fn weasyprint_rejections_are_fail_closed() {
        let base = PdfOptions {
            backend: PdfBackend::ExternalWeasyPrint,
            display_header_footer: false,
            ..PdfOptions::default()
        };
        let cases: Vec<(PdfOptions, &str, &str)> = vec![
            (base.clone(), "<html dir=\"rtl\"></html>", "right-to-left"),
            (
                PdfOptions {
                    allowed_hosts: Some(vec!["example.com".to_string()]),
                    ..base.clone()
                },
                "<html></html>",
                "allowed_hosts",
            ),
            (
                PdfOptions {
                    debug_dir: Some(std::env::temp_dir()),
                    ..base.clone()
                },
                "<html></html>",
                "debug_dir",
            ),
            (
                PdfOptions {
                    page_ranges: Some("1-2".to_string()),
                    ..base.clone()
                },
                "<html></html>",
                "page_ranges",
            ),
            (
                PdfOptions {
                    header_template: Some("header".to_string()),
                    ..base.clone()
                },
                "<html></html>",
                "header_template",
            ),
            (
                PdfOptions {
                    display_header_footer: true,
                    ..base.clone()
                },
                "<html></html>",
                "Playwright header/footer",
            ),
            (base.clone(), "<img src=\"https://example.com/x.png\">", "external resources"),
        ];
        for (options, html, expected) in cases {
            let error = render_weasyprint(html, &options).await.unwrap_err();
            assert!(error.to_string().contains(expected), "{expected}: {error}");
        }
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn cross_platform_smoke() {
        let _cleanup = PoolCleanup;
        let options = PdfOptions {
            format: PageFormat::Letter,
            ..PdfOptions::default()
        };
        let pdf = render_html_to_pdf("<!doctype html><html><body><h1>Cross-platform PDF</h1></body></html>", &options)
            .await
            .unwrap();
        assert!(pdf.starts_with(b"%PDF-"));
        assert!(pdf.len() > 1000);
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn renders_a_real_pdf() {
        let _cleanup = PoolCleanup;
        let options = PdfOptions::default();
        let pdf = render_html_to_pdf("<!doctype html><html><body><h1>Hello PDF</h1></body></html>", &options)
            .await
            .unwrap();
        assert!(pdf.starts_with(b"%PDF-"));
        assert!(pdf.len() > 1000);
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn pdf_page_format_is_applied() {
        let _cleanup = PoolCleanup;
        let options = PdfOptions {
            format: PageFormat::Letter,
            ..PdfOptions::default()
        };
        let pdf = render_html_to_pdf("<html><body><p>Letter</p></body></html>", &options)
            .await
            .unwrap();
        let document = lopdf::Document::load_mem(&pdf).unwrap();
        let pages = document.get_pages();
        assert_eq!(pages.len(), 1);
        let page_id = *pages.values().next().unwrap();
        let page = document.get_object(page_id).unwrap().as_dict().unwrap();
        let media_box = page.get(b"MediaBox").unwrap().as_array().unwrap();
        let width = media_box[2].as_float().unwrap();
        let height = media_box[3].as_float().unwrap();
        assert!((width - 612.0).abs() < 2.0, "width={width}");
        assert!((height - 792.0).abs() < 2.0, "height={height}");
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn debug_dir_writes_html_png_and_trace() {
        let _cleanup = PoolCleanup;
        let directory = tempfile::tempdir().unwrap();
        let options = PdfOptions {
            debug_dir: Some(directory.path().to_path_buf()),
            ..PdfOptions::default()
        };
        let pdf = render_html_to_pdf("<html><body><p>debug artifact</p></body></html>", &options)
            .await
            .unwrap();
        assert!(pdf.starts_with(b"%PDF-"));
        let html = std::fs::read_to_string(directory.path().join("report.html")).unwrap();
        assert!(html.contains("debug artifact"));
        let png = std::fs::read(directory.path().join("report.png")).unwrap();
        assert!(png.starts_with(b"\x89PNG"));
        let trace = std::fs::read_to_string(directory.path().join("trace.json")).unwrap();
        assert!(trace.trim_start().starts_with('['));
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn debug_dir_is_cleaned_after_render_failure() {
        let _cleanup = PoolCleanup;
        let directory = tempfile::tempdir().unwrap();
        let options = PdfOptions {
            debug_dir: Some(directory.path().to_path_buf()),
            timeout_ms: Some(1),
            ..PdfOptions::default()
        };
        let error = render_html_to_pdf("<html><body><p>failure</p></body></html>", &options)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("timed out"), "{error}");
        for name in ["report.html", "report.png", "trace.json"] {
            assert!(!directory.path().join(name).exists(), "{name} was not cleaned up");
        }
    }

    #[tokio::test]
    #[ignore = "requires a local Chromium/Chrome installation"]
    async fn network_allowlist_blocks_and_allows() {
        let _cleanup = PoolCleanup;
        use std::io::{Read, Write};
        use std::net::TcpListener;
        use std::sync::atomic::{AtomicUsize, Ordering};

        fn start_server(hits: Arc<AtomicUsize>) -> (u16, std::thread::JoinHandle<()>) {
            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
            let port = listener.local_addr().unwrap().port();
            listener.set_nonblocking(true).unwrap();
            let handle = std::thread::spawn(move || {
                let deadline = std::time::Instant::now() + Duration::from_secs(4);
                while std::time::Instant::now() < deadline {
                    match listener.accept() {
                        Ok((mut stream, _)) => {
                            hits.fetch_add(1, Ordering::SeqCst);
                            let mut buffer = [0u8; 1024];
                            let _ = stream.read(&mut buffer);
                            let _ = stream.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
                        }
                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                            std::thread::sleep(Duration::from_millis(10));
                        }
                        Err(_) => break,
                    }
                }
            });
            (port, handle)
        }

        let blocked_hits = Arc::new(AtomicUsize::new(0));
        let (port, server) = start_server(Arc::clone(&blocked_hits));
        let html = format!("<!doctype html><html><body><img src=\"http://127.0.0.1:{port}/x.png\"></body></html>");
        render_html_to_pdf(&html, &PdfOptions::default()).await.unwrap();
        server.join().unwrap();
        assert_eq!(blocked_hits.load(Ordering::SeqCst), 0);

        let allowed_hits = Arc::new(AtomicUsize::new(0));
        let (port, server) = start_server(Arc::clone(&allowed_hits));
        let html = format!("<!doctype html><html><body><img src=\"http://127.0.0.1:{port}/x.png\"></body></html>");
        let options = PdfOptions {
            allowed_hosts: Some(vec!["127.0.0.1".to_string()]),
            ..PdfOptions::default()
        };
        render_html_to_pdf(&html, &options).await.unwrap();
        server.join().unwrap();
        assert!(allowed_hits.load(Ordering::SeqCst) > 0);
    }
}