data-modelling-core 2.4.0

Core SDK library for model operations across platforms
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
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
//! PDF exporter with branding support
//!
//! Exports ODCS, ODPS, Knowledge Base articles, and Architecture Decision Records
//! to PDF format with customizable branding options.
//!
//! ## Features
//!
//! - Logo support (base64 encoded or URL)
//! - Customizable header and footer
//! - Brand color theming
//! - Page numbering
//! - Proper GitHub Flavored Markdown rendering
//!
//! ## WASM Compatibility
//!
//! This module is designed to work in both native and WASM environments
//! by generating PDF as base64-encoded bytes.

use crate::export::ExportError;
use crate::models::decision::Decision;
use crate::models::knowledge::KnowledgeArticle;
use chrono::Utc;
use serde::{Deserialize, Serialize};

/// Default logo URL for Open Data Modelling
const DEFAULT_LOGO_URL: &str = "https://opendatamodelling.com/logo.png";

/// Default copyright footer
const DEFAULT_COPYRIGHT: &str = "© opendatamodelling.com";

/// Branding configuration for PDF exports
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BrandingConfig {
    /// Logo as base64-encoded image data (PNG or JPEG)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logo_base64: Option<String>,

    /// Logo URL (alternative to base64)
    #[serde(default = "default_logo_url")]
    pub logo_url: Option<String>,

    /// Header text (appears at top of each page)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub header: Option<String>,

    /// Footer text (appears at bottom of each page)
    #[serde(default = "default_footer")]
    pub footer: Option<String>,

    /// Primary brand color in hex format (e.g., "#0066CC")
    #[serde(default = "default_brand_color")]
    pub brand_color: String,

    /// Company or organization name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub company_name: Option<String>,

    /// Include page numbers
    #[serde(default = "default_true")]
    pub show_page_numbers: bool,

    /// Include generation timestamp
    #[serde(default = "default_true")]
    pub show_timestamp: bool,

    /// Font size for body text (in points)
    #[serde(default = "default_font_size")]
    pub font_size: u8,

    /// Page size (A4 or Letter)
    #[serde(default)]
    pub page_size: PageSize,
}

fn default_logo_url() -> Option<String> {
    Some(DEFAULT_LOGO_URL.to_string())
}

fn default_footer() -> Option<String> {
    Some(DEFAULT_COPYRIGHT.to_string())
}

fn default_brand_color() -> String {
    "#0066CC".to_string()
}

fn default_true() -> bool {
    true
}

fn default_font_size() -> u8 {
    11
}

impl Default for BrandingConfig {
    fn default() -> Self {
        Self {
            logo_base64: None,
            logo_url: default_logo_url(),
            header: None,
            footer: default_footer(),
            brand_color: default_brand_color(),
            company_name: None,
            show_page_numbers: default_true(),
            show_timestamp: default_true(),
            font_size: default_font_size(),
            page_size: PageSize::default(),
        }
    }
}

/// Page size options
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PageSize {
    /// A4 paper size (210 x 297 mm)
    #[default]
    A4,
    /// US Letter size (8.5 x 11 inches)
    Letter,
}

impl PageSize {
    /// Get page dimensions in millimeters (width, height)
    pub fn dimensions_mm(&self) -> (f64, f64) {
        match self {
            PageSize::A4 => (210.0, 297.0),
            PageSize::Letter => (215.9, 279.4),
        }
    }
}

/// PDF document content types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
#[allow(clippy::large_enum_variant)]
pub enum PdfContent {
    /// Architecture Decision Record
    Decision(Decision),
    /// Knowledge Base article
    Knowledge(KnowledgeArticle),
    /// Raw markdown content
    Markdown { title: String, content: String },
}

/// Result of PDF export operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PdfExportResult {
    /// PDF content as base64-encoded bytes
    pub pdf_base64: String,
    /// Filename suggestion
    pub filename: String,
    /// Number of pages
    pub page_count: u32,
    /// Document title
    pub title: String,
}

/// PDF exporter with branding support
pub struct PdfExporter {
    branding: BrandingConfig,
}

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

impl PdfExporter {
    /// Create a new PDF exporter with default branding
    pub fn new() -> Self {
        Self {
            branding: BrandingConfig::default(),
        }
    }

    /// Create a new PDF exporter with custom branding
    pub fn with_branding(branding: BrandingConfig) -> Self {
        Self { branding }
    }

    /// Update branding configuration
    pub fn set_branding(&mut self, branding: BrandingConfig) {
        self.branding = branding;
    }

    /// Get current branding configuration
    pub fn branding(&self) -> &BrandingConfig {
        &self.branding
    }

    /// Export a Decision to PDF
    pub fn export_decision(&self, decision: &Decision) -> Result<PdfExportResult, ExportError> {
        let title = format!("{}: {}", decision.formatted_number(), decision.title);
        let markdown = self.decision_to_markdown(decision);
        self.generate_pdf(
            &title,
            &markdown,
            &decision.markdown_filename().replace(".md", ".pdf"),
            "Decision Record",
        )
    }

    /// Export a Knowledge article to PDF
    pub fn export_knowledge(
        &self,
        article: &KnowledgeArticle,
    ) -> Result<PdfExportResult, ExportError> {
        let title = format!("{}: {}", article.formatted_number(), article.title);
        let markdown = self.knowledge_to_markdown(article);
        self.generate_pdf(
            &title,
            &markdown,
            &article.markdown_filename().replace(".md", ".pdf"),
            "Knowledge Base",
        )
    }

    /// Export raw markdown content to PDF
    pub fn export_markdown(
        &self,
        title: &str,
        content: &str,
        filename: &str,
    ) -> Result<PdfExportResult, ExportError> {
        self.generate_pdf(title, content, filename, "Document")
    }

    /// Export an ODCS Data Contract (Table) to PDF
    pub fn export_table(
        &self,
        table: &crate::models::Table,
    ) -> Result<PdfExportResult, ExportError> {
        let title = table.name.clone();
        let markdown = self.table_to_markdown(table);
        let filename = format!("{}.pdf", table.name.to_lowercase().replace(' ', "_"));
        self.generate_pdf(&title, &markdown, &filename, "Data Contract")
    }

    /// Export an ODPS Data Product to PDF
    pub fn export_data_product(
        &self,
        product: &crate::models::odps::ODPSDataProduct,
    ) -> Result<PdfExportResult, ExportError> {
        let title = product.name.clone().unwrap_or_else(|| product.id.clone());
        let markdown = self.data_product_to_markdown(product);
        let filename = format!(
            "{}.pdf",
            title.to_lowercase().replace(' ', "_").replace('/', "-")
        );
        self.generate_pdf(&title, &markdown, &filename, "Data Product")
    }

    /// Export a CADS Asset to PDF
    pub fn export_cads_asset(
        &self,
        asset: &crate::models::cads::CADSAsset,
    ) -> Result<PdfExportResult, ExportError> {
        let title = asset.name.clone();
        let markdown = self.cads_asset_to_markdown(asset);
        let filename = format!(
            "{}.pdf",
            title.to_lowercase().replace(' ', "_").replace('/', "-")
        );
        self.generate_pdf(&title, &markdown, &filename, "Compute Asset")
    }

    // ============================================================================
    // Public Markdown Generation Methods (for WASM bindings)
    // ============================================================================

    /// Convert an ODCS Table (Data Contract) to Markdown format.
    ///
    /// This is a public wrapper for use by WASM bindings.
    pub fn table_to_markdown_public(&self, table: &crate::models::Table) -> String {
        self.table_to_markdown(table)
    }

    /// Convert an ODPS Data Product to Markdown format.
    ///
    /// This is a public wrapper for use by WASM bindings.
    pub fn data_product_to_markdown_public(
        &self,
        product: &crate::models::odps::ODPSDataProduct,
    ) -> String {
        self.data_product_to_markdown(product)
    }

    /// Convert a CADS Asset to Markdown format.
    ///
    /// This is a public wrapper for use by WASM bindings.
    pub fn cads_asset_to_markdown_public(&self, asset: &crate::models::cads::CADSAsset) -> String {
        self.cads_asset_to_markdown(asset)
    }

    /// Convert Decision to properly formatted GFM markdown for PDF rendering
    /// Note: Logo and copyright footer are rendered as part of the PDF template,
    /// not in the markdown content.
    fn decision_to_markdown(&self, decision: &Decision) -> String {
        use crate::models::decision::DecisionStatus;

        let mut md = String::new();

        // Main title
        md.push_str(&format!(
            "# {}: {}\n\n",
            decision.formatted_number(),
            decision.title
        ));

        // Metadata table
        let status_text = match decision.status {
            DecisionStatus::Draft => "Draft",
            DecisionStatus::Proposed => "Proposed",
            DecisionStatus::Accepted => "Accepted",
            DecisionStatus::Deprecated => "Deprecated",
            DecisionStatus::Superseded => "Superseded",
            DecisionStatus::Rejected => "Rejected",
        };

        md.push_str("| Property | Value |\n");
        md.push_str("|----------|-------|\n");
        md.push_str(&format!("| **Status** | {} |\n", status_text));
        md.push_str(&format!("| **Category** | {} |\n", decision.category));
        md.push_str(&format!(
            "| **Date** | {} |\n",
            decision.date.format("%Y-%m-%d")
        ));

        if !decision.authors.is_empty() {
            md.push_str(&format!(
                "| **Authors** | {} |\n",
                decision.authors.join(", ")
            ));
        }

        if let Some(domain) = &decision.domain {
            md.push_str(&format!("| **Domain** | {} |\n", domain));
        }

        md.push_str("\n---\n\n");

        // Context section
        md.push_str("## Context\n\n");
        md.push_str(&decision.context);
        md.push_str("\n\n");

        // Decision section
        md.push_str("## Decision\n\n");
        md.push_str(&decision.decision);
        md.push_str("\n\n");

        // Consequences section
        if let Some(consequences) = &decision.consequences {
            md.push_str("## Consequences\n\n");
            md.push_str(consequences);
            md.push_str("\n\n");
        }

        // Stakeholders section (if present)
        if !decision.consulted.is_empty() || !decision.informed.is_empty() {
            md.push_str("## Stakeholders\n\n");
            md.push_str("| Role | Participants |\n");
            md.push_str("|------|-------------|\n");

            if !decision.deciders.is_empty() {
                md.push_str(&format!(
                    "| **Deciders** | {} |\n",
                    decision.deciders.join(", ")
                ));
            }
            if !decision.consulted.is_empty() {
                md.push_str(&format!(
                    "| **Consulted** | {} |\n",
                    decision.consulted.join(", ")
                ));
            }
            if !decision.informed.is_empty() {
                md.push_str(&format!(
                    "| **Informed** | {} |\n",
                    decision.informed.join(", ")
                ));
            }
            md.push('\n');
        }

        // Decision Drivers (if any)
        if !decision.drivers.is_empty() {
            md.push_str("## Decision Drivers\n\n");
            for driver in &decision.drivers {
                let priority = match driver.priority {
                    Some(crate::models::decision::DriverPriority::High) => " *(High Priority)*",
                    Some(crate::models::decision::DriverPriority::Medium) => " *(Medium Priority)*",
                    Some(crate::models::decision::DriverPriority::Low) => " *(Low Priority)*",
                    None => "",
                };
                md.push_str(&format!("- {}{}\n", driver.description, priority));
            }
            md.push('\n');
        }

        // Options Considered (if any) - with side-by-side Pros/Cons
        if !decision.options.is_empty() {
            md.push_str("## Options Considered\n\n");
            for (i, option) in decision.options.iter().enumerate() {
                let selected_marker = if option.selected {
                    " **(Selected)**"
                } else {
                    ""
                };
                md.push_str(&format!(
                    "### Option {}: {}{}\n\n",
                    i + 1,
                    option.name,
                    selected_marker
                ));

                if let Some(desc) = &option.description {
                    md.push_str(&format!("{}\n\n", desc));
                }

                // Render Pros and Cons side by side using a table
                if !option.pros.is_empty() || !option.cons.is_empty() {
                    md.push_str("| Pros | Cons |\n");
                    md.push_str("|------|------|\n");

                    let max_rows = std::cmp::max(option.pros.len(), option.cons.len());
                    for row in 0..max_rows {
                        let pro = option
                            .pros
                            .get(row)
                            .map(|s| format!("+ {}", s))
                            .unwrap_or_default();
                        let con = option
                            .cons
                            .get(row)
                            .map(|s| format!("- {}", s))
                            .unwrap_or_default();
                        md.push_str(&format!("| {} | {} |\n", pro, con));
                    }
                    md.push('\n');
                }
            }
        }

        // Linked Assets (if any)
        if !decision.linked_assets.is_empty() {
            md.push_str("## Linked Assets\n\n");
            md.push_str("| Asset | Type |\n");
            md.push_str("|-------|------|\n");
            for asset in &decision.linked_assets {
                md.push_str(&format!(
                    "| {} | {} |\n",
                    asset.asset_name, asset.asset_type
                ));
            }
            md.push('\n');
        }

        // Notes (if present)
        if let Some(notes) = &decision.notes {
            md.push_str("## Notes\n\n");
            md.push_str(notes);
            md.push_str("\n\n");
        }

        // Horizontal rule before footer
        md.push_str("---\n\n");

        // Tags
        if !decision.tags.is_empty() {
            let tag_strings: Vec<String> =
                decision.tags.iter().map(|t| format!("`{}`", t)).collect();
            md.push_str(&format!("**Tags:** {}\n\n", tag_strings.join(" ")));
        }

        // Horizontal rule
        md.push_str("---\n\n");

        // Timestamps
        md.push_str(&format!(
            "*Created: {} | Last Updated: {}*\n\n",
            decision.created_at.format("%Y-%m-%d %H:%M UTC"),
            decision.updated_at.format("%Y-%m-%d %H:%M UTC")
        ));

        md
    }

    /// Convert Knowledge article to properly formatted GFM markdown for PDF rendering
    /// Note: Logo and copyright footer are rendered as part of the PDF template,
    /// not in the markdown content.
    fn knowledge_to_markdown(&self, article: &KnowledgeArticle) -> String {
        use crate::models::knowledge::{KnowledgeStatus, KnowledgeType};

        let mut md = String::new();

        // Main title
        md.push_str(&format!(
            "# {}: {}\n\n",
            article.formatted_number(),
            article.title
        ));

        // Metadata table
        let status_text = match article.status {
            KnowledgeStatus::Draft => "Draft",
            KnowledgeStatus::Review => "Under Review",
            KnowledgeStatus::Published => "Published",
            KnowledgeStatus::Archived => "Archived",
            KnowledgeStatus::Deprecated => "Deprecated",
        };

        let type_text = match article.article_type {
            KnowledgeType::Guide => "Guide",
            KnowledgeType::Standard => "Standard",
            KnowledgeType::Reference => "Reference",
            KnowledgeType::HowTo => "How-To",
            KnowledgeType::Troubleshooting => "Troubleshooting",
            KnowledgeType::Policy => "Policy",
            KnowledgeType::Template => "Template",
            KnowledgeType::Concept => "Concept",
            KnowledgeType::Runbook => "Runbook",
            KnowledgeType::Tutorial => "Tutorial",
            KnowledgeType::Glossary => "Glossary",
        };

        md.push_str("| Property | Value |\n");
        md.push_str("|----------|-------|\n");
        md.push_str(&format!("| **Type** | {} |\n", type_text));
        md.push_str(&format!("| **Status** | {} |\n", status_text));

        if let Some(domain) = &article.domain {
            md.push_str(&format!("| **Domain** | {} |\n", domain));
        }

        if !article.authors.is_empty() {
            md.push_str(&format!(
                "| **Authors** | {} |\n",
                article.authors.join(", ")
            ));
        }

        if let Some(skill_level) = &article.skill_level {
            md.push_str(&format!("| **Skill Level** | {} |\n", skill_level));
        }

        if !article.audience.is_empty() {
            md.push_str(&format!(
                "| **Audience** | {} |\n",
                article.audience.join(", ")
            ));
        }

        md.push_str("\n---\n\n");

        // Summary section
        md.push_str("## Summary\n\n");
        md.push_str(&article.summary);
        md.push_str("\n\n---\n\n");

        // Content section (the main article content - already in markdown)
        md.push_str(&article.content);
        md.push_str("\n\n");

        // Related Articles (if any)
        if !article.related_articles.is_empty() {
            md.push_str("---\n\n");
            md.push_str("## Related Articles\n\n");
            md.push_str("| Article | Relationship |\n");
            md.push_str("|---------|-------------|\n");
            for related in &article.related_articles {
                md.push_str(&format!(
                    "| {}: {} | {} |\n",
                    related.article_number, related.title, related.relationship
                ));
            }
            md.push('\n');
        }

        // Notes (if present)
        if let Some(notes) = &article.notes {
            md.push_str("---\n\n");
            md.push_str("## Notes\n\n");
            md.push_str(notes);
            md.push_str("\n\n");
        }

        // Horizontal rule before footer
        md.push_str("---\n\n");

        // Tags
        if !article.tags.is_empty() {
            let tag_strings: Vec<String> =
                article.tags.iter().map(|t| format!("`{}`", t)).collect();
            md.push_str(&format!("**Tags:** {}\n\n", tag_strings.join(" ")));
        }

        // Horizontal rule
        md.push_str("---\n\n");

        // Timestamps
        md.push_str(&format!(
            "*Created: {} | Last Updated: {}*\n\n",
            article.created_at.format("%Y-%m-%d %H:%M UTC"),
            article.updated_at.format("%Y-%m-%d %H:%M UTC")
        ));

        md
    }

    /// Convert Table (ODCS Data Contract) to properly formatted GFM markdown for PDF rendering
    fn table_to_markdown(&self, table: &crate::models::Table) -> String {
        let mut md = String::new();

        // Main title
        md.push_str(&format!("# {}\n\n", table.name));

        // Metadata table
        md.push_str("| Property | Value |\n");
        md.push_str("|----------|-------|\n");

        if let Some(db_type) = &table.database_type {
            md.push_str(&format!("| **Database Type** | {:?} |\n", db_type));
        }

        if let Some(catalog) = &table.catalog_name {
            md.push_str(&format!("| **Catalog** | {} |\n", catalog));
        }

        if let Some(schema) = &table.schema_name {
            md.push_str(&format!("| **Schema** | {} |\n", schema));
        }

        if let Some(owner) = &table.owner {
            md.push_str(&format!("| **Owner** | {} |\n", owner));
        }

        if !table.medallion_layers.is_empty() {
            let layers: Vec<String> = table
                .medallion_layers
                .iter()
                .map(|l| format!("{:?}", l))
                .collect();
            md.push_str(&format!(
                "| **Medallion Layers** | {} |\n",
                layers.join(", ")
            ));
        }

        if let Some(scd) = &table.scd_pattern {
            md.push_str(&format!("| **SCD Pattern** | {:?} |\n", scd));
        }

        if let Some(dv) = &table.data_vault_classification {
            md.push_str(&format!("| **Data Vault** | {:?} |\n", dv));
        }

        if let Some(level) = &table.modeling_level {
            md.push_str(&format!("| **Modeling Level** | {:?} |\n", level));
        }

        if let Some(infra) = &table.infrastructure_type {
            md.push_str(&format!("| **Infrastructure** | {:?} |\n", infra));
        }

        md.push_str(&format!("| **Columns** | {} |\n", table.columns.len()));

        md.push_str("\n---\n\n");

        // Notes section
        if let Some(notes) = &table.notes {
            md.push_str("## Description\n\n");
            md.push_str(notes);
            md.push_str("\n\n---\n\n");
        }

        // Columns section
        md.push_str("## Columns\n\n");
        md.push_str("| Column | Type | Nullable | PK | Description |\n");
        md.push_str("|--------|------|----------|----|--------------|\n");

        for col in &table.columns {
            let nullable = if col.nullable { "Yes" } else { "No" };
            let pk = if col.primary_key { "Yes" } else { "" };
            let desc = col
                .description
                .chars()
                .take(50)
                .collect::<String>()
                .replace('|', "/");
            let desc_display = if col.description.len() > 50 {
                format!("{}...", desc)
            } else {
                desc
            };

            md.push_str(&format!(
                "| {} | {} | {} | {} | {} |\n",
                col.name, col.data_type, nullable, pk, desc_display
            ));
        }
        md.push('\n');

        // Column Details (for columns with descriptions, business names, constraints, etc.)
        let cols_with_details: Vec<_> = table
            .columns
            .iter()
            .filter(|c| {
                !c.description.is_empty()
                    || c.business_name.is_some()
                    || !c.enum_values.is_empty()
                    || c.physical_type.is_some()
                    || c.unique
                    || c.partitioned
                    || c.classification.is_some()
                    || c.critical_data_element
                    || c.logical_type_options.is_some()
                    || !c.transform_source_objects.is_empty()
                    || c.transform_logic.is_some()
                    || c.transform_description.is_some()
                    || !c.relationships.is_empty()
                    || c.foreign_key.is_some()
                    || !c.authoritative_definitions.is_empty()
                    || !c.quality.is_empty()
                    || !c.tags.is_empty()
                    || c.secondary_key
                    || c.composite_key.is_some()
                    || c.primary_key_position.is_some()
                    || c.partition_key_position.is_some()
                    || !c.constraints.is_empty()
                    || c.encrypted_name.is_some()
                    || c.physical_name.is_some()
            })
            .collect();

        if !cols_with_details.is_empty() {
            md.push_str("## Column Details\n\n");
            for col in cols_with_details {
                md.push_str(&format!("### {}\n\n", col.name));

                if let Some(biz_name) = &col.business_name {
                    md.push_str(&format!("**Business Name:** {}\n\n", biz_name));
                }

                if !col.description.is_empty() {
                    md.push_str(&format!("{}\n\n", col.description));
                }

                // Physical type if different from logical
                if let Some(phys) = &col.physical_type
                    && phys != &col.data_type
                {
                    md.push_str(&format!("**Physical Type:** {}\n\n", phys));
                }

                // Physical name if different from column name
                if let Some(phys_name) = &col.physical_name
                    && phys_name != &col.name
                {
                    md.push_str(&format!("**Physical Name:** {}\n\n", phys_name));
                }

                // Key information
                if col.primary_key
                    && let Some(pos) = col.primary_key_position
                {
                    md.push_str(&format!("**Primary Key Position:** {}\n\n", pos));
                }

                if col.secondary_key {
                    md.push_str("**Secondary Key:** Yes\n\n");
                }

                if let Some(composite) = &col.composite_key {
                    md.push_str(&format!("**Composite Key:** {}\n\n", composite));
                }

                // Partitioning
                if col.partitioned
                    && let Some(pos) = col.partition_key_position
                {
                    md.push_str(&format!("**Partition Key Position:** {}\n\n", pos));
                }

                // Constraints
                let mut constraint_flags = Vec::new();
                if col.unique {
                    constraint_flags.push("Unique");
                }
                if col.partitioned && col.partition_key_position.is_none() {
                    constraint_flags.push("Partitioned");
                }
                if col.clustered {
                    constraint_flags.push("Clustered");
                }
                if col.critical_data_element {
                    constraint_flags.push("Critical Data Element");
                }
                if !constraint_flags.is_empty() {
                    md.push_str(&format!(
                        "**Constraints:** {}\n\n",
                        constraint_flags.join(", ")
                    ));
                }

                // Additional constraints (CHECK, etc.)
                if !col.constraints.is_empty() {
                    md.push_str("**Additional Constraints:**\n");
                    for constraint in &col.constraints {
                        md.push_str(&format!("- {}\n", constraint));
                    }
                    md.push('\n');
                }

                // Classification
                if let Some(class) = &col.classification {
                    md.push_str(&format!("**Classification:** {}\n\n", class));
                }

                // Encrypted name
                if let Some(enc_name) = &col.encrypted_name {
                    md.push_str(&format!("**Encrypted Name:** {}\n\n", enc_name));
                }

                // Logical Type Options
                if let Some(opts) = &col.logical_type_options
                    && !opts.is_empty()
                {
                    md.push_str("**Type Options:**\n");
                    if let Some(min_len) = opts.min_length {
                        md.push_str(&format!("- Min Length: {}\n", min_len));
                    }
                    if let Some(max_len) = opts.max_length {
                        md.push_str(&format!("- Max Length: {}\n", max_len));
                    }
                    if let Some(pattern) = &opts.pattern {
                        md.push_str(&format!("- Pattern: `{}`\n", pattern));
                    }
                    if let Some(format) = &opts.format {
                        md.push_str(&format!("- Format: {}\n", format));
                    }
                    if let Some(min) = &opts.minimum {
                        md.push_str(&format!("- Minimum: {}\n", min));
                    }
                    if let Some(max) = &opts.maximum {
                        md.push_str(&format!("- Maximum: {}\n", max));
                    }
                    if let Some(exc_min) = &opts.exclusive_minimum {
                        md.push_str(&format!("- Exclusive Minimum: {}\n", exc_min));
                    }
                    if let Some(exc_max) = &opts.exclusive_maximum {
                        md.push_str(&format!("- Exclusive Maximum: {}\n", exc_max));
                    }
                    if let Some(prec) = opts.precision {
                        md.push_str(&format!("- Precision: {}\n", prec));
                    }
                    if let Some(scale) = opts.scale {
                        md.push_str(&format!("- Scale: {}\n", scale));
                    }
                    md.push('\n');
                }

                // Enum values
                if !col.enum_values.is_empty() {
                    md.push_str("**Allowed Values:**\n");
                    for val in &col.enum_values {
                        md.push_str(&format!("- `{}`\n", val));
                    }
                    md.push('\n');
                }

                // Examples
                if !col.examples.is_empty() {
                    let examples_str: Vec<String> =
                        col.examples.iter().map(|v| v.to_string()).collect();
                    md.push_str(&format!("**Examples:** {}\n\n", examples_str.join(", ")));
                }

                // Default value
                if let Some(default) = &col.default_value {
                    md.push_str(&format!("**Default:** {}\n\n", default));
                }

                // Transformation Metadata
                if !col.transform_source_objects.is_empty()
                    || col.transform_logic.is_some()
                    || col.transform_description.is_some()
                {
                    md.push_str("**Transformation:**\n");
                    if !col.transform_source_objects.is_empty() {
                        md.push_str(&format!(
                            "- Source Objects: {}\n",
                            col.transform_source_objects.join(", ")
                        ));
                    }
                    if let Some(logic) = &col.transform_logic {
                        md.push_str(&format!("- Logic: `{}`\n", logic));
                    }
                    if let Some(desc) = &col.transform_description {
                        md.push_str(&format!("- Description: {}\n", desc));
                    }
                    md.push('\n');
                }

                // Relationships
                if !col.relationships.is_empty() {
                    md.push_str("**Relationships:**\n");
                    for rel in &col.relationships {
                        md.push_str(&format!("- {} → {}\n", rel.relationship_type, rel.to));
                    }
                    md.push('\n');
                }

                // Foreign Key (legacy)
                if let Some(fk) = &col.foreign_key {
                    md.push_str(&format!(
                        "**Foreign Key:** {}.{}\n\n",
                        fk.table_id, fk.column_name
                    ));
                }

                // Authoritative Definitions
                if !col.authoritative_definitions.is_empty() {
                    md.push_str("**Authoritative Definitions:**\n");
                    for def in &col.authoritative_definitions {
                        md.push_str(&format!("- {} - {}\n", def.definition_type, def.url));
                    }
                    md.push('\n');
                }

                // Column-level Quality Rules
                if !col.quality.is_empty() {
                    md.push_str("**Quality Rules:**\n");
                    for rule in &col.quality {
                        let rule_parts: Vec<String> =
                            rule.iter().map(|(k, v)| format!("{}: {}", k, v)).collect();
                        md.push_str(&format!("- {}\n", rule_parts.join(", ")));
                    }
                    md.push('\n');
                }

                // Column-level Tags
                if !col.tags.is_empty() {
                    let tag_strings: Vec<String> =
                        col.tags.iter().map(|t| format!("`{}`", t)).collect();
                    md.push_str(&format!("**Tags:** {}\n\n", tag_strings.join(" ")));
                }
            }
        }

        // SLA section
        if let Some(sla) = &table.sla
            && !sla.is_empty()
        {
            md.push_str("---\n\n## Service Level Agreements\n\n");
            md.push_str("| Property | Value | Unit | Description |\n");
            md.push_str("|----------|-------|------|-------------|\n");
            for sla_prop in sla {
                let desc = sla_prop
                    .description
                    .as_deref()
                    .unwrap_or("")
                    .replace('|', "/");
                md.push_str(&format!(
                    "| {} | {} | {} | {} |\n",
                    sla_prop.property, sla_prop.value, sla_prop.unit, desc
                ));
            }
            md.push('\n');
        }

        // Contact Details
        if let Some(contact) = &table.contact_details {
            md.push_str("---\n\n## Contact Information\n\n");
            if let Some(name) = &contact.name {
                md.push_str(&format!("- **Name:** {}\n", name));
            }
            if let Some(email) = &contact.email {
                md.push_str(&format!("- **Email:** {}\n", email));
            }
            if let Some(role) = &contact.role {
                md.push_str(&format!("- **Role:** {}\n", role));
            }
            if let Some(phone) = &contact.phone {
                md.push_str(&format!("- **Phone:** {}\n", phone));
            }
            md.push('\n');
        }

        // Quality Rules
        if !table.quality.is_empty() {
            md.push_str("---\n\n## Quality Rules\n\n");
            for (i, rule) in table.quality.iter().enumerate() {
                md.push_str(&format!("**Rule {}:**\n", i + 1));
                for (key, value) in rule {
                    md.push_str(&format!("- {}: {}\n", key, value));
                }
                md.push('\n');
            }
        }

        // ODCS Metadata (legacy format fields preserved from import)
        if !table.odcl_metadata.is_empty() {
            md.push_str("---\n\n## ODCS Contract Metadata\n\n");
            // Sort keys for consistent output
            let mut keys: Vec<_> = table.odcl_metadata.keys().collect();
            keys.sort();
            for key in keys {
                if let Some(value) = table.odcl_metadata.get(key) {
                    // Format the value based on its type
                    let formatted = match value {
                        serde_json::Value::String(s) => s.clone(),
                        serde_json::Value::Array(arr) => {
                            let items: Vec<String> = arr.iter().map(|v| v.to_string()).collect();
                            items.join(", ")
                        }
                        serde_json::Value::Object(_) => {
                            // For nested objects, show as formatted JSON-like structure
                            serde_json::to_string_pretty(value)
                                .unwrap_or_else(|_| value.to_string())
                        }
                        _ => value.to_string(),
                    };
                    md.push_str(&format!("- **{}:** {}\n", key, formatted));
                }
            }
            md.push('\n');
        }

        // Tags
        if !table.tags.is_empty() {
            md.push_str("---\n\n");
            let tag_strings: Vec<String> = table.tags.iter().map(|t| format!("`{}`", t)).collect();
            md.push_str(&format!("**Tags:** {}\n\n", tag_strings.join(" ")));
        }

        // Timestamps
        md.push_str("---\n\n");
        md.push_str(&format!(
            "*Created: {} | Last Updated: {}*\n\n",
            table.created_at.format("%Y-%m-%d %H:%M UTC"),
            table.updated_at.format("%Y-%m-%d %H:%M UTC")
        ));

        md
    }

    /// Convert ODPS Data Product to properly formatted GFM markdown for PDF rendering
    fn data_product_to_markdown(&self, product: &crate::models::odps::ODPSDataProduct) -> String {
        use crate::models::odps::ODPSStatus;

        let mut md = String::new();

        // Main title
        let title = product.name.as_deref().unwrap_or(&product.id);
        md.push_str(&format!("# {}\n\n", title));

        // Metadata table
        let status_text = match product.status {
            ODPSStatus::Proposed => "Proposed",
            ODPSStatus::Draft => "Draft",
            ODPSStatus::Active => "Active",
            ODPSStatus::Deprecated => "Deprecated",
            ODPSStatus::Retired => "Retired",
        };

        md.push_str("| Property | Value |\n");
        md.push_str("|----------|-------|\n");
        md.push_str(&format!("| **ID** | {} |\n", product.id));
        md.push_str(&format!("| **Status** | {} |\n", status_text));
        md.push_str(&format!("| **API Version** | {} |\n", product.api_version));

        if let Some(version) = &product.version {
            md.push_str(&format!("| **Version** | {} |\n", version));
        }

        if let Some(domain) = &product.domain {
            md.push_str(&format!("| **Domain** | {} |\n", domain));
        }

        if let Some(tenant) = &product.tenant {
            md.push_str(&format!("| **Tenant** | {} |\n", tenant));
        }

        md.push_str("\n---\n\n");

        // Description section
        if let Some(desc) = &product.description {
            md.push_str("## Description\n\n");
            if let Some(purpose) = &desc.purpose {
                md.push_str(&format!("**Purpose:** {}\n\n", purpose));
            }
            if let Some(usage) = &desc.usage {
                md.push_str(&format!("**Usage:** {}\n\n", usage));
            }
            if let Some(limitations) = &desc.limitations {
                md.push_str(&format!("**Limitations:** {}\n\n", limitations));
            }
            md.push_str("---\n\n");
        }

        // Input Ports
        if let Some(input_ports) = &product.input_ports
            && !input_ports.is_empty()
        {
            md.push_str("## Input Ports\n\n");
            md.push_str("| Name | Version | Contract ID |\n");
            md.push_str("|------|---------|-------------|\n");
            for port in input_ports {
                md.push_str(&format!(
                    "| {} | {} | {} |\n",
                    port.name, port.version, port.contract_id
                ));
            }
            md.push('\n');
        }

        // Output Ports
        if let Some(output_ports) = &product.output_ports
            && !output_ports.is_empty()
        {
            md.push_str("## Output Ports\n\n");
            md.push_str("| Name | Version | Type | Contract ID |\n");
            md.push_str("|------|---------|------|-------------|\n");
            for port in output_ports {
                let port_type = port.r#type.as_deref().unwrap_or("-");
                let contract = port.contract_id.as_deref().unwrap_or("-");
                md.push_str(&format!(
                    "| {} | {} | {} | {} |\n",
                    port.name, port.version, port_type, contract
                ));
            }
            md.push('\n');

            // Output port details
            for port in output_ports {
                if port.description.is_some()
                    || port.sbom.is_some()
                    || port.input_contracts.is_some()
                {
                    md.push_str(&format!("### {}\n\n", port.name));
                    if let Some(desc) = &port.description {
                        md.push_str(&format!("{}\n\n", desc));
                    }
                    if let Some(sbom) = &port.sbom
                        && !sbom.is_empty()
                    {
                        md.push_str("**SBOM:**\n");
                        for s in sbom {
                            let stype = s.r#type.as_deref().unwrap_or("unknown");
                            md.push_str(&format!("- {} ({})\n", s.url, stype));
                        }
                        md.push('\n');
                    }
                    if let Some(contracts) = &port.input_contracts
                        && !contracts.is_empty()
                    {
                        md.push_str("**Input Contracts:**\n");
                        for c in contracts {
                            md.push_str(&format!("- {} v{}\n", c.id, c.version));
                        }
                        md.push('\n');
                    }
                }
            }
        }

        // Management Ports
        if let Some(mgmt_ports) = &product.management_ports
            && !mgmt_ports.is_empty()
        {
            md.push_str("## Management Ports\n\n");
            md.push_str("| Name | Type | Content |\n");
            md.push_str("|------|------|--------|\n");
            for port in mgmt_ports {
                let port_type = port.r#type.as_deref().unwrap_or("-");
                md.push_str(&format!(
                    "| {} | {} | {} |\n",
                    port.name, port_type, port.content
                ));
            }
            md.push('\n');
        }

        // Support Channels
        if let Some(support) = &product.support
            && !support.is_empty()
        {
            md.push_str("## Support Channels\n\n");
            md.push_str("| Channel | URL | Description |\n");
            md.push_str("|---------|-----|-------------|\n");
            for s in support {
                let desc = s.description.as_deref().unwrap_or("-").replace('|', "/");
                md.push_str(&format!("| {} | {} | {} |\n", s.channel, s.url, desc));
            }
            md.push('\n');
        }

        // Team
        if let Some(team) = &product.team {
            md.push_str("## Team\n\n");
            if let Some(name) = &team.name {
                md.push_str(&format!("**Team Name:** {}\n\n", name));
            }
            if let Some(desc) = &team.description {
                md.push_str(&format!("{}\n\n", desc));
            }
            if let Some(members) = &team.members
                && !members.is_empty()
            {
                md.push_str("### Team Members\n\n");
                md.push_str("| Username | Name | Role |\n");
                md.push_str("|----------|------|------|\n");
                for member in members {
                    let name = member.name.as_deref().unwrap_or("-");
                    let role = member.role.as_deref().unwrap_or("-");
                    md.push_str(&format!("| {} | {} | {} |\n", member.username, name, role));
                }
                md.push('\n');
            }
        }

        // Tags
        if !product.tags.is_empty() {
            md.push_str("---\n\n");
            let tag_strings: Vec<String> =
                product.tags.iter().map(|t| format!("`{}`", t)).collect();
            md.push_str(&format!("**Tags:** {}\n\n", tag_strings.join(" ")));
        }

        // Timestamps
        if product.created_at.is_some() || product.updated_at.is_some() {
            md.push_str("---\n\n");
            if let Some(created) = &product.created_at {
                md.push_str(&format!(
                    "*Created: {}",
                    created.format("%Y-%m-%d %H:%M UTC")
                ));
                if let Some(updated) = &product.updated_at {
                    md.push_str(&format!(
                        " | Last Updated: {}",
                        updated.format("%Y-%m-%d %H:%M UTC")
                    ));
                }
                md.push_str("*\n\n");
            } else if let Some(updated) = &product.updated_at {
                md.push_str(&format!(
                    "*Last Updated: {}*\n\n",
                    updated.format("%Y-%m-%d %H:%M UTC")
                ));
            }
        }

        md
    }

    /// Convert CADS Asset to properly formatted GFM markdown for PDF rendering
    fn cads_asset_to_markdown(&self, asset: &crate::models::cads::CADSAsset) -> String {
        use crate::models::cads::{CADSKind, CADSStatus};

        let mut md = String::new();

        // Main title
        md.push_str(&format!("# {}\n\n", asset.name));

        // Metadata table
        let kind_text = match asset.kind {
            CADSKind::AIModel => "AI Model",
            CADSKind::MLPipeline => "ML Pipeline",
            CADSKind::Application => "Application",
            CADSKind::DataPipeline => "Data Pipeline",
            CADSKind::ETLProcess => "ETL Process",
            CADSKind::ETLPipeline => "ETL Pipeline",
            CADSKind::SourceSystem => "Source System",
            CADSKind::DestinationSystem => "Destination System",
        };

        let status_text = match asset.status {
            CADSStatus::Draft => "Draft",
            CADSStatus::Validated => "Validated",
            CADSStatus::Production => "Production",
            CADSStatus::Deprecated => "Deprecated",
        };

        md.push_str("| Property | Value |\n");
        md.push_str("|----------|-------|\n");
        md.push_str(&format!("| **ID** | {} |\n", asset.id));
        md.push_str(&format!("| **Kind** | {} |\n", kind_text));
        md.push_str(&format!("| **Version** | {} |\n", asset.version));
        md.push_str(&format!("| **Status** | {} |\n", status_text));
        md.push_str(&format!("| **API Version** | {} |\n", asset.api_version));

        if let Some(domain) = &asset.domain {
            md.push_str(&format!("| **Domain** | {} |\n", domain));
        }

        md.push_str("\n---\n\n");

        // Description section
        if let Some(desc) = &asset.description {
            md.push_str("## Description\n\n");
            if let Some(purpose) = &desc.purpose {
                md.push_str(&format!("**Purpose:** {}\n\n", purpose));
            }
            if let Some(usage) = &desc.usage {
                md.push_str(&format!("**Usage:** {}\n\n", usage));
            }
            if let Some(limitations) = &desc.limitations {
                md.push_str(&format!("**Limitations:** {}\n\n", limitations));
            }
            if let Some(links) = &desc.external_links
                && !links.is_empty()
            {
                md.push_str("**External Links:**\n");
                for link in links {
                    let desc = link.description.as_deref().unwrap_or("");
                    md.push_str(&format!("- {} {}\n", link.url, desc));
                }
                md.push('\n');
            }
            md.push_str("---\n\n");
        }

        // Runtime section
        if let Some(runtime) = &asset.runtime {
            md.push_str("## Runtime\n\n");
            if let Some(env) = &runtime.environment {
                md.push_str(&format!("**Environment:** {}\n\n", env));
            }
            if let Some(endpoints) = &runtime.endpoints
                && !endpoints.is_empty()
            {
                md.push_str("**Endpoints:**\n");
                for ep in endpoints {
                    md.push_str(&format!("- {}\n", ep));
                }
                md.push('\n');
            }
            if let Some(container) = &runtime.container
                && let Some(image) = &container.image
            {
                md.push_str(&format!("**Container Image:** {}\n\n", image));
            }
            if let Some(resources) = &runtime.resources {
                md.push_str("**Resources:**\n");
                if let Some(cpu) = &resources.cpu {
                    md.push_str(&format!("- CPU: {}\n", cpu));
                }
                if let Some(memory) = &resources.memory {
                    md.push_str(&format!("- Memory: {}\n", memory));
                }
                if let Some(gpu) = &resources.gpu {
                    md.push_str(&format!("- GPU: {}\n", gpu));
                }
                md.push('\n');
            }
        }

        // SLA section
        if let Some(sla) = &asset.sla
            && let Some(props) = &sla.properties
            && !props.is_empty()
        {
            md.push_str("## Service Level Agreements\n\n");
            md.push_str("| Element | Value | Unit | Driver |\n");
            md.push_str("|---------|-------|------|--------|\n");
            for prop in props {
                let driver = prop.driver.as_deref().unwrap_or("-");
                md.push_str(&format!(
                    "| {} | {} | {} | {} |\n",
                    prop.element, prop.value, prop.unit, driver
                ));
            }
            md.push('\n');
        }

        // Pricing section
        if let Some(pricing) = &asset.pricing {
            md.push_str("## Pricing\n\n");
            if let Some(model) = &pricing.model {
                md.push_str(&format!("**Model:** {:?}\n\n", model));
            }
            if let Some(currency) = &pricing.currency
                && let Some(cost) = pricing.unit_cost
            {
                let unit = pricing.billing_unit.as_deref().unwrap_or("unit");
                md.push_str(&format!("**Cost:** {} {} per {}\n\n", cost, currency, unit));
            }
            if let Some(notes) = &pricing.notes {
                md.push_str(&format!("**Notes:** {}\n\n", notes));
            }
        }

        // Team section
        if let Some(team) = &asset.team
            && !team.is_empty()
        {
            md.push_str("## Team\n\n");
            md.push_str("| Role | Name | Contact |\n");
            md.push_str("|------|------|--------|\n");
            for member in team {
                let contact = member.contact.as_deref().unwrap_or("-");
                md.push_str(&format!(
                    "| {} | {} | {} |\n",
                    member.role, member.name, contact
                ));
            }
            md.push('\n');
        }

        // Risk section
        if let Some(risk) = &asset.risk {
            md.push_str("## Risk Management\n\n");
            if let Some(classification) = &risk.classification {
                md.push_str(&format!("**Classification:** {:?}\n\n", classification));
            }
            if let Some(areas) = &risk.impact_areas
                && !areas.is_empty()
            {
                let areas_str: Vec<String> = areas.iter().map(|a| format!("{:?}", a)).collect();
                md.push_str(&format!("**Impact Areas:** {}\n\n", areas_str.join(", ")));
            }
            if let Some(intended) = &risk.intended_use {
                md.push_str(&format!("**Intended Use:** {}\n\n", intended));
            }
            if let Some(out_of_scope) = &risk.out_of_scope_use {
                md.push_str(&format!("**Out of Scope:** {}\n\n", out_of_scope));
            }
            if let Some(mitigations) = &risk.mitigations
                && !mitigations.is_empty()
            {
                md.push_str("**Mitigations:**\n");
                for m in mitigations {
                    md.push_str(&format!("- {} ({:?})\n", m.description, m.status));
                }
                md.push('\n');
            }
        }

        // Compliance section
        if let Some(compliance) = &asset.compliance {
            md.push_str("## Compliance\n\n");
            if let Some(frameworks) = &compliance.frameworks
                && !frameworks.is_empty()
            {
                md.push_str("### Frameworks\n\n");
                md.push_str("| Name | Category | Status |\n");
                md.push_str("|------|----------|--------|\n");
                for fw in frameworks {
                    let cat = fw.category.as_deref().unwrap_or("-");
                    md.push_str(&format!("| {} | {} | {:?} |\n", fw.name, cat, fw.status));
                }
                md.push('\n');
            }
            if let Some(controls) = &compliance.controls
                && !controls.is_empty()
            {
                md.push_str("### Controls\n\n");
                md.push_str("| ID | Description |\n");
                md.push_str("|----|-------------|\n");
                for ctrl in controls {
                    md.push_str(&format!("| {} | {} |\n", ctrl.id, ctrl.description));
                }
                md.push('\n');
            }
        }

        // Tags
        if !asset.tags.is_empty() {
            md.push_str("---\n\n");
            let tag_strings: Vec<String> = asset.tags.iter().map(|t| format!("`{}`", t)).collect();
            md.push_str(&format!("**Tags:** {}\n\n", tag_strings.join(" ")));
        }

        // Timestamps
        if asset.created_at.is_some() || asset.updated_at.is_some() {
            md.push_str("---\n\n");
            if let Some(created) = &asset.created_at {
                md.push_str(&format!(
                    "*Created: {}",
                    created.format("%Y-%m-%d %H:%M UTC")
                ));
                if let Some(updated) = &asset.updated_at {
                    md.push_str(&format!(
                        " | Last Updated: {}",
                        updated.format("%Y-%m-%d %H:%M UTC")
                    ));
                }
                md.push_str("*\n\n");
            } else if let Some(updated) = &asset.updated_at {
                md.push_str(&format!(
                    "*Last Updated: {}*\n\n",
                    updated.format("%Y-%m-%d %H:%M UTC")
                ));
            }
        }

        md
    }

    /// Generate PDF from markdown content
    fn generate_pdf(
        &self,
        title: &str,
        markdown: &str,
        filename: &str,
        doc_type: &str,
    ) -> Result<PdfExportResult, ExportError> {
        let pdf_content = self.create_pdf_document(title, markdown, doc_type)?;
        let pdf_base64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &pdf_content);

        // Estimate page count based on content length
        let chars_per_page = 3000;
        let page_count = std::cmp::max(1, (markdown.len() / chars_per_page) as u32 + 1);

        Ok(PdfExportResult {
            pdf_base64,
            filename: filename.to_string(),
            page_count,
            title: title.to_string(),
        })
    }

    /// Create a PDF document with proper GFM rendering and multi-page support
    fn create_pdf_document(
        &self,
        title: &str,
        markdown: &str,
        doc_type: &str,
    ) -> Result<Vec<u8>, ExportError> {
        let (width, height) = self.branding.page_size.dimensions_mm();
        let width_pt = width * 2.83465;
        let height_pt = height * 2.83465;

        // Generate all page content streams
        let page_streams =
            self.render_markdown_to_pdf_pages(title, markdown, width_pt, height_pt, doc_type);
        let page_count = page_streams.len();

        let mut pdf = Vec::new();

        // PDF Header
        pdf.extend_from_slice(b"%PDF-1.4\n");
        pdf.extend_from_slice(b"%\xE2\xE3\xCF\xD3\n");

        let mut xref_positions: Vec<usize> = Vec::new();

        // Object 1: Catalog
        xref_positions.push(pdf.len());
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");

        // Object 2: Pages - will be written later after we know all page refs
        let pages_obj_position = xref_positions.len();
        xref_positions.push(0); // Placeholder, will update

        // For each page, we need: Page object + Content stream object
        // Object numbering: 3,4 for page 1; 5,6 for page 2; etc.
        // Then fonts start after all pages
        let mut page_obj_ids: Vec<usize> = Vec::new();
        let font_obj_start = 3 + (page_count * 2); // First font object ID

        for (page_idx, content_stream) in page_streams.iter().enumerate() {
            let page_obj_id = 3 + (page_idx * 2);
            let content_obj_id = page_obj_id + 1;
            page_obj_ids.push(page_obj_id);

            // Page object
            xref_positions.push(pdf.len());
            let page_obj = format!(
                "{} 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {:.2} {:.2}] /Contents {} 0 R /Resources << /Font << /F1 {} 0 R /F2 {} 0 R >> >> >>\nendobj\n",
                page_obj_id,
                width_pt,
                height_pt,
                content_obj_id,
                font_obj_start,
                font_obj_start + 1
            );
            pdf.extend_from_slice(page_obj.as_bytes());

            // Content stream object
            xref_positions.push(pdf.len());
            let content_obj = format!(
                "{} 0 obj\n<< /Length {} >>\nstream\n{}\nendstream\nendobj\n",
                content_obj_id,
                content_stream.len(),
                content_stream
            );
            pdf.extend_from_slice(content_obj.as_bytes());
        }

        // Now write the Pages object with correct kids list
        let pages_position = pdf.len();
        let kids_list: Vec<String> = page_obj_ids
            .iter()
            .map(|id| format!("{} 0 R", id))
            .collect();
        let pages_obj = format!(
            "2 0 obj\n<< /Type /Pages /Kids [{}] /Count {} >>\nendobj\n",
            kids_list.join(" "),
            page_count
        );
        pdf.extend_from_slice(pages_obj.as_bytes());
        xref_positions[pages_obj_position] = pages_position;

        // Font objects
        xref_positions.push(pdf.len());
        let font1_obj = format!(
            "{} 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\nendobj\n",
            font_obj_start
        );
        pdf.extend_from_slice(font1_obj.as_bytes());

        xref_positions.push(pdf.len());
        let font2_obj = format!(
            "{} 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>\nendobj\n",
            font_obj_start + 1
        );
        pdf.extend_from_slice(font2_obj.as_bytes());

        // Info dictionary
        let info_obj_id = font_obj_start + 2;
        xref_positions.push(pdf.len());
        let timestamp = if self.branding.show_timestamp {
            Utc::now().format("D:%Y%m%d%H%M%S").to_string()
        } else {
            String::new()
        };

        let escaped_title = self.escape_pdf_string(title);
        let producer = "Open Data Modelling SDK";
        let company = self
            .branding
            .company_name
            .as_deref()
            .unwrap_or("opendatamodelling.com");

        let info_obj = format!(
            "{} 0 obj\n<< /Title ({}) /Producer ({}) /Creator ({}) /CreationDate ({}) >>\nendobj\n",
            info_obj_id, escaped_title, producer, company, timestamp
        );
        pdf.extend_from_slice(info_obj.as_bytes());

        // Cross-reference table
        let xref_start = pdf.len();
        pdf.extend_from_slice(b"xref\n");
        pdf.extend_from_slice(format!("0 {}\n", xref_positions.len() + 1).as_bytes());
        pdf.extend_from_slice(b"0000000000 65535 f \n");
        for pos in &xref_positions {
            pdf.extend_from_slice(format!("{:010} 00000 n \n", pos).as_bytes());
        }

        // Trailer
        pdf.extend_from_slice(b"trailer\n");
        pdf.extend_from_slice(
            format!(
                "<< /Size {} /Root 1 0 R /Info {} 0 R >>\n",
                xref_positions.len() + 1,
                info_obj_id
            )
            .as_bytes(),
        );
        pdf.extend_from_slice(b"startxref\n");
        pdf.extend_from_slice(format!("{}\n", xref_start).as_bytes());
        pdf.extend_from_slice(b"%%EOF\n");

        Ok(pdf)
    }

    /// Render markdown to PDF content streams with proper formatting (multi-page)
    fn render_markdown_to_pdf_pages(
        &self,
        title: &str,
        markdown: &str,
        width: f64,
        height: f64,
        doc_type: &str,
    ) -> Vec<String> {
        let mut pages: Vec<String> = Vec::new();
        let mut stream = String::new();
        let margin = 50.0;
        let footer_height = 40.0; // Reserve space for footer
        let header_height = 100.0; // Reserve space for header/logo/title/doc type
        let body_font_size = self.branding.font_size as f64;
        let line_height = body_font_size * 1.4;
        let max_width = width - (2.0 * margin);
        let mut page_num = 1;

        // === HEADER SECTION WITH LOGO ===

        // Draw the logo circle with gradient-like effect (blue circle)
        let logo_cx = margin + 15.0;
        let logo_cy = height - margin - 10.0;
        let logo_r = 12.0;

        // Draw filled blue circle
        stream.push_str("q\n");
        stream.push_str("0 0.4 0.8 rg\n"); // RGB for #0066CC
        stream.push_str(&format!("{:.2} {:.2} m\n", logo_cx + logo_r, logo_cy));
        // Approximate circle with bezier curves
        let k = 0.5523; // bezier constant for circle
        stream.push_str(&format!(
            "{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c\n",
            logo_cx + logo_r,
            logo_cy + logo_r * k,
            logo_cx + logo_r * k,
            logo_cy + logo_r,
            logo_cx,
            logo_cy + logo_r
        ));
        stream.push_str(&format!(
            "{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c\n",
            logo_cx - logo_r * k,
            logo_cy + logo_r,
            logo_cx - logo_r,
            logo_cy + logo_r * k,
            logo_cx - logo_r,
            logo_cy
        ));
        stream.push_str(&format!(
            "{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c\n",
            logo_cx - logo_r,
            logo_cy - logo_r * k,
            logo_cx - logo_r * k,
            logo_cy - logo_r,
            logo_cx,
            logo_cy - logo_r
        ));
        stream.push_str(&format!(
            "{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c\n",
            logo_cx + logo_r * k,
            logo_cy - logo_r,
            logo_cx + logo_r,
            logo_cy - logo_r * k,
            logo_cx + logo_r,
            logo_cy
        ));
        stream.push_str("f\n"); // Fill the circle
        stream.push_str("Q\n");

        // Draw white cross inside the circle
        stream.push_str("q\n");
        stream.push_str("1 1 1 RG\n"); // White stroke
        stream.push_str("2 w\n"); // Line width
        stream.push_str("1 J\n"); // Round line cap
        // Vertical line
        stream.push_str(&format!(
            "{:.2} {:.2} m\n{:.2} {:.2} l\nS\n",
            logo_cx,
            logo_cy - logo_r * 0.6,
            logo_cx,
            logo_cy + logo_r * 0.6
        ));
        // Horizontal line
        stream.push_str(&format!(
            "{:.2} {:.2} m\n{:.2} {:.2} l\nS\n",
            logo_cx - logo_r * 0.6,
            logo_cy,
            logo_cx + logo_r * 0.6,
            logo_cy
        ));
        stream.push_str("Q\n");

        // Render "Open Data Modelling" text next to logo
        stream.push_str("BT\n");
        let logo_text_x = margin + 35.0;
        let logo_text_y = height - margin - 5.0;
        stream.push_str("/F2 11 Tf\n"); // Bold font
        stream.push_str(&format!("{:.2} {:.2} Td\n", logo_text_x, logo_text_y));
        stream.push_str("(Open Data) Tj\n");
        stream.push_str(&format!("0 {:.2} Td\n", -12.0));
        stream.push_str("(Modelling) Tj\n");
        stream.push_str("ET\n");

        // Draw header line below logo
        let header_line_y = height - margin - 30.0;
        stream.push_str(&format!(
            "q\n0.7 G\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
            margin,
            header_line_y,
            width - margin,
            header_line_y
        ));

        // === DOCUMENT TYPE TITLE (e.g., "DECISION RECORD" or "KNOWLEDGE BASE") ===
        stream.push_str("BT\n");
        let doc_type_y = height - margin - 48.0;
        stream.push_str("/F2 12 Tf\n"); // Bold font for document type
        stream.push_str("0.3 0.3 0.3 rg\n"); // Dark gray color
        stream.push_str(&format!("{:.2} {:.2} Td\n", margin, doc_type_y));
        stream.push_str(&format!(
            "({}) Tj\n",
            self.escape_pdf_string(&doc_type.to_uppercase())
        ));
        stream.push_str("ET\n");

        // === DOCUMENT TITLE ===
        stream.push_str("BT\n");
        stream.push_str("0 0 0 rg\n"); // Black color for title
        let title_y = height - margin - 68.0;
        stream.push_str("/F2 16 Tf\n"); // Bold, large font for title
        stream.push_str(&format!("{:.2} {:.2} Td\n", margin, title_y));
        stream.push_str(&format!("({}) Tj\n", self.escape_pdf_string(title)));
        stream.push_str("ET\n");

        // Note: Footer is rendered by render_page_header_footer closure for all pages
        // This ensures consistent footer across all pages including page numbers

        // === BODY CONTENT ===
        let content_top = height - margin - header_height;
        let content_bottom = margin + footer_height;
        let mut y_pos = content_top;
        let mut in_table = false;
        let mut in_code_block = false;

        // Helper closure to render footer on each page
        let render_page_header_footer =
            |stream: &mut String,
             page_num: u32,
             width: f64,
             height: f64,
             margin: f64,
             footer_height: f64| {
                // Draw logo on continuation pages (smaller, simpler)
                if page_num > 1 {
                    // Small logo indicator
                    stream.push_str("BT\n");
                    stream.push_str("/F2 9 Tf\n");
                    stream.push_str("0.3 0.3 0.3 rg\n");
                    stream.push_str(&format!(
                        "1 0 0 1 {:.2} {:.2} Tm\n",
                        margin,
                        height - margin - 10.0
                    ));
                    stream.push_str("(Open Data Modelling) Tj\n");
                    stream.push_str("ET\n");
                }

                // Footer line
                let footer_line_y = margin + footer_height - 10.0;
                stream.push_str(&format!(
                    "q\n0.3 G\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
                    margin,
                    footer_line_y,
                    width - margin,
                    footer_line_y
                ));

                let footer_y = margin + 15.0;

                // Copyright text on the left (use octal \251 for © symbol)
                stream.push_str("BT\n");
                stream.push_str("/F1 9 Tf\n");
                stream.push_str("0 0 0 rg\n");
                stream.push_str(&format!("1 0 0 1 {:.2} {:.2} Tm\n", margin, footer_y));
                stream.push_str("(\\251 opendatamodelling.com) Tj\n");
                stream.push_str("ET\n");

                // Page number on the right
                stream.push_str("BT\n");
                stream.push_str("/F1 9 Tf\n");
                stream.push_str("0 0 0 rg\n");
                stream.push_str(&format!(
                    "1 0 0 1 {:.2} {:.2} Tm\n",
                    width - margin - 40.0,
                    footer_y
                ));
                stream.push_str(&format!("(Page {}) Tj\n", page_num));
                stream.push_str("ET\n");
            };

        for line in markdown.lines() {
            // Check if we need a new page
            if y_pos < content_bottom + line_height {
                // Render footer on current page
                render_page_header_footer(
                    &mut stream,
                    page_num,
                    width,
                    height,
                    margin,
                    footer_height,
                );

                // Save current page and start new one
                pages.push(stream);
                stream = String::new();
                page_num += 1;
                y_pos = height - margin - 30.0; // Start content higher on continuation pages
            }

            let trimmed = line.trim();

            // Handle code blocks
            if trimmed.starts_with("```") {
                in_code_block = !in_code_block;
                y_pos -= line_height * 0.5;
                continue;
            }

            if in_code_block {
                // Draw dark background for code block line
                let code_bg_padding = 3.0;
                let code_line_height = line_height * 0.9;
                stream.push_str("q\n");
                stream.push_str("0.15 0.15 0.15 rg\n"); // Dark gray background (#262626)
                stream.push_str(&format!(
                    "{:.2} {:.2} {:.2} {:.2} re f\n",
                    margin + 15.0,
                    y_pos - code_bg_padding,
                    max_width - 15.0,
                    code_line_height + code_bg_padding
                ));
                stream.push_str("Q\n");

                // Render code with light text using absolute positioning
                stream.push_str("BT\n");
                let code_font_size = body_font_size - 1.0;
                stream.push_str(&format!("/F1 {:.1} Tf\n", code_font_size));
                stream.push_str("0.9 0.9 0.9 rg\n"); // Light gray text for code
                stream.push_str(&format!("1 0 0 1 {:.2} {:.2} Tm\n", margin + 20.0, y_pos));
                stream.push_str(&format!("({}) Tj\n", self.escape_pdf_string(line)));
                stream.push_str("ET\n");
                y_pos -= code_line_height;
                continue;
            }

            // Skip image references and markdown footer (already rendered)
            if trimmed.starts_with("![") {
                continue;
            }

            // Skip the copyright line in content (already in footer)
            if trimmed.starts_with("©") || trimmed == DEFAULT_COPYRIGHT {
                continue;
            }

            // Handle horizontal rules
            if trimmed == "---" || trimmed == "***" || trimmed == "___" {
                y_pos -= line_height * 0.3;
                // Draw a line
                stream.push_str(&format!(
                    "q\n0.7 G\n{:.2} {:.2} m\n{:.2} {:.2} l\nS\nQ\n",
                    margin,
                    y_pos,
                    width - margin,
                    y_pos
                ));
                y_pos -= line_height * 0.5;
                continue;
            }

            // Handle table rows
            if trimmed.starts_with("|") && trimmed.ends_with("|") {
                // Skip separator rows
                if trimmed.contains("---") {
                    in_table = true;
                    continue;
                }

                let cells: Vec<&str> = trimmed
                    .trim_matches('|')
                    .split('|')
                    .map(|s| s.trim())
                    .collect();

                let cell_width = max_width / cells.len() as f64;

                // Calculate max chars per cell based on cell width and font size
                let font_size = if in_table {
                    body_font_size - 1.0
                } else {
                    body_font_size
                };
                // Approximate character width for Helvetica
                // Using a conservative factor to ensure text fits
                let char_width_factor = 0.45;
                let max_chars_per_line =
                    ((cell_width - 10.0) / (font_size * char_width_factor)) as usize;
                let max_chars_per_line = max_chars_per_line.max(10); // Minimum 10 chars per line

                // Word-wrap each cell and find maximum number of lines needed
                let mut wrapped_cells: Vec<(Vec<String>, bool)> = Vec::new();
                let mut max_lines = 1usize;

                for cell in &cells {
                    // Check if cell content is bold
                    let (text, is_bold) = if cell.starts_with("**") && cell.ends_with("**") {
                        (cell.trim_matches('*'), true)
                    } else {
                        (*cell, false)
                    };

                    // Word wrap the text
                    let lines = self.word_wrap(text, max_chars_per_line);
                    max_lines = max_lines.max(lines.len());
                    wrapped_cells.push((lines, is_bold));
                }

                // Check if we have enough space for this row
                let row_height = line_height * max_lines as f64;
                if y_pos - row_height < content_bottom {
                    // Need a new page
                    render_page_header_footer(
                        &mut stream,
                        page_num,
                        width,
                        height,
                        margin,
                        footer_height,
                    );
                    pages.push(stream);
                    stream = String::new();
                    page_num += 1;
                    y_pos = height - margin - 30.0;
                }

                // Render each line of each cell
                for line_idx in 0..max_lines {
                    let mut x_pos = margin;
                    let line_y = y_pos - (line_idx as f64 * line_height);

                    for (lines, is_bold) in &wrapped_cells {
                        let font = if *is_bold || !in_table { "/F2" } else { "/F1" };
                        let text = lines.get(line_idx).map(|s| s.as_str()).unwrap_or("");

                        if !text.is_empty() {
                            stream.push_str("BT\n");
                            stream.push_str(&format!("{} {:.1} Tf\n", font, font_size));
                            stream.push_str("0 0 0 rg\n");
                            stream.push_str(&format!("1 0 0 1 {:.2} {:.2} Tm\n", x_pos, line_y));
                            stream.push_str(&format!("({}) Tj\n", self.escape_pdf_string(text)));
                            stream.push_str("ET\n");
                        }
                        x_pos += cell_width;
                    }
                }

                y_pos -= row_height + (line_height * 0.2); // Add small padding between rows
                in_table = true;
                continue;
            } else if in_table && !trimmed.is_empty() {
                in_table = false;
                y_pos -= line_height * 0.3;
            }

            // Handle headings - Skip H1 since we render the title in the header
            if trimmed.starts_with("# ") && !trimmed.starts_with("## ") {
                // Skip the main H1 title as it's already in the header
                continue;
            }

            if trimmed.starts_with("## ") {
                let text = trimmed.trim_start_matches("## ");
                let h2_size = body_font_size + 3.0;

                // Check if we have enough space for heading + at least 4 lines of content
                // If not, start a new page to keep section together
                let min_section_space = line_height * 5.0;
                if y_pos - min_section_space < content_bottom {
                    render_page_header_footer(
                        &mut stream,
                        page_num,
                        width,
                        height,
                        margin,
                        footer_height,
                    );
                    pages.push(stream);
                    stream = String::new();
                    page_num += 1;
                    y_pos = height - margin - 30.0;
                }

                y_pos -= line_height * 0.3;
                stream.push_str("BT\n");
                stream.push_str(&format!("/F2 {:.1} Tf\n", h2_size));
                stream.push_str("0 0 0 rg\n");
                stream.push_str(&format!("1 0 0 1 {:.2} {:.2} Tm\n", margin, y_pos));
                stream.push_str(&format!("({}) Tj\n", self.escape_pdf_string(text)));
                stream.push_str("ET\n");
                y_pos -= line_height * 1.2;
                continue;
            }

            if trimmed.starts_with("### ") {
                let text = trimmed.trim_start_matches("### ");

                // Check if we have enough space for subheading + at least 3 lines of content
                let min_subsection_space = line_height * 4.0;
                if y_pos - min_subsection_space < content_bottom {
                    render_page_header_footer(
                        &mut stream,
                        page_num,
                        width,
                        height,
                        margin,
                        footer_height,
                    );
                    pages.push(stream);
                    stream = String::new();
                    page_num += 1;
                    y_pos = height - margin - 30.0;
                }
                let h3_size = body_font_size + 1.0;
                stream.push_str("BT\n");
                stream.push_str(&format!("/F2 {:.1} Tf\n", h3_size));
                stream.push_str("0 0 0 rg\n");
                stream.push_str(&format!("1 0 0 1 {:.2} {:.2} Tm\n", margin, y_pos));
                stream.push_str(&format!("({}) Tj\n", self.escape_pdf_string(text)));
                stream.push_str("ET\n");
                y_pos -= line_height * 1.1;
                continue;
            }

            // Handle list items
            if trimmed.starts_with("- ") || trimmed.starts_with("* ") {
                let text = trimmed[2..].to_string();
                stream.push_str("BT\n");
                stream.push_str(&format!("/F1 {:.1} Tf\n", body_font_size));
                stream.push_str("0 0 0 rg\n");
                stream.push_str(&format!("1 0 0 1 {:.2} {:.2} Tm\n", margin + 10.0, y_pos));
                stream.push_str(&format!(
                    "(\\267 {}) Tj\n",
                    self.escape_pdf_string(&self.strip_markdown_formatting(&text))
                ));
                stream.push_str("ET\n");
                y_pos -= line_height;
                continue;
            }

            // Handle numbered list items
            if let Some(rest) = self.parse_numbered_list(trimmed) {
                stream.push_str("BT\n");
                stream.push_str(&format!("/F1 {:.1} Tf\n", body_font_size));
                stream.push_str("0 0 0 rg\n");
                stream.push_str(&format!("1 0 0 1 {:.2} {:.2} Tm\n", margin + 10.0, y_pos));
                stream.push_str(&format!(
                    "({}) Tj\n",
                    self.escape_pdf_string(&self.strip_markdown_formatting(rest))
                ));
                stream.push_str("ET\n");
                y_pos -= line_height;
                continue;
            }

            // Handle empty lines
            if trimmed.is_empty() {
                y_pos -= line_height * 0.5;
                continue;
            }

            // Handle italic text (*text*)
            let display_text = self.strip_markdown_formatting(trimmed);

            // Check if this is bold text
            let (text, font) = if trimmed.starts_with("**") && trimmed.ends_with("**") {
                (display_text.as_str(), "/F2")
            } else if trimmed.starts_with("*")
                && trimmed.ends_with("*")
                && !trimmed.starts_with("**")
            {
                // Italic - we don't have an italic font, so just use regular
                (display_text.as_str(), "/F1")
            } else {
                (display_text.as_str(), "/F1")
            };

            // Word wrap regular text
            let wrapped_lines = self.word_wrap(text, (max_width / (body_font_size * 0.5)) as usize);
            for wrapped_line in wrapped_lines {
                // Check for page break
                if y_pos < content_bottom + line_height {
                    render_page_header_footer(
                        &mut stream,
                        page_num,
                        width,
                        height,
                        margin,
                        footer_height,
                    );
                    pages.push(stream);
                    stream = String::new();
                    page_num += 1;
                    y_pos = height - margin - 30.0;
                }
                stream.push_str("BT\n");
                stream.push_str(&format!("{} {:.1} Tf\n", font, body_font_size));
                stream.push_str("0 0 0 rg\n");
                stream.push_str(&format!("1 0 0 1 {:.2} {:.2} Tm\n", margin, y_pos));
                stream.push_str(&format!("({}) Tj\n", self.escape_pdf_string(&wrapped_line)));
                stream.push_str("ET\n");
                y_pos -= line_height;
            }
        }

        // Render footer on last page and add it to pages
        render_page_header_footer(&mut stream, page_num, width, height, margin, footer_height);
        pages.push(stream);

        pages
    }

    /// Strip markdown formatting from text for display
    fn strip_markdown_formatting(&self, text: &str) -> String {
        let mut result = text.to_string();

        // Remove bold markers
        while result.contains("**") {
            result = result.replacen("**", "", 2);
        }

        // Remove italic markers (single asterisk)
        // Be careful not to remove list markers
        let chars: Vec<char> = result.chars().collect();
        let mut cleaned = String::new();
        let mut i = 0;
        while i < chars.len() {
            if chars[i] == '*' && i + 1 < chars.len() && chars[i + 1] != '*' && chars[i + 1] != ' '
            {
                // This might be italic start
                if result[i + 1..].contains('*') {
                    // Skip the asterisk
                    i += 1;
                    continue;
                }
            }
            cleaned.push(chars[i]);
            i += 1;
        }

        // Remove backticks (inline code)
        result = cleaned.replace('`', "");

        // Remove link formatting [text](url) -> text
        while let Some(start) = result.find('[') {
            if let Some(mid) = result[start..].find("](")
                && let Some(end) = result[start + mid..].find(')')
            {
                let link_text = &result[start + 1..start + mid];
                let before = &result[..start];
                let after = &result[start + mid + end + 1..];
                result = format!("{}{}{}", before, link_text, after);
                continue;
            }
            break;
        }

        result
    }

    /// Parse numbered list item, returns the text after the number
    fn parse_numbered_list<'a>(&self, text: &'a str) -> Option<&'a str> {
        let bytes = text.as_bytes();
        let mut i = 0;

        // Skip digits
        while i < bytes.len() && bytes[i].is_ascii_digit() {
            i += 1;
        }

        // Check for period and space
        if i > 0 && i < bytes.len() - 1 && bytes[i] == b'.' && bytes[i + 1] == b' ' {
            return Some(&text[i + 2..]);
        }

        None
    }

    /// Escape special characters for PDF strings
    fn escape_pdf_string(&self, s: &str) -> String {
        let mut result = String::new();
        for c in s.chars() {
            match c {
                '\\' => result.push_str("\\\\"),
                '(' => result.push_str("\\("),
                ')' => result.push_str("\\)"),
                '\n' => result.push_str("\\n"),
                '\r' => result.push_str("\\r"),
                '\t' => result.push_str("\\t"),
                // Handle special characters by using octal encoding
                '©' => result.push_str("\\251"), // Copyright symbol in WinAnsiEncoding
                '®' => result.push_str("\\256"), // Registered trademark
                'â„¢' => result.push_str("\\231"), // Trademark
                '•' => result.push_str("\\267"), // Bullet
                '–' => result.push_str("\\226"), // En dash
                '—' => result.push_str("\\227"), // Em dash
                '…' => result.push_str("\\205"), // Ellipsis
                _ if c.is_ascii() => result.push(c),
                // For non-ASCII characters, try to use closest ASCII equivalent
                _ => result.push('?'),
            }
        }
        result
    }

    /// Word wrap text to fit within max characters per line.
    /// Long words (URLs, field names) that exceed max_chars are broken with a
    /// continuation marker (→) to indicate the text continues on the next line.
    fn word_wrap(&self, text: &str, max_chars: usize) -> Vec<String> {
        let mut lines = Vec::new();
        let mut current_line = String::new();
        // Ensure we have at least some space for the continuation marker
        let effective_max = max_chars.max(5);

        for word in text.split_whitespace() {
            // If the word itself is too long, break it with continuation markers
            if word.len() > effective_max {
                // First, flush any current content
                if !current_line.is_empty() {
                    lines.push(current_line);
                    current_line = String::new();
                }
                // Break the long word into chunks
                let broken = self.break_long_word(word, effective_max);
                for (i, chunk) in broken.iter().enumerate() {
                    if i < broken.len() - 1 {
                        // Not the last chunk, push it as its own line
                        lines.push(chunk.clone());
                    } else {
                        // Last chunk becomes start of current line
                        current_line = chunk.clone();
                    }
                }
            } else if current_line.is_empty() {
                current_line = word.to_string();
            } else if current_line.len() + 1 + word.len() <= effective_max {
                current_line.push(' ');
                current_line.push_str(word);
            } else {
                lines.push(current_line);
                current_line = word.to_string();
            }
        }

        if !current_line.is_empty() {
            lines.push(current_line);
        }

        if lines.is_empty() {
            lines.push(String::new());
        }

        lines
    }

    /// Break a long word into chunks that fit within max_chars.
    /// Each chunk except the last ends with a hyphen (-) to indicate continuation.
    fn break_long_word(&self, word: &str, max_chars: usize) -> Vec<String> {
        let mut chunks = Vec::new();
        let chars: Vec<char> = word.chars().collect();
        // Use hyphen as continuation marker (ASCII-safe for PDF)
        let continuation_marker = "-";
        // Reserve 1 char for the continuation marker on non-final chunks
        let chunk_size = (max_chars - 1).max(1);

        let mut start = 0;
        while start < chars.len() {
            let remaining = chars.len() - start;
            if remaining <= max_chars {
                // Final chunk - no continuation marker needed
                chunks.push(chars[start..].iter().collect());
                break;
            } else {
                // Not final - add continuation marker
                let end = start + chunk_size;
                let mut chunk: String = chars[start..end].iter().collect();
                chunk.push_str(continuation_marker);
                chunks.push(chunk);
                start = end;
            }
        }

        if chunks.is_empty() {
            chunks.push(word.to_string());
        }

        chunks
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::decision::Decision;
    use crate::models::knowledge::KnowledgeArticle;

    #[test]
    fn test_branding_config_default() {
        let config = BrandingConfig::default();
        assert_eq!(config.brand_color, "#0066CC");
        assert!(config.show_page_numbers);
        assert!(config.show_timestamp);
        assert_eq!(config.font_size, 11);
        assert_eq!(config.page_size, PageSize::A4);
        assert_eq!(config.logo_url, Some(DEFAULT_LOGO_URL.to_string()));
        assert_eq!(config.footer, Some(DEFAULT_COPYRIGHT.to_string()));
    }

    #[test]
    fn test_page_size_dimensions() {
        let a4 = PageSize::A4;
        let (w, h) = a4.dimensions_mm();
        assert_eq!(w, 210.0);
        assert_eq!(h, 297.0);

        let letter = PageSize::Letter;
        let (w, h) = letter.dimensions_mm();
        assert!((w - 215.9).abs() < 0.1);
        assert!((h - 279.4).abs() < 0.1);
    }

    #[test]
    fn test_pdf_exporter_with_branding() {
        let branding = BrandingConfig {
            header: Some("Company Header".to_string()),
            footer: Some("Confidential".to_string()),
            company_name: Some("Test Corp".to_string()),
            brand_color: "#FF0000".to_string(),
            ..Default::default()
        };

        let exporter = PdfExporter::with_branding(branding.clone());
        assert_eq!(
            exporter.branding().header,
            Some("Company Header".to_string())
        );
        assert_eq!(exporter.branding().brand_color, "#FF0000");
    }

    #[test]
    fn test_export_decision_to_pdf() {
        let decision = Decision::new(
            1,
            "Use Rust for SDK",
            "We need to choose a language for the SDK implementation.",
            "Use Rust for type safety and performance.",
            "author@example.com",
        );

        let exporter = PdfExporter::new();
        let result = exporter.export_decision(&decision);
        assert!(result.is_ok());

        let pdf_result = result.unwrap();
        assert!(!pdf_result.pdf_base64.is_empty());
        assert!(pdf_result.filename.ends_with(".pdf"));
        assert!(pdf_result.page_count >= 1);
        assert!(pdf_result.title.contains("ADR-"));
    }

    #[test]
    fn test_export_knowledge_to_pdf() {
        let article = KnowledgeArticle::new(
            1,
            "Getting Started Guide",
            "A guide to getting started with the SDK.",
            "This guide covers the basics...",
            "author@example.com",
        );

        let exporter = PdfExporter::new();
        let result = exporter.export_knowledge(&article);
        assert!(result.is_ok());

        let pdf_result = result.unwrap();
        assert!(!pdf_result.pdf_base64.is_empty());
        assert!(pdf_result.filename.ends_with(".pdf"));
        assert!(pdf_result.title.contains("KB-"));
    }

    #[test]
    fn test_export_table_to_pdf() {
        use crate::models::{Column, Table};

        let mut table = Table::new(
            "users".to_string(),
            vec![
                Column::new("id".to_string(), "BIGINT".to_string()),
                Column::new("name".to_string(), "VARCHAR(255)".to_string()),
                Column::new("email".to_string(), "VARCHAR(255)".to_string()),
            ],
        );
        table.schema_name = Some("public".to_string());
        table.owner = Some("Data Engineering".to_string());
        table.notes = Some("Core user table for the application".to_string());

        let exporter = PdfExporter::new();
        let result = exporter.export_table(&table);
        assert!(result.is_ok());

        let pdf_result = result.unwrap();
        assert!(!pdf_result.pdf_base64.is_empty());
        assert!(pdf_result.filename.ends_with(".pdf"));
        assert_eq!(pdf_result.title, "users");
    }

    #[test]
    fn test_export_data_product_to_pdf() {
        use crate::models::odps::{ODPSDataProduct, ODPSDescription, ODPSOutputPort, ODPSStatus};

        let product = ODPSDataProduct {
            api_version: "v1.0.0".to_string(),
            kind: "DataProduct".to_string(),
            id: "dp-customer-360".to_string(),
            name: Some("Customer 360".to_string()),
            version: Some("1.0.0".to_string()),
            status: ODPSStatus::Active,
            domain: Some("Customer".to_string()),
            tenant: None,
            authoritative_definitions: None,
            description: Some(ODPSDescription {
                purpose: Some("Unified customer view across all touchpoints".to_string()),
                limitations: Some("Does not include real-time data".to_string()),
                usage: Some("Use for analytics and reporting".to_string()),
                authoritative_definitions: None,
                custom_properties: None,
            }),
            custom_properties: None,
            tags: vec![],
            input_ports: None,
            output_ports: Some(vec![ODPSOutputPort {
                name: "customer-data".to_string(),
                version: "1.0.0".to_string(),
                description: Some("Customer master data".to_string()),
                r#type: Some("table".to_string()),
                contract_id: Some("contract-123".to_string()),
                sbom: None,
                input_contracts: None,
                tags: vec![],
                custom_properties: None,
                authoritative_definitions: None,
            }]),
            management_ports: None,
            support: None,
            team: None,
            product_created_ts: None,
            created_at: None,
            updated_at: None,
        };

        let exporter = PdfExporter::new();
        let result = exporter.export_data_product(&product);
        assert!(result.is_ok());

        let pdf_result = result.unwrap();
        assert!(!pdf_result.pdf_base64.is_empty());
        assert!(pdf_result.filename.ends_with(".pdf"));
        assert_eq!(pdf_result.title, "Customer 360");
    }

    #[test]
    fn test_export_cads_asset_to_pdf() {
        use crate::models::cads::{
            CADSAsset, CADSDescription, CADSKind, CADSStatus, CADSTeamMember,
        };

        let asset = CADSAsset {
            api_version: "v1.0".to_string(),
            kind: CADSKind::AIModel,
            id: "model-sentiment-v1".to_string(),
            name: "Sentiment Analysis Model".to_string(),
            version: "1.0.0".to_string(),
            status: CADSStatus::Production,
            domain: Some("NLP".to_string()),
            domain_id: None,
            tags: vec![],
            description: Some(CADSDescription {
                purpose: Some("Analyze sentiment in customer feedback".to_string()),
                usage: Some("Call the /predict endpoint with text input".to_string()),
                limitations: Some("English language only".to_string()),
                external_links: None,
            }),
            runtime: None,
            sla: None,
            pricing: None,
            team: Some(vec![CADSTeamMember {
                role: "Owner".to_string(),
                name: "ML Team".to_string(),
                contact: Some("ml-team@example.com".to_string()),
            }]),
            risk: None,
            compliance: None,
            validation_profiles: None,
            bpmn_models: None,
            dmn_models: None,
            openapi_specs: None,
            custom_properties: None,
            created_at: None,
            updated_at: None,
        };

        let exporter = PdfExporter::new();
        let result = exporter.export_cads_asset(&asset);
        assert!(result.is_ok());

        let pdf_result = result.unwrap();
        assert!(!pdf_result.pdf_base64.is_empty());
        assert!(pdf_result.filename.ends_with(".pdf"));
        assert_eq!(pdf_result.title, "Sentiment Analysis Model");
    }

    #[test]
    fn test_export_markdown_to_pdf() {
        let exporter = PdfExporter::new();
        let result = exporter.export_markdown(
            "Test Document",
            "# Test\n\nThis is a test document.\n\n## Section\n\n- Item 1\n- Item 2",
            "test.pdf",
        );
        assert!(result.is_ok());

        let pdf_result = result.unwrap();
        assert!(!pdf_result.pdf_base64.is_empty());
        assert_eq!(pdf_result.filename, "test.pdf");
    }

    #[test]
    fn test_escape_pdf_string() {
        let exporter = PdfExporter::new();
        assert_eq!(exporter.escape_pdf_string("Hello"), "Hello");
        assert_eq!(exporter.escape_pdf_string("(test)"), "\\(test\\)");
        assert_eq!(exporter.escape_pdf_string("back\\slash"), "back\\\\slash");
    }

    #[test]
    fn test_word_wrap() {
        let exporter = PdfExporter::new();

        let wrapped = exporter.word_wrap("Hello world this is a test", 10);
        assert!(wrapped.len() > 1);

        let wrapped = exporter.word_wrap("Short", 100);
        assert_eq!(wrapped.len(), 1);
        assert_eq!(wrapped[0], "Short");
    }

    #[test]
    fn test_word_wrap_long_url() {
        let exporter = PdfExporter::new();

        // Test that a long URL without spaces gets broken with continuation markers
        let long_url = "https://example.com/very/long/path/to/some/resource/file.json";
        let wrapped = exporter.word_wrap(long_url, 20);

        // Should be broken into multiple lines
        assert!(
            wrapped.len() > 1,
            "Long URL should be wrapped into multiple lines"
        );

        // All lines except the last should end with hyphen
        for (i, line) in wrapped.iter().enumerate() {
            if i < wrapped.len() - 1 {
                assert!(
                    line.ends_with('-'),
                    "Non-final line should end with hyphen: {}",
                    line
                );
            }
        }

        // When joined (removing hyphens), should reconstruct the original
        let reconstructed: String = wrapped
            .iter()
            .map(|s| s.trim_end_matches('-'))
            .collect::<Vec<_>>()
            .join("");
        assert_eq!(reconstructed, long_url);
    }

    #[test]
    fn test_word_wrap_mixed_content() {
        let exporter = PdfExporter::new();

        // Test mixed content with short words and a long URL
        let text = "See https://example.com/very/long/path/to/resource for details";
        let wrapped = exporter.word_wrap(text, 25);

        // Should have multiple lines
        assert!(wrapped.len() > 1);

        // The URL should be broken across lines
        let all_text = wrapped.join(" ");
        assert!(all_text.contains("https://"));
    }

    #[test]
    fn test_break_long_word() {
        let exporter = PdfExporter::new();

        // Test breaking a long word
        let long_word = "abcdefghijklmnopqrstuvwxyz";
        let broken = exporter.break_long_word(long_word, 10);

        // Should be broken into multiple chunks
        assert!(broken.len() > 1);

        // All chunks except the last should end with hyphen
        for (i, chunk) in broken.iter().enumerate() {
            if i < broken.len() - 1 {
                assert!(
                    chunk.ends_with('-'),
                    "Chunk should end with hyphen: {}",
                    chunk
                );
                assert!(chunk.len() <= 10, "Chunk should fit within max_chars");
            }
        }

        // Reconstruct and verify
        let reconstructed: String = broken
            .iter()
            .map(|s| s.trim_end_matches('-'))
            .collect::<Vec<_>>()
            .join("");
        assert_eq!(reconstructed, long_word);
    }

    #[test]
    fn test_pdf_result_serialization() {
        let result = PdfExportResult {
            pdf_base64: "dGVzdA==".to_string(),
            filename: "test.pdf".to_string(),
            page_count: 1,
            title: "Test".to_string(),
        };

        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("pdf_base64"));
        assert!(json.contains("filename"));
    }

    #[test]
    fn test_strip_markdown_formatting() {
        let exporter = PdfExporter::new();
        assert_eq!(exporter.strip_markdown_formatting("**bold**"), "bold");
        assert_eq!(exporter.strip_markdown_formatting("`code`"), "code");
        assert_eq!(
            exporter.strip_markdown_formatting("[link](http://example.com)"),
            "link"
        );
    }

    /// Generate sample PDFs for visual inspection (writes to /tmp)
    /// Run with: cargo test generate_sample_pdfs_for_inspection -- --ignored --nocapture
    #[test]
    #[ignore]
    fn generate_sample_pdfs_for_inspection() {
        use crate::models::decision::DecisionOption;
        use base64::Engine;

        // Create a Decision with rich content including options with pros/cons
        let mut decision = Decision::new(
            2501100001,
            "Use Rust for SDK Implementation",
            "We need to choose a programming language for the SDK implementation.\n\nKey requirements:\n- Type safety\n- Performance\n- Cross-platform compilation\n- WASM support\n\nThe decision will impact the entire development team and future maintenance of the codebase. We need to carefully consider all options before making a final choice.",
            "We will use Rust as the primary programming language.\n\nRust provides:\n1. Strong type safety through its ownership system\n2. Excellent performance comparable to C/C++\n3. Cross-platform compilation via LLVM\n4. First-class WASM support\n\nThis decision was made after careful evaluation of all alternatives and considering the long-term maintainability of the project.",
            "architect@example.com",
        );

        // Add options with pros and cons
        decision.options = vec![
            DecisionOption::with_details(
                "Rust",
                "A systems programming language focused on safety and performance.",
                vec![
                    "Memory safety without garbage collection".to_string(),
                    "Excellent performance".to_string(),
                    "Strong type system".to_string(),
                    "First-class WASM support".to_string(),
                    "Growing ecosystem".to_string(),
                ],
                vec![
                    "Steeper learning curve".to_string(),
                    "Longer compilation times".to_string(),
                    "Smaller talent pool".to_string(),
                ],
                true, // selected
            ),
            DecisionOption::with_details(
                "TypeScript",
                "A typed superset of JavaScript.",
                vec![
                    "Large developer community".to_string(),
                    "Easy to learn".to_string(),
                    "Good tooling".to_string(),
                ],
                vec![
                    "Runtime type checking only".to_string(),
                    "Performance limitations".to_string(),
                    "Node.js dependency".to_string(),
                ],
                false,
            ),
            DecisionOption::with_details(
                "Go",
                "A statically typed language designed at Google.",
                vec![
                    "Simple syntax".to_string(),
                    "Fast compilation".to_string(),
                    "Good concurrency support".to_string(),
                ],
                vec![
                    "Limited generics".to_string(),
                    "No WASM support".to_string(),
                    "Verbose error handling".to_string(),
                ],
                false,
            ),
        ];

        decision.consequences =
            Some("This decision will have significant impact on the project.".to_string());

        // Debug: print the generated markdown to see what's being rendered
        let exporter = PdfExporter::new();
        let md = exporter.decision_to_markdown(&decision);
        println!("Generated markdown length: {} chars", md.len());
        println!(
            "Contains 'Options Considered': {}",
            md.contains("Options Considered")
        );
        println!("Contains 'Pros': {}", md.contains("Pros"));

        // Create a Knowledge Article with code blocks
        let article = KnowledgeArticle::new(
            2501100001,
            "Getting Started with the SDK",
            "A comprehensive guide to getting started with the Open Data Modelling SDK.",
            r#"## Installation

Install the SDK using cargo:

```bash
cargo add data-modelling-sdk
```

## Basic Usage

Here's a simple example:

```rust
use data_modelling_core::models::decision::Decision;

fn main() {
    let decision = Decision::new(
        1,
        "Use microservices",
        "Context here",
        "Decision here",
        "author@example.com",
    );
    println!("Created: {}", decision.title);
}
```

## Configuration

Configure using YAML:

```yaml
sdk:
  log_level: info
  storage_path: ./data
```

For more information, see the documentation."#,
            "docs@opendatamodelling.com",
        );

        let exporter = PdfExporter::new();

        // Export Decision
        let result = exporter.export_decision(&decision).unwrap();
        let pdf_bytes = base64::engine::general_purpose::STANDARD
            .decode(&result.pdf_base64)
            .unwrap();
        std::fs::write("/tmp/sample_decision.pdf", &pdf_bytes).unwrap();
        println!("Wrote /tmp/sample_decision.pdf ({} bytes)", pdf_bytes.len());

        // Export Knowledge Article
        let result = exporter.export_knowledge(&article).unwrap();
        let pdf_bytes = base64::engine::general_purpose::STANDARD
            .decode(&result.pdf_base64)
            .unwrap();
        std::fs::write("/tmp/sample_knowledge.pdf", &pdf_bytes).unwrap();
        println!(
            "Wrote /tmp/sample_knowledge.pdf ({} bytes)",
            pdf_bytes.len()
        );

        // Export Data Contract (Table)
        use crate::models::{Column, Table};

        let mut table = Table::new(
            "customer_orders".to_string(),
            vec![
                {
                    let mut col = Column::new("order_id".to_string(), "BIGINT".to_string());
                    col.primary_key = true;
                    col.description = "Unique identifier for each order".to_string();
                    col
                },
                {
                    let mut col = Column::new("customer_id".to_string(), "BIGINT".to_string());
                    col.description = "Foreign key reference to customers table".to_string();
                    col
                },
                {
                    let mut col = Column::new("order_date".to_string(), "TIMESTAMP".to_string());
                    col.description = "Date and time when the order was placed".to_string();
                    col.nullable = false;
                    col
                },
                {
                    let mut col = Column::new("status".to_string(), "VARCHAR(50)".to_string());
                    col.description = "Current status of the order".to_string();
                    col.enum_values = vec![
                        "pending".to_string(),
                        "processing".to_string(),
                        "shipped".to_string(),
                        "delivered".to_string(),
                        "cancelled".to_string(),
                    ];
                    col.business_name = Some("Order Status".to_string());
                    col
                },
                {
                    let mut col =
                        Column::new("total_amount".to_string(), "DECIMAL(10,2)".to_string());
                    col.description = "Total order amount in USD".to_string();
                    col
                },
            ],
        );
        table.schema_name = Some("sales".to_string());
        table.catalog_name = Some("production".to_string());
        table.owner = Some("Data Engineering Team".to_string());
        table.notes = Some("Contains all customer orders including historical data. This table is partitioned by order_date for query performance. Updated daily via ETL pipeline.".to_string());

        // Add ODCS metadata to test full export
        table
            .odcl_metadata
            .insert("apiVersion".to_string(), serde_json::json!("v3.0.2"));
        table
            .odcl_metadata
            .insert("kind".to_string(), serde_json::json!("DataContract"));
        table
            .odcl_metadata
            .insert("status".to_string(), serde_json::json!("active"));
        table
            .odcl_metadata
            .insert("version".to_string(), serde_json::json!("1.2.0"));
        table
            .odcl_metadata
            .insert("domain".to_string(), serde_json::json!("Sales"));
        table.odcl_metadata.insert(
            "dataProduct".to_string(),
            serde_json::json!("Customer Orders Analytics"),
        );

        // Add SLA information
        use crate::models::table::SlaProperty;
        table.sla = Some(vec![
            SlaProperty {
                property: "availability".to_string(),
                value: serde_json::json!("99.9"),
                unit: "%".to_string(),
                element: None,
                driver: Some("operational".to_string()),
                description: Some("Guaranteed uptime for data access".to_string()),
                scheduler: None,
                schedule: None,
            },
            SlaProperty {
                property: "freshness".to_string(),
                value: serde_json::json!(24),
                unit: "hours".to_string(),
                element: None,
                driver: Some("analytics".to_string()),
                description: Some("Maximum data staleness".to_string()),
                scheduler: None,
                schedule: None,
            },
        ]);

        // Add contact details
        use crate::models::table::ContactDetails;
        table.contact_details = Some(ContactDetails {
            name: Some("John Smith".to_string()),
            email: Some("john.smith@example.com".to_string()),
            role: Some("Data Steward".to_string()),
            phone: Some("+1-555-0123".to_string()),
            other: None,
        });

        let result = exporter.export_table(&table).unwrap();
        let pdf_bytes = base64::engine::general_purpose::STANDARD
            .decode(&result.pdf_base64)
            .unwrap();
        std::fs::write("/tmp/sample_table.pdf", &pdf_bytes).unwrap();
        println!("Wrote /tmp/sample_table.pdf ({} bytes)", pdf_bytes.len());

        // Export Data Product (ODPS)
        use crate::models::odps::{
            ODPSDataProduct, ODPSDescription, ODPSInputPort, ODPSOutputPort, ODPSStatus,
            ODPSSupport, ODPSTeam, ODPSTeamMember,
        };

        let product = ODPSDataProduct {
            api_version: "v1.0.0".to_string(),
            kind: "DataProduct".to_string(),
            id: "dp-customer-360-view".to_string(),
            name: Some("Customer 360 View".to_string()),
            version: Some("2.1.0".to_string()),
            status: ODPSStatus::Active,
            domain: Some("Customer Intelligence".to_string()),
            tenant: Some("ACME Corp".to_string()),
            authoritative_definitions: None,
            description: Some(ODPSDescription {
                purpose: Some("Provides a unified 360-degree view of customers by aggregating data from multiple sources including CRM, transactions, support tickets, and marketing interactions.".to_string()),
                limitations: Some("Data is refreshed daily at 2 AM UTC. Real-time updates are not supported. Historical data is retained for 7 years.".to_string()),
                usage: Some("Use this data product for customer analytics, segmentation, personalization, and churn prediction models.".to_string()),
                authoritative_definitions: None,
                custom_properties: None,
            }),
            custom_properties: None,
            tags: vec![],
            input_ports: Some(vec![
                ODPSInputPort {
                    name: "crm-contacts".to_string(),
                    version: "1.0.0".to_string(),
                    contract_id: "contract-crm-001".to_string(),
                    tags: vec![],
                    custom_properties: None,
                    authoritative_definitions: None,
                },
                ODPSInputPort {
                    name: "transaction-history".to_string(),
                    version: "2.0.0".to_string(),
                    contract_id: "contract-txn-002".to_string(),
                    tags: vec![],
                    custom_properties: None,
                    authoritative_definitions: None,
                },
            ]),
            output_ports: Some(vec![
                ODPSOutputPort {
                    name: "customer-profile".to_string(),
                    version: "2.1.0".to_string(),
                    description: Some("Unified customer profile with demographics, preferences, and behavioral scores".to_string()),
                    r#type: Some("table".to_string()),
                    contract_id: Some("contract-profile-001".to_string()),
                    sbom: None,
                    input_contracts: None,
                    tags: vec![],
                    custom_properties: None,
                    authoritative_definitions: None,
                },
                ODPSOutputPort {
                    name: "customer-segments".to_string(),
                    version: "1.5.0".to_string(),
                    description: Some("Customer segmentation based on RFM analysis and behavioral clustering".to_string()),
                    r#type: Some("table".to_string()),
                    contract_id: Some("contract-segments-001".to_string()),
                    sbom: None,
                    input_contracts: None,
                    tags: vec![],
                    custom_properties: None,
                    authoritative_definitions: None,
                },
            ]),
            management_ports: None,
            support: Some(vec![ODPSSupport {
                channel: "Slack".to_string(),
                url: "https://acme.slack.com/channels/customer-data".to_string(),
                description: Some("Primary support channel for data product questions".to_string()),
                tool: Some("Slack".to_string()),
                scope: None,
                invitation_url: None,
                tags: vec![],
                custom_properties: None,
                authoritative_definitions: None,
            }]),
            team: Some(ODPSTeam {
                name: Some("Customer Data Team".to_string()),
                description: Some("Responsible for customer data products and analytics".to_string()),
                members: Some(vec![
                    ODPSTeamMember {
                        username: "john.doe@acme.com".to_string(),
                        name: Some("John Doe".to_string()),
                        role: Some("Product Owner".to_string()),
                        description: None,
                        date_in: None,
                        date_out: None,
                        replaced_by_username: None,
                        tags: vec![],
                        custom_properties: None,
                        authoritative_definitions: None,
                    },
                    ODPSTeamMember {
                        username: "jane.smith@acme.com".to_string(),
                        name: Some("Jane Smith".to_string()),
                        role: Some("Data Engineer".to_string()),
                        description: None,
                        date_in: None,
                        date_out: None,
                        replaced_by_username: None,
                        tags: vec![],
                        custom_properties: None,
                        authoritative_definitions: None,
                    },
                ]),
                tags: vec![],
                custom_properties: None,
                authoritative_definitions: None,
            }),
            product_created_ts: None,
            created_at: Some(chrono::Utc::now()),
            updated_at: Some(chrono::Utc::now()),
        };

        let result = exporter.export_data_product(&product).unwrap();
        let pdf_bytes = base64::engine::general_purpose::STANDARD
            .decode(&result.pdf_base64)
            .unwrap();
        std::fs::write("/tmp/sample_data_product.pdf", &pdf_bytes).unwrap();
        println!(
            "Wrote /tmp/sample_data_product.pdf ({} bytes)",
            pdf_bytes.len()
        );

        // Export CADS Asset
        use crate::models::cads::{
            CADSAsset, CADSDescription, CADSImpactArea, CADSKind, CADSRisk, CADSRiskClassification,
            CADSRuntime, CADSRuntimeResources, CADSStatus, CADSTeamMember,
        };

        let asset = CADSAsset {
            api_version: "v1.0".to_string(),
            kind: CADSKind::AIModel,
            id: "urn:cads:ai-model:sentiment-analysis:v2".to_string(),
            name: "Customer Sentiment Analysis Model".to_string(),
            version: "2.3.1".to_string(),
            status: CADSStatus::Production,
            domain: Some("Natural Language Processing".to_string()),
            domain_id: None,
            tags: vec![],
            description: Some(CADSDescription {
                purpose: Some("Analyzes customer feedback, reviews, and support tickets to determine sentiment polarity (positive, negative, neutral) and emotion categories.".to_string()),
                usage: Some("Send text via REST API to /v2/predict endpoint. Supports batch processing up to 100 items per request.".to_string()),
                limitations: Some("English language only. Maximum 5000 characters per text input. Not suitable for sarcasm detection.".to_string()),
                external_links: None,
            }),
            runtime: Some(CADSRuntime {
                environment: Some("Kubernetes".to_string()),
                endpoints: Some(vec![
                    "https://api.example.com/ml/sentiment/v2".to_string(),
                ]),
                container: None,
                resources: Some(CADSRuntimeResources {
                    cpu: Some("4 cores".to_string()),
                    memory: Some("16 GB".to_string()),
                    gpu: Some("1x NVIDIA T4".to_string()),
                }),
            }),
            sla: None,
            pricing: None,
            team: Some(vec![
                CADSTeamMember {
                    role: "Model Owner".to_string(),
                    name: "Dr. Sarah Chen".to_string(),
                    contact: Some("sarah.chen@example.com".to_string()),
                },
                CADSTeamMember {
                    role: "ML Engineer".to_string(),
                    name: "Alex Kumar".to_string(),
                    contact: Some("alex.kumar@example.com".to_string()),
                },
            ]),
            risk: Some(CADSRisk {
                classification: Some(CADSRiskClassification::Medium),
                impact_areas: Some(vec![CADSImpactArea::Fairness, CADSImpactArea::Privacy]),
                intended_use: Some("Analyzing customer sentiment for product improvement and support prioritization".to_string()),
                out_of_scope_use: Some("Medical diagnosis, legal decisions, credit scoring".to_string()),
                assessment: None,
                mitigations: None,
            }),
            compliance: None,
            validation_profiles: None,
            bpmn_models: None,
            dmn_models: None,
            openapi_specs: None,
            custom_properties: None,
            created_at: Some(chrono::Utc::now()),
            updated_at: Some(chrono::Utc::now()),
        };

        let result = exporter.export_cads_asset(&asset).unwrap();
        let pdf_bytes = base64::engine::general_purpose::STANDARD
            .decode(&result.pdf_base64)
            .unwrap();
        std::fs::write("/tmp/sample_cads_asset.pdf", &pdf_bytes).unwrap();
        println!(
            "Wrote /tmp/sample_cads_asset.pdf ({} bytes)",
            pdf_bytes.len()
        );
    }
}