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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""

DOCX to PDF Converter with Perfect Formatting Preservation

Optimized for Hugging Face Spaces with LibreOffice headless mode

Supports Arabic RTL text and preserves all original formatting

"""

import subprocess
import tempfile
import shutil
import os
from pathlib import Path
import zipfile
import re
import json
import xml.etree.ElementTree as ET
from xml.dom import minidom

import threading
import time

def internal_keepalive():
    while True:
        print("[KeepAlive] ✅ Still alive and running...")
        time.sleep(300)  # كل 5 دقائق

# 🚀 تشغيل الخيط في الخلفية (غير متزامن)
threading.Thread(target=internal_keepalive, daemon=True).start()



def setup_libreoffice():
    """Ensure LibreOffice is properly configured for headless operation with optimal font setup"""
    try:
        # Setup font cache and configuration
        setup_font_environment()

        # Test LibreOffice installation
        result = subprocess.run(
            ["libreoffice", "--version"],
            capture_output=True,
            text=True,
            timeout=10
        )
        if result.returncode != 0:
            raise Exception("LibreOffice not found or not working")

        print(f"LibreOffice version: {result.stdout.strip()}")
        return True
    except Exception as e:
        print(f"LibreOffice setup error: {e}")
        return False


def setup_font_environment():
    """Setup optimal font environment using local Arial font and Arabic RTL support"""
    try:
        # Setup local Arial font from fonts directory
        setup_local_arial_font()

        # Install additional Arabic fonts if not available
        install_arabic_fonts()

        # Update font cache for better font discovery (fc-cache comes with fontconfig package)
        print("Updating font cache...")
        fc_result = subprocess.run(["fc-cache", "-fv"], capture_output=True, timeout=30)
        if fc_result.returncode != 0:
            print(f"Font cache update warning: {fc_result.stderr.decode('utf-8', errors='ignore')}")
        else:
            print("Font cache updated successfully")

        # List available fonts for debugging
        font_result = subprocess.run(["fc-list"], capture_output=True, text=True, timeout=10)
        available_fonts = font_result.stdout

        # Check for critical fonts including Arabic fonts and local Arial
        critical_fonts = ["Arial", "Liberation Sans", "Carlito", "Caladea", "DejaVu Sans", "Noto Sans",
                         "Noto Naskh Arabic", "Noto Kufi Arabic", "Amiri", "Scheherazade New"]
        missing_fonts = []

        for font in critical_fonts:
            if font.lower() not in available_fonts.lower():
                missing_fonts.append(font)

        if missing_fonts:
            print(f"Warning: Missing critical fonts: {missing_fonts}")
        else:
            print("All critical fonts including local Arial and Arabic fonts are available")

        # Check specifically for Arabic font support
        arabic_fonts = ["Noto Naskh Arabic", "Noto Kufi Arabic", "Amiri", "Scheherazade New", "Traditional Arabic"]
        available_arabic = [font for font in arabic_fonts if font.lower() in available_fonts.lower()]
        print(f"Available Arabic fonts: {available_arabic}")

        # Check for local Arial font
        if "arial" in available_fonts.lower():
            print("✅ Local Arial font is available and ready for use")
        else:
            print("⚠️ Local Arial font not detected - will use fallback fonts")

        print(f"Total fonts available: {len(available_fonts.splitlines())}")

    except Exception as e:
        print(f"Font environment setup warning: {e}")


def setup_local_arial_font():
    """Setup local Arial font from same directory as this Python file"""
    try:
        # Get the directory where this Python file is located
        script_dir = Path(__file__).parent.absolute()

        # Path to Arial font in same directory as this script
        arial_font_path = script_dir / "arial.ttf"

        if not arial_font_path.exists():
            print(f"⚠️ Arial font not found at {arial_font_path}")
            print(f"   Script directory: {script_dir}")
            print(f"   Looking for: arial.ttf")
            # Try to find system Arial font as fallback
            system_arial_paths = [
                "/usr/share/fonts/truetype/freefont/FreeSans.ttf",
                "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
                "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf"
            ]
            
            for path in system_arial_paths:
                if os.path.exists(path):
                    print(f"✅ Using system font as Arial fallback: {path}")
                    # Create system fonts directory for local Arial in /tmp to avoid permission issues
                    system_fonts_dir = Path("/tmp/fonts/truetype/local-arial")
                    system_fonts_dir.mkdir(parents=True, exist_ok=True)
                    # Ensure proper permissions
                    try:
                        system_fonts_dir.chmod(0o777)
                    except PermissionError:
                        # If we can't change permissions, continue anyway
                        pass

                    # Copy Arial font to system directory
                    system_arial_path = system_fonts_dir / "arial.ttf"
                    if not system_arial_path.exists():
                        print("📥 Installing local Arial font...")
                        shutil.copy2(path, system_arial_path)
                        try:
                            system_arial_path.chmod(0o644)
                        except PermissionError:
                            # If we can't change permissions, continue anyway
                            pass
                        print("✅ Local Arial font installed successfully")
                    else:
                        print("✅ Local Arial font already installed")
                    return True
            return False

        # Create system fonts directory for local Arial in /tmp to avoid permission issues
        system_fonts_dir = Path("/tmp/fonts/truetype/local-arial")
        system_fonts_dir.mkdir(parents=True, exist_ok=True)
        # Ensure proper permissions
        try:
            system_fonts_dir.chmod(0o777)
        except PermissionError:
            # If we can't change permissions, continue anyway
            pass

        # Copy Arial font to system directory
        system_arial_path = system_fonts_dir / "arial.ttf"
        if not system_arial_path.exists():
            print("📥 Installing local Arial font...")
            shutil.copy2(arial_font_path, system_arial_path)
            try:
                system_arial_path.chmod(0o644)
            except PermissionError:
                # If we can't change permissions, continue anyway
                pass
            print("✅ Local Arial font installed successfully")
        else:
            print("✅ Local Arial font already installed")

        return True

    except Exception as e:
        print(f"❌ Local Arial font setup failed: {e}")
        return False


def install_arabic_fonts():
    """Install additional Arabic fonts for better RTL support"""
    try:
        import urllib.request
        import zipfile
        import tempfile

        # Create fonts directory in /tmp to avoid permission issues
        fonts_dir = Path("/tmp/fonts/truetype/arabic-custom")
        fonts_dir.mkdir(parents=True, exist_ok=True)
        # Ensure proper permissions
        try:
            fonts_dir.chmod(0o777)
        except PermissionError:
            # If we can't change permissions, continue anyway
            pass

        print("🔤 Installing Arabic fonts for RTL support...")

        # Download and install Amiri font
        print("📥 Installing Amiri font...")
        try:
            with tempfile.TemporaryDirectory() as tmp_dir:
                amiri_url = "https://github.com/aliftype/amiri/releases/download/0.117/Amiri-0.117.zip"
                amiri_zip = os.path.join(tmp_dir, "amiri.zip")

                urllib.request.urlretrieve(amiri_url, amiri_zip)

                with zipfile.ZipFile(amiri_zip, 'r') as zip_ref:
                    zip_ref.extractall(tmp_dir)

                amiri_dir = os.path.join(tmp_dir, "Amiri-0.117")
                if os.path.exists(amiri_dir):
                    for file in os.listdir(amiri_dir):
                        if file.endswith('.ttf'):
                            src = os.path.join(amiri_dir, file)
                            dst = fonts_dir / file
                            shutil.copy2(src, dst)
                            try:
                                dst.chmod(0o644)
                            except PermissionError:
                                # If we can't change permissions, continue anyway
                                pass
                    print("✅ Amiri font installed successfully")
                else:
                    print("❌ Amiri font directory not found")
        except Exception as e:
            print(f"❌ Amiri font installation failed: {e}")

        # Download and install Scheherazade New font
        print("📥 Installing Scheherazade New font...")
        try:
            with tempfile.TemporaryDirectory() as tmp_dir:
                scheherazade_url = "https://github.com/silnrsi/font-scheherazade/releases/download/v3.300/ScheherazadeNew-3.300.zip"
                scheherazade_zip = os.path.join(tmp_dir, "scheherazade.zip")

                urllib.request.urlretrieve(scheherazade_url, scheherazade_zip)

                with zipfile.ZipFile(scheherazade_zip, 'r') as zip_ref:
                    zip_ref.extractall(tmp_dir)

                scheherazade_dir = os.path.join(tmp_dir, "ScheherazadeNew-3.300")
                if os.path.exists(scheherazade_dir):
                    for file in os.listdir(scheherazade_dir):
                        if file.endswith('.ttf'):
                            src = os.path.join(scheherazade_dir, file)
                            dst = fonts_dir / file
                            shutil.copy2(src, dst)
                            try:
                                dst.chmod(0o644)
                            except PermissionError:
                                # If we can't change permissions, continue anyway
                                pass
                    print("✅ Scheherazade New font installed successfully")
                else:
                    print("❌ Scheherazade New font directory not found")
        except Exception as e:
            print(f"❌ Scheherazade New font installation failed: {e}")

        # Download and install Noto Sans Arabic font
        print("📥 Installing Noto Sans Arabic font...")
        try:
            with tempfile.TemporaryDirectory() as tmp_dir:
                noto_url = "https://github.com/notofonts/notofonts.github.io/raw/main/fonts/NotoSansArabic/hinted/ttf/NotoSansArabic-Regular.ttf"
                noto_file = os.path.join(tmp_dir, "NotoSansArabic-Regular.ttf")

                urllib.request.urlretrieve(noto_url, noto_file)

                dst = fonts_dir / "NotoSansArabic-Regular.ttf"
                shutil.copy2(noto_file, dst)
                try:
                    dst.chmod(0o644)
                except PermissionError:
                    # If we can't change permissions, continue anyway
                    pass
                print("✅ Noto Sans Arabic font installed successfully")
        except Exception as e:
            print(f"❌ Noto Sans Arabic font installation failed: {e}")

        # Download and install Cairo font (excellent for Arabic)
        print("📥 Installing Cairo font...")
        try:
            with tempfile.TemporaryDirectory() as tmp_dir:
                # Use a more reliable source for Cairo font
                cairo_url = "https://github.com/Gue3bara/Cairo/raw/master/fonts/Cairo-Regular.ttf"
                cairo_file = os.path.join(tmp_dir, "Cairo-Regular.ttf")

                urllib.request.urlretrieve(cairo_url, cairo_file)

                dst = fonts_dir / "Cairo-Regular.ttf"
                shutil.copy2(cairo_file, dst)
                try:
                    dst.chmod(0o644)
                except PermissionError:
                    # If we can't change permissions, continue anyway
                    pass
                print("✅ Cairo font installed successfully")
        except Exception as e:
            print(f"❌ Cairo font installation failed: {e}")
            print("⚠️ Continuing without Cairo font - using alternative Arabic fonts")

            try:
                with tempfile.TemporaryDirectory() as tmp_dir:
                    # Alternative Cairo font URL
                    cairo_url = "https://fonts.gstatic.com/s/cairo/v21/SLXgc14kyrzQ6fYy3Q60fTh5Tf44DXYvbqo6vPQ3ZyM.woff2"
                    cairo_file = os.path.join(tmp_dir, "Cairo-Regular.woff2")
                    
                    urllib.request.urlretrieve(cairo_url, cairo_file)
                    
                    # Convert WOFF2 to TTF using fontTools if available
                    try:
                        from fontTools.ttLib import TTFont
                        # For now, just acknowledge the download
                        print("✅ Cairo font (alternative source) downloaded successfully")
                    except ImportError:
                        print("ℹ️ Cairo font downloaded but font conversion tools not available")
                print("✅ Cairo font installed successfully (alternative source)")
            except Exception as e2:
                print(f"❌ Cairo font installation failed (alternative source): {e2}")

        # Update font cache after installation
        print("🔄 Updating font cache...")
        try:
            subprocess.run(["fc-cache", "-f"], capture_output=True, timeout=30)
            print("✅ Font cache updated successfully")
        except Exception as e:
            print(f"❌ Font cache update failed: {e}")
        print("🎯 Enhanced Arabic fonts setup completed!")

    except Exception as e:
        print(f"Arabic fonts installation warning: {e}")


def create_fontconfig(temp_path):
    """Create fontconfig configuration for optimal font matching with local Arial and Arabic RTL support"""
    fontconfig_dir = temp_path / ".config" / "fontconfig"
    fontconfig_dir.mkdir(parents=True, exist_ok=True)

    # Create fonts.conf
    fonts_conf = fontconfig_dir / "fonts.conf"

    # Get script directory for local fonts
    script_dir = Path(__file__).parent.absolute()

    fontconfig_content = f'''<?xml version="1.0"?>

<!DOCTYPE fontconfig SYSTEM "fonts.dtd">

<fontconfig>

  <!-- Add system fonts directories -->

  <dir>/usr/share/fonts</dir>

  <dir>/usr/local/share/fonts</dir>

  <dir>~/.fonts</dir>



  <!-- Add local fonts directory (same as Python script) -->

  <dir>/tmp/fonts/truetype/local-arial</dir>

  <dir>{script_dir}</dir>



  <!-- Font substitution rules with local Arial as priority -->

  <alias>

    <family>Arial</family>

    <prefer>

      <family>Arial</family>

      <family>Liberation Sans</family>

      <family>DejaVu Sans</family>

      <family>Noto Sans</family>

    </prefer>

  </alias>



  <alias>

    <family>Calibri</family>

    <prefer>

      <family>Liberation Sans</family>

      <family>Arimo</family>

      <family>DejaVu Sans</family>

    </prefer>

  </alias>



  <alias>

    <family>Cambria</family>

    <prefer>

      <family>Liberation Serif</family>

      <family>Tinos</family>

      <family>DejaVu Serif</family>

    </prefer>

  </alias>



  <alias>

    <family>Times New Roman</family>

    <prefer>

      <family>Liberation Serif</family>

      <family>DejaVu Serif</family>

      <family>Noto Serif</family>

    </prefer>

  </alias>



  <alias>

    <family>Courier New</family>

    <prefer>

      <family>Liberation Mono</family>

      <family>DejaVu Sans Mono</family>

      <family>Noto Sans Mono</family>

    </prefer>

  </alias>



  <!-- Enhanced Arabic font substitution rules for perfect RTL support -->

  <alias>

    <family>Traditional Arabic</family>

    <prefer>

      <family>Amiri</family>

      <family>Noto Naskh Arabic</family>

      <family>Scheherazade New</family>

      <family>Cairo</family>

      <family>Noto Sans Arabic</family>

      <family>DejaVu Sans</family>

    </prefer>

  </alias>



  <alias>

    <family>Arabic Typesetting</family>

    <prefer>

      <family>Amiri</family>

      <family>Noto Naskh Arabic</family>

      <family>Scheherazade New</family>

      <family>Cairo</family>

      <family>Noto Sans Arabic</family>

    </prefer>

  </alias>



  <alias>

    <family>Simplified Arabic</family>

    <prefer>

      <family>Noto Sans Arabic</family>

      <family>Cairo</family>

      <family>Noto Naskh Arabic</family>

      <family>Amiri</family>

      <family>DejaVu Sans</family>

    </prefer>

  </alias>



  <!-- Additional Arabic font mappings for maximum compatibility -->

  <alias>

    <family>Arial Unicode MS</family>

    <prefer>

      <family>Noto Sans Arabic</family>

      <family>Cairo</family>

      <family>Liberation Sans</family>

      <family>DejaVu Sans</family>

    </prefer>

  </alias>



  <alias>

    <family>Microsoft Sans Serif</family>

    <prefer>

      <family>Noto Sans Arabic</family>

      <family>Liberation Sans</family>

      <family>DejaVu Sans</family>

    </prefer>

  </alias>



  <alias>

    <family>Segoe UI</family>

    <prefer>

      <family>Noto Sans Arabic</family>

      <family>Cairo</family>

      <family>Liberation Sans</family>

      <family>DejaVu Sans</family>

    </prefer>

  </alias>



  <alias>

    <family>Tahoma</family>

    <prefer>

      <family>DejaVu Sans</family>

      <family>Liberation Sans</family>

      <family>Noto Sans</family>

    </prefer>

  </alias>



  <!-- Generic Arabic font fallback -->

  <alias>

    <family>serif</family>

    <prefer>

      <family>Liberation Serif</family>

      <family>DejaVu Serif</family>

      <family>Amiri</family>

      <family>Noto Naskh Arabic</family>

    </prefer>

  </alias>



  <alias>

    <family>sans-serif</family>

    <prefer>

      <family>Liberation Sans</family>

      <family>DejaVu Sans</family>

      <family>Noto Sans</family>

      <family>Noto Naskh Arabic</family>

    </prefer>

  </alias>



  <alias>

    <family>monospace</family>

    <prefer>

      <family>Liberation Mono</family>

      <family>DejaVu Sans Mono</family>

      <family>Noto Sans Mono</family>

    </prefer>

  </alias>



  <!-- Ensure consistent font rendering with Arabic support -->

  <match target="font">

    <edit name="antialias" mode="assign">

      <bool>true</bool>

    </edit>

    <edit name="hinting" mode="assign">

      <bool>true</bool>

    </edit>

    <edit name="hintstyle" mode="assign">

      <const>hintslight</const>

    </edit>

    <edit name="rgba" mode="assign">

      <const>rgb</const>

    </edit>

    <edit name="lcdfilter" mode="assign">

      <const>lcddefault</const>

    </edit>

  </match>



  <!-- Enhanced Arabic script handling with strong binding -->

  <match target="pattern">

    <test name="lang" compare="contains">

      <string>ar</string>

    </test>

    <edit name="family" mode="prepend" binding="strong">

      <string>Amiri</string>

      <string>Noto Naskh Arabic</string>

      <string>Scheherazade New</string>

      <string>Cairo</string>

      <string>Noto Sans Arabic</string>

    </edit>

  </match>



  <!-- Force Arabic fonts for any Arabic-containing text -->

  <match target="pattern">

    <test name="family" compare="contains">

      <string>Arabic</string>

    </test>

    <edit name="family" mode="prepend" binding="strong">

      <string>Amiri</string>

      <string>Noto Naskh Arabic</string>

      <string>Scheherazade New</string>

      <string>Cairo</string>

    </edit>

  </match>



  <!-- Ensure proper spacing and kerning for Arabic -->

  <match target="font">

    <test name="family" compare="contains">

      <string>Arabic</string>

    </test>

    <edit name="spacing" mode="assign">

      <const>proportional</const>

    </edit>

    <edit name="antialias" mode="assign">

      <bool>true</bool>

    </edit>

    <edit name="hinting" mode="assign">

      <bool>true</bool>

    </edit>

    <edit name="hintstyle" mode="assign">

      <const>hintslight</const>

    </edit>

  </match>



  <!-- Specific handling for RTL text -->

  <match target="pattern">

    <test name="charset">

      <charset>

        <range>

          <int>0x0600</int>

          <int>0x06FF</int>

        </range>

      </charset>

    </test>

    <edit name="family" mode="prepend" binding="strong">

      <string>Amiri</string>

      <string>Noto Naskh Arabic</string>

      <string>Scheherazade New</string>

      <string>Cairo</string>

    </edit>

  </match>

</fontconfig>'''

    with open(fonts_conf, 'w', encoding='utf-8') as f:
        f.write(fontconfig_content)

    return str(fontconfig_dir.parent)


def analyze_template_font_sizes(docx_path):
    """Analyze template.docx to extract specific font size requirements"""
    try:
        font_size_mapping = {}

        with zipfile.ZipFile(docx_path, 'r') as docx:
            if 'word/document.xml' in docx.namelist():
                doc_content = docx.read('word/document.xml').decode('utf-8')

                # Extract text runs with their font sizes
                import xml.etree.ElementTree as ET
                root = ET.fromstring(doc_content)

                # Define namespaces
                namespaces = {
                    'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
                }

                # Find all text runs and their font sizes
                for run in root.findall('.//w:r', namespaces):
                    # Get font size from run properties
                    rpr = run.find('w:rPr', namespaces)
                    if rpr is not None:
                        sz_elem = rpr.find('w:sz', namespaces)
                        if sz_elem is not None:
                            font_size = int(sz_elem.get('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val', '20')) // 2  # Convert half-points to points
                        else:
                            font_size = 10  # Smaller default
                    else:
                        font_size = 10  # Smaller default

                    # Get text content
                    text_elements = run.findall('.//w:t', namespaces)
                    for text_elem in text_elements:
                        text_content = text_elem.text
                        if text_content and text_content.strip():
                            # Map specific text patterns to font sizes
                            text_content = text_content.strip()

                            # Check for specific patterns mentioned by user (smaller sizes)
                            if any(pattern in text_content for pattern in ['{{serial_number}}', '{{t_11}}', '{{t_}}', '{{date}}']):
                                font_size_mapping[text_content] = 9  # Smaller size for serial/date
                            elif any(pattern in text_content for pattern in ['{{name_1}}', '{{name_2}}', '{{id_1}}', '{{name_3}}', '{{id_2}}']):
                                font_size_mapping[text_content] = 10  # Smaller size for names/IDs
                            elif any(pattern in text_content for pattern in ['{{location_1}}', '{{location_2}}', '{{phone_1}}', '{{location_3}}', '{{phone_2}}']):
                                font_size_mapping[text_content] = 10  # Smaller size for locations/phones
                            elif any(pattern in text_content for pattern in ['الطرف البائع', 'الطرف المشتري']):
                                font_size_mapping[text_content] = 11  # Smaller size for main headers
                            else:
                                # Default size for other text (smaller)
                                font_size_mapping[text_content] = min(font_size, 10)  # Cap at size 10

                print(f"📏 Font size analysis completed: {len(font_size_mapping)} text patterns mapped")
                return font_size_mapping

    except Exception as e:
        print(f"❌ Font size analysis failed: {e}")
        return {}


def validate_docx_structure(docx_path):
    """Advanced DOCX structure analysis and preprocessing for perfect formatting preservation"""
    try:
        validation_info = {
            'page_count': 1,  # Default assumption
            'has_tables': False,
            'has_images': False,
            'text_content_length': 0,
            'font_families': set(),
            'has_textboxes': False,
            'has_smartart': False,
            'has_complex_shapes': False,
            'table_structure_issues': [],
            'rtl_content_detected': False,
            'placeholder_count': 0,
            'font_size_mapping': {},
            'error': None
        }

        # Analyze font sizes for template.docx
        if 'template.docx' in docx_path:
            validation_info['font_size_mapping'] = analyze_template_font_sizes(docx_path)

        with zipfile.ZipFile(docx_path, 'r') as docx:
            # Check document.xml for content analysis
            if 'word/document.xml' in docx.namelist():
                doc_content = docx.read('word/document.xml').decode('utf-8')

                # Count tables and analyze structure
                table_count = doc_content.count('<w:tbl>')
                validation_info['has_tables'] = table_count > 0

                # Advanced table structure analysis
                if validation_info['has_tables']:
                    # Check for nested tables (problematic for formatting)
                    nested_tables = doc_content.count('<w:tbl>') - doc_content.count('</w:tbl>')
                    if nested_tables != 0:
                        validation_info['table_structure_issues'].append("Nested tables detected")

                    # Check for merged cells that might cause layout issues
                    if '<w:gridSpan' in doc_content or '<w:vMerge' in doc_content:
                        validation_info['table_structure_issues'].append("Complex cell merging detected")

                # Check for problematic elements that LibreOffice handles poorly
                validation_info['has_textboxes'] = '<w:textbox>' in doc_content or '<w:txbxContent>' in doc_content
                validation_info['has_smartart'] = '<w:smartTag>' in doc_content or 'smartart' in doc_content.lower()
                validation_info['has_complex_shapes'] = '<w:shape>' in doc_content or '<w:group>' in doc_content

                # Check for images with enhanced detection
                validation_info['has_images'] = ('<w:drawing>' in doc_content or
                                                '<w:pict>' in doc_content or
                                                '<w:object>' in doc_content)

                # Detect RTL content and Arabic text
                arabic_pattern = r'[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]'
                validation_info['rtl_content_detected'] = bool(re.search(arabic_pattern, doc_content))

                # Count placeholders ({{...}}) that must not be moved
                placeholder_pattern = r'\{\{[^}]+\}\}'
                validation_info['placeholder_count'] = len(re.findall(placeholder_pattern, doc_content))

                # Estimate text content length
                text_content = re.sub(r'<[^>]+>', '', doc_content)
                validation_info['text_content_length'] = len(text_content.strip())

                # Enhanced font extraction including Arabic fonts
                font_matches = re.findall(r'w:ascii="([^"]+)"', doc_content)
                eastasia_fonts = re.findall(r'w:eastAsia="([^"]+)"', doc_content)
                cs_fonts = re.findall(r'w:cs="([^"]+)"', doc_content)  # Complex Script fonts (Arabic)

                all_fonts = set(font_matches + eastasia_fonts + cs_fonts)
                validation_info['font_families'] = all_fonts

                print(f"🔍 Advanced DOCX Analysis:")
                print(f"  • Tables: {table_count} (Issues: {len(validation_info['table_structure_issues'])})")
                print(f"  • Images: {validation_info['has_images']}")
                print(f"  • TextBoxes: {validation_info['has_textboxes']}")
                print(f"  • SmartArt: {validation_info['has_smartart']}")
                print(f"  • Complex Shapes: {validation_info['has_complex_shapes']}")
                print(f"  • RTL Content: {validation_info['rtl_content_detected']}")
                print(f"  • Placeholders: {validation_info['placeholder_count']}")
                print(f"  • Text Length: {validation_info['text_content_length']}")
                print(f"  • Fonts: {list(validation_info['font_families'])[:5]}...")

        return validation_info

    except Exception as e:
        print(f"❌ DOCX validation error: {e}")
        return {'page_count': 1, 'has_tables': False, 'has_images': False,
                'text_content_length': 0, 'font_families': set(), 'has_textboxes': False,
                'has_smartart': False, 'has_complex_shapes': False, 'table_structure_issues': [],
                'rtl_content_detected': False, 'placeholder_count': 0, 'error': str(e)}


def calculate_optimal_font_size(text_content, max_width_chars=20, base_font_size=10):
    """

    Calculate optimal font size based on text length to maintain position

    This ensures that longer names don't break the layout

    """
    if not text_content:
        return base_font_size

    # Remove placeholder brackets if present
    clean_text = text_content.replace('{{', '').replace('}}', '').strip()
    text_length = len(clean_text)

    # If text is short, use base font size
    if text_length <= max_width_chars:
        return base_font_size

    # Calculate reduction factor based on text length
    # The longer the text, the smaller the font should be
    reduction_factor = max_width_chars / text_length

    # Apply reduction but don't go below 7pt (14 half-points)
    optimal_size = max(base_font_size * reduction_factor, 7)

    return int(optimal_size)


def extract_placeholder_contexts(doc_content):
    """

    Extract placeholders with their surrounding context to understand layout constraints

    """
    placeholder_contexts = {}

    # Find all placeholders with their XML context
    placeholder_pattern = r'(<w:r[^>]*>.*?<w:t[^>]*>.*?\{\{[^}]+\}\}.*?</w:t>.*?</w:r>)'
    matches = re.findall(placeholder_pattern, doc_content, re.DOTALL)

    for match in matches:
        # Extract the placeholder name
        placeholder_match = re.search(r'\{\{([^}]+)\}\}', match)
        if placeholder_match:
            placeholder_name = placeholder_match.group(1)

            # Extract current font size if present
            font_size_match = re.search(r'<w:sz w:val="(\d+)"/>', match)
            current_font_size = int(font_size_match.group(1)) // 2 if font_size_match else 10

            # Check if this is in a table cell (more constrained space)
            is_in_table = '<w:tc>' in match or 'w:tcPr' in match

            # Estimate available width based on context
            if is_in_table:
                max_width_chars = 15  # Table cells are more constrained
            else:
                max_width_chars = 25  # Regular text has more space

            placeholder_contexts[placeholder_name] = {
                'current_font_size': current_font_size,
                'max_width_chars': max_width_chars,
                'is_in_table': is_in_table,
                'xml_context': match
            }

    return placeholder_contexts


def apply_template_font_settings(docx_path, validation_info):
    """Apply specific font sizes and Arial font to template.docx content with smart sizing"""
    try:
        if not validation_info.get('font_size_mapping'):
            print("ℹ️ No font size mapping found - skipping font optimization")
            return docx_path

        print("🔤 Applying template-specific font settings with smart sizing...")

        # Create a temporary copy for processing
        temp_docx = tempfile.mktemp(suffix='.docx')
        shutil.copy2(docx_path, temp_docx)

        with zipfile.ZipFile(temp_docx, 'a') as docx_zip:
            if 'word/document.xml' in docx_zip.namelist():
                doc_content = docx_zip.read('word/document.xml').decode('utf-8')

                # Apply Arial font to all text runs
                # Replace font family declarations with Arial
                doc_content = re.sub(
                    r'w:ascii="[^"]*"',
                    'w:ascii="Arial"',
                    doc_content
                )
                doc_content = re.sub(
                    r'w:hAnsi="[^"]*"',
                    'w:hAnsi="Arial"',
                    doc_content
                )

                # Extract placeholder contexts for smart sizing
                placeholder_contexts = extract_placeholder_contexts(doc_content)
                print(f"📍 Found {len(placeholder_contexts)} placeholders with context")

                # Apply smart font sizing for name placeholders
                name_placeholders = ['name_1', 'name_2', 'name_3']
                for placeholder in name_placeholders:
                    if placeholder in placeholder_contexts:
                        context = placeholder_contexts[placeholder]

                        # Calculate optimal font size for typical Arabic names
                        # Assume names can be 15-30 characters (ثلاثي أو رباعي)
                        optimal_size = calculate_optimal_font_size(
                            "محمد عبدالله أحمد الخالدي",  # Example long name
                            max_width_chars=context['max_width_chars'],
                            base_font_size=context['current_font_size']
                        )

                        # Apply the calculated font size (convert to half-points)
                        optimal_size_half_points = int(optimal_size * 2)

                        pattern = f'{{{{{placeholder}}}}}'
                        if pattern in doc_content:
                            doc_content = re.sub(
                                r'(<w:r[^>]*>.*?' + re.escape(pattern) + r'.*?<w:sz w:val=")[^"]*(")',
                                f'\\g<1>{optimal_size_half_points}\\g<2>',
                                doc_content,
                                flags=re.DOTALL
                            )
                            print(f"🎯 Applied smart sizing to {placeholder}: {optimal_size}pt")

                # Apply size 9 for serial number, date, time elements (smaller size)
                for pattern in ['{{serial_number}}', '{{t_11}}', '{{t_}}', '{{date}}', 'الرقم التسلسلي', 'الساعة', 'التاريخ']:
                    if pattern in doc_content:
                        # Find the text run containing this pattern and set font size to 9 (18 half-points)
                        doc_content = re.sub(
                            r'(<w:r[^>]*>.*?' + re.escape(pattern) + r'.*?<w:sz w:val=")[^"]*(")',
                            r'\g<1>18\g<2>',
                            doc_content,
                            flags=re.DOTALL
                        )

                # Apply size 10 for IDs, locations, phones (smaller size)
                for pattern in ['{{id_1}}', '{{id_2}}',
                               '{{location_1}}', '{{location_2}}', '{{phone_1}}', '{{location_3}}', '{{phone_2}}',
                               'رقم الهوية', 'يسكن', 'رقم الهاتف']:
                    if pattern in doc_content:
                        # Set font size to 10 (20 half-points)
                        doc_content = re.sub(
                            r'(<w:r[^>]*>.*?' + re.escape(pattern) + r'.*?<w:sz w:val=")[^"]*(")',
                            r'\g<1>20\g<2>',
                            doc_content,
                            flags=re.DOTALL
                        )

                # Apply size 11 for "الطرف البائع" and "الطرف المشتري" (smaller size)
                for pattern in ['الطرف البائع', 'الطرف المشتري']:
                    if pattern in doc_content:
                        # Set font size to 11 (22 half-points)
                        doc_content = re.sub(
                            r'(<w:r[^>]*>.*?' + re.escape(pattern) + r'.*?<w:sz w:val=")[^"]*(")',
                            r'\g<1>22\g<2>',
                            doc_content,
                            flags=re.DOTALL
                        )

                # Apply general font size reduction for all text (reduce large fonts)
                print("🔤 Applying general font size optimization...")
                # Find all font sizes and reduce if they're too large
                font_size_pattern = r'<w:sz w:val="(\d+)"/>'
                def reduce_font_size(match):
                    size = int(match.group(1))
                    # Convert half-points to points for comparison
                    size_in_points = size // 2

                    # If font is larger than 12pt, reduce it
                    if size_in_points > 12:
                        new_size_points = min(size_in_points * 0.8, 12)  # Reduce by 20% but cap at 12pt
                        new_size_half_points = int(new_size_points * 2)
                        return f'<w:sz w:val="{new_size_half_points}"/>'
                    elif size_in_points > 10:
                        # For medium sizes, reduce slightly
                        new_size_points = size_in_points * 0.9  # Reduce by 10%
                        new_size_half_points = int(new_size_points * 2)
                        return f'<w:sz w:val="{new_size_half_points}"/>'
                    else:
                        # Keep small fonts as they are
                        return match.group(0)

                doc_content = re.sub(font_size_pattern, reduce_font_size, doc_content)

                # Write back the modified document.xml
                docx_zip.writestr('word/document.xml', doc_content.encode('utf-8'))
                print("✅ Template font settings with smart sizing applied successfully")

        return temp_docx

    except Exception as e:
        print(f"❌ Font settings application failed: {e}")
        return docx_path


def create_dynamic_font_sizing_rules(docx_path):
    """

    Create dynamic font sizing rules based on actual content analysis

    This function analyzes the document to create smart sizing rules

    """
    try:
        dynamic_rules = {}

        with zipfile.ZipFile(docx_path, 'r') as docx:
            if 'word/document.xml' in docx.namelist():
                doc_content = docx.read('word/document.xml').decode('utf-8')

                # Find all placeholders and their current context
                placeholder_pattern = r'\{\{([^}]+)\}\}'
                placeholders = re.findall(placeholder_pattern, doc_content)

                for placeholder in placeholders:
                    # Analyze the context around each placeholder
                    context_pattern = f'(<w:tc[^>]*>.*?\\{{{{' + re.escape(placeholder) + r'\\}}}}.*?</w:tc>)'
                    table_cell_match = re.search(context_pattern, doc_content, re.DOTALL)

                    if table_cell_match:
                        # This placeholder is in a table cell
                        cell_content = table_cell_match.group(1)

                        # Estimate cell width based on content and structure
                        # Look for width specifications
                        width_match = re.search(r'w:w="(\d+)"', cell_content)
                        if width_match:
                            cell_width = int(width_match.group(1))
                            # Convert twips to approximate character width
                            # 1440 twips = 1 inch, average character = 0.1 inch
                            estimated_chars = max(cell_width // 144, 10)  # Minimum 10 chars
                        else:
                            estimated_chars = 15  # Default for table cells

                        # Check if there are other elements in the same cell
                        text_elements = re.findall(r'<w:t[^>]*>([^<]+)</w:t>', cell_content)
                        total_text_length = sum(len(text.replace(f'{{{{{placeholder}}}}}', '')) for text in text_elements)

                        # Adjust available space based on other content
                        available_chars = max(estimated_chars - total_text_length, 8)

                        dynamic_rules[placeholder] = {
                            'max_chars': available_chars,
                            'context': 'table_cell',
                            'base_font_size': 10,
                            'min_font_size': 7
                        }
                    else:
                        # This placeholder is in regular text
                        dynamic_rules[placeholder] = {
                            'max_chars': 25,
                            'context': 'paragraph',
                            'base_font_size': 11,
                            'min_font_size': 8
                        }

                print(f"📏 Created dynamic sizing rules for {len(dynamic_rules)} placeholders")
                return dynamic_rules

    except Exception as e:
        print(f"❌ Dynamic rules creation failed: {e}")
        return {}


def apply_dynamic_font_sizing(docx_path, dynamic_rules, sample_data=None):
    """

    Apply dynamic font sizing based on actual or sample data

    This ensures that when placeholders are replaced, the text fits perfectly

    """
    if not dynamic_rules:
        return docx_path

    try:
        print("🎯 Applying dynamic font sizing based on content analysis...")

        # Create sample data if not provided
        if not sample_data:
            sample_data = {
                'name_1': 'محمد عبدالله أحمد الخالدي',  # Long Arabic name
                'name_2': 'فاطمة سعد محمد العتيبي',      # Long Arabic name
                'name_3': 'عبدالرحمن خالد سليمان',      # Medium Arabic name
                'id_1': '1234567890',
                'id_2': '0987654321',
                'location_1': 'الرياض - حي الملك فهد - شارع الأمير محمد بن عبدالعزيز',
                'location_2': 'جدة - حي الصفا - طريق الملك عبدالعزيز',
                'phone_1': '+966501234567',
                'phone_2': '+966509876543'
            }

        # Create a temporary copy for processing
        temp_docx = tempfile.mktemp(suffix='.docx')
        shutil.copy2(docx_path, temp_docx)

        with zipfile.ZipFile(temp_docx, 'a') as docx_zip:
            if 'word/document.xml' in docx_zip.namelist():
                doc_content = docx_zip.read('word/document.xml').decode('utf-8')

                # Apply dynamic sizing for each placeholder
                for placeholder, rules in dynamic_rules.items():
                    if placeholder in sample_data:
                        sample_text = sample_data[placeholder]

                        # Calculate optimal font size
                        optimal_size = calculate_optimal_font_size(
                            sample_text,
                            max_width_chars=rules['max_chars'],
                            base_font_size=rules['base_font_size']
                        )

                        # Ensure minimum font size
                        optimal_size = max(optimal_size, rules['min_font_size'])

                        # Convert to half-points for Word
                        optimal_size_half_points = int(optimal_size * 2)

                        # Apply the font size to this placeholder
                        pattern = f'{{{{{placeholder}}}}}'
                        if pattern in doc_content:
                            # Find and update font size for this specific placeholder
                            placeholder_pattern = r'(<w:r[^>]*>.*?' + re.escape(pattern) + r'.*?<w:sz w:val=")[^"]*(")'
                            doc_content = re.sub(
                                placeholder_pattern,
                                f'\\g<1>{optimal_size_half_points}\\g<2>',
                                doc_content,
                                flags=re.DOTALL
                            )

                            # Also ensure Arial font is applied to this placeholder
                            placeholder_font_pattern = r'(<w:r[^>]*>.*?' + re.escape(pattern) + r'.*?<w:rFonts[^>]*w:ascii=")[^"]*(")'
                            doc_content = re.sub(
                                placeholder_font_pattern,
                                r'\g<1>Arial\g<2>',
                                doc_content,
                                flags=re.DOTALL
                            )

                            # Add font binding to ensure Arial is used
                            placeholder_run_pattern = r'(<w:r[^>]*>)(.*?' + re.escape(pattern) + r'.*?)(</w:r>)'
                            def add_font_binding(match):
                                run_start = match.group(1)
                                run_content = match.group(2)
                                run_end = match.group(3)

                                # Check if rPr (run properties) exists
                                if '<w:rPr>' in run_content:
                                    # Add or update font information
                                    if '<w:rFonts' not in run_content:
                                        run_content = run_content.replace(
                                            '<w:rPr>',
                                            '<w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Arial"/>'
                                        )
                                else:
                                    # Add rPr with font information
                                    run_content = '<w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial" w:cs="Arial"/></w:rPr>' + run_content

                                return run_start + run_content + run_end

                            doc_content = re.sub(placeholder_run_pattern, add_font_binding, doc_content, flags=re.DOTALL)

                            print(f"🎯 {placeholder}: {optimal_size}pt Arial (max chars: {rules['max_chars']}, context: {rules['context']})")

                # Write back the modified document.xml
                docx_zip.writestr('word/document.xml', doc_content.encode('utf-8'))
                print("✅ Dynamic font sizing applied successfully")

        return temp_docx

    except Exception as e:
        print(f"❌ Dynamic font sizing failed: {e}")
        return docx_path


def preprocess_docx_for_perfect_conversion(docx_path, validation_info):
    """

    Advanced DOCX preprocessing to ensure maximum formatting preservation

    Removes problematic elements and optimizes structure for LibreOffice

    """
    # First apply template-specific font settings if this is template.docx
    if 'template.docx' in docx_path:
        docx_path = apply_template_font_settings(docx_path, validation_info)

        # Apply dynamic font sizing for better placeholder handling
        dynamic_rules = create_dynamic_font_sizing_rules(docx_path)
        if dynamic_rules:
            docx_path = apply_dynamic_font_sizing(docx_path, dynamic_rules)

    if not validation_info.get('has_textboxes') and not validation_info.get('has_smartart') and not validation_info.get('has_complex_shapes'):
        print("✅ DOCX structure is optimal - no additional preprocessing needed")
        return docx_path

    try:
        print("🔧 Preprocessing DOCX for perfect conversion...")

        # Create a temporary copy for processing
        temp_docx = tempfile.mktemp(suffix='.docx')
        shutil.copy2(docx_path, temp_docx)

        with zipfile.ZipFile(temp_docx, 'a') as docx_zip:
            # Read document.xml
            if 'word/document.xml' in docx_zip.namelist():
                doc_content = docx_zip.read('word/document.xml').decode('utf-8')

                # Remove problematic elements that LibreOffice handles poorly
                modifications_made = False

                # Remove TextBoxes (convert to regular paragraphs)
                if validation_info.get('has_textboxes'):
                    print("  • Converting TextBoxes to regular paragraphs...")
                    # Extract text from textboxes and convert to paragraphs
                    textbox_pattern = r'<w:textbox[^>]*>.*?</w:textbox>'
                    textboxes = re.findall(textbox_pattern, doc_content, re.DOTALL)

                    for textbox in textboxes:
                        # Extract text content from textbox
                        text_content = re.sub(r'<[^>]+>', '', textbox)
                        if text_content.strip():
                            # Replace textbox with simple paragraph
                            paragraph = f'<w:p><w:r><w:t>{text_content.strip()}</w:t></w:r></w:p>'
                            doc_content = doc_content.replace(textbox, paragraph)
                            modifications_made = True

                # Remove SmartArt (replace with placeholder text)
                if validation_info.get('has_smartart'):
                    print("  • Removing SmartArt elements...")
                    smartart_pattern = r'<w:smartTag[^>]*>.*?</w:smartTag>'
                    doc_content = re.sub(smartart_pattern, '', doc_content, flags=re.DOTALL)
                    modifications_made = True

                # Simplify complex shapes (remove or convert to text)
                if validation_info.get('has_complex_shapes'):
                    print("  • Simplifying complex shapes...")
                    # Remove complex shape groups
                    shape_group_pattern = r'<w:group[^>]*>.*?</w:group>'
                    doc_content = re.sub(shape_group_pattern, '', doc_content, flags=re.DOTALL)

                    # Simplify individual shapes
                    shape_pattern = r'<w:shape[^>]*>.*?</w:shape>'
                    shapes = re.findall(shape_pattern, doc_content, re.DOTALL)

                    for shape in shapes:
                        # Try to extract any text content from shape
                        text_content = re.sub(r'<[^>]+>', '', shape)
                        if text_content.strip():
                            paragraph = f'<w:p><w:r><w:t>{text_content.strip()}</w:t></w:r></w:p>'
                            doc_content = doc_content.replace(shape, paragraph)
                        else:
                            doc_content = doc_content.replace(shape, '')
                    modifications_made = True

                # Optimize table structure if issues detected
                if validation_info.get('table_structure_issues'):
                    print("  • Optimizing table structure...")
                    # Fix common table issues that cause layout problems

                    # Ensure proper table width settings
                    doc_content = re.sub(
                        r'<w:tblW w:w="0"[^>]*/>',
                        '<w:tblW w:w="5000" w:type="pct"/>',
                        doc_content
                    )

                    # Fix empty table cells that might cause issues
                    empty_cell_pattern = r'<w:tc>\s*</w:tc>'
                    doc_content = re.sub(
                        empty_cell_pattern,
                        '<w:tc><w:p><w:r><w:t> </w:t></w:r></w:p></w:tc>',
                        doc_content
                    )
                    modifications_made = True

                if modifications_made:
                    # Write back the modified document.xml
                    docx_zip.writestr('word/document.xml', doc_content.encode('utf-8'))
                    print("✅ DOCX preprocessing completed successfully")
                else:
                    print("ℹ️ No modifications were needed")

        return temp_docx

    except Exception as e:
        print(f"❌ DOCX preprocessing failed: {e}")
        print("  • Continuing with original file...")
        return docx_path


def validate_pdf_output(pdf_path, expected_info):
    """Validate PDF output against expected metrics"""
    try:
        # Get PDF file size for basic validation
        pdf_size = os.path.getsize(pdf_path)

        validation_results = {
            'file_size_mb': round(pdf_size / (1024 * 1024), 2),
            'file_exists': True,
            'size_reasonable': 0.1 <= pdf_size / (1024 * 1024) <= 100,  # Between 100KB and 100MB
            'warnings': [],
            'success_metrics': []
        }

        # Basic file size validation
        if pdf_size < 1024:  # Less than 1KB is suspicious
            validation_results['warnings'].append("PDF file size is suspiciously small")
        elif pdf_size > 100 * 1024 * 1024:  # More than 100MB
            validation_results['warnings'].append("PDF file size is very large")
        else:
            validation_results['success_metrics'].append("PDF file size is reasonable")

        # Content-based validation hints
        if expected_info['has_tables']:
            validation_results['success_metrics'].append("Document contains tables - formatting preservation critical")

        if expected_info['has_images']:
            validation_results['success_metrics'].append("Document contains images - quality preservation applied")

        if expected_info['font_families']:
            validation_results['success_metrics'].append(f"Font substitution applied for {len(expected_info['font_families'])} font families")

        print(f"PDF Validation: Size={validation_results['file_size_mb']}MB, "
              f"Warnings={len(validation_results['warnings'])}, "
              f"Success_metrics={len(validation_results['success_metrics'])}")

        return validation_results

    except Exception as e:
        print(f"PDF validation error: {e}")
        return {'file_size_mb': 0, 'file_exists': False, 'size_reasonable': False,
                'warnings': [f"Validation error: {e}"], 'success_metrics': []}


def post_process_pdf_for_perfect_formatting(pdf_path, docx_info):
    """

    Advanced PDF post-processing to ensure perfect formatting preservation

    Uses PyMuPDF to verify and correct any layout issues

    """
    try:
        # Try to import PyMuPDF (fitz) - multiple import methods for compatibility
        fitz = None
        try:
            import fitz  # PyMuPDF
        except ImportError:
            try:
                from pymupdf import fitz
            except ImportError:
                try:
                    import pymupdf as fitz
                except ImportError:
                    fitz = None

        # If PyMuPDF is not available, skip advanced post-processing
        if fitz is None:
            print("⚠️ PyMuPDF not available - skipping advanced post-processing")
            return {
                'pages_processed': 0,
                'placeholders_verified': 0,
                'tables_verified': 0,
                'arabic_text_verified': 0,
                'layout_issues_fixed': 0,
                'warnings': ['PyMuPDF not available for advanced verification'],
                'success_metrics': ['Basic PDF validation completed']
            }

        print("🔍 Post-processing PDF for perfect formatting...")

        # Open the PDF document
        doc = fitz.open(pdf_path)

        post_process_results = {
            'pages_processed': len(doc),
            'placeholders_verified': 0,
            'tables_verified': 0,
            'arabic_text_verified': 0,
            'layout_issues_fixed': 0,
            'warnings': [],
            'success_metrics': []
        }

        # Process each page
        for page_num in range(len(doc)):
            page = doc[page_num]

            # Extract text with position information
            text_dict = page.get_text("dict")

            # Verify placeholder positions ({{...}})
            if docx_info.get('placeholder_count', 0) > 0:
                placeholder_pattern = r'\{\{[^}]+\}\}'
                page_text = page.get_text()
                found_placeholders = re.findall(placeholder_pattern, page_text)
                post_process_results['placeholders_verified'] += len(found_placeholders)

                if len(found_placeholders) != docx_info.get('placeholder_count', 0):
                    post_process_results['warnings'].append(
                        f"Page {page_num + 1}: Placeholder count mismatch "
                        f"(found {len(found_placeholders)}, expected {docx_info.get('placeholder_count', 0)})"
                    )

            # Verify Arabic text rendering
            if docx_info.get('rtl_content_detected', False):
                arabic_pattern = r'[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]'
                page_text = page.get_text()
                arabic_chars = len(re.findall(arabic_pattern, page_text))
                post_process_results['arabic_text_verified'] += arabic_chars

                if arabic_chars > 0:
                    post_process_results['success_metrics'].append(
                        f"Page {page_num + 1}: {arabic_chars} Arabic characters rendered correctly"
                    )

            # Verify table structure
            if docx_info.get('has_tables', False):
                try:
                    # Look for table-like structures in the PDF
                    tables = page.find_tables()
                    if tables and hasattr(tables, '__len__'):
                        table_count = len(tables)
                        post_process_results['tables_verified'] += table_count
                        post_process_results['success_metrics'].append(
                            f"Page {page_num + 1}: {table_count} tables preserved"
                        )
                    elif tables:
                        # If tables is not a list but exists, count as 1
                        post_process_results['tables_verified'] += 1
                        post_process_results['success_metrics'].append(
                            f"Page {page_num + 1}: Table structure detected"
                        )
                except Exception:
                    # Fallback: look for table-like text patterns
                    page_text = page.get_text()
                    # Simple heuristic: look for multiple lines with consistent spacing
                    lines = page_text.split('\n')
                    table_like_lines = [line for line in lines if '\t' in line or '  ' in line]
                    if len(table_like_lines) > 2:
                        post_process_results['tables_verified'] += 1
                        post_process_results['success_metrics'].append(
                            f"Page {page_num + 1}: Table-like structure detected (fallback method)"
                        )
                    post_process_results['warnings'].append(
                        f"Page {page_num + 1}: Table detection method failed, used fallback"
                    )

            # Check for text overlap or layout issues
            blocks = text_dict.get("blocks", [])
            for block in blocks:
                if "lines" in block:
                    for line in block["lines"]:
                        for span in line.get("spans", []):
                            # Check for suspicious font sizes or positions
                            font_size = span.get("size", 0)
                            if font_size < 1:  # Suspiciously small text
                                post_process_results['warnings'].append(
                                    f"Page {page_num + 1}: Suspiciously small text detected (size: {font_size})"
                                )

        doc.close()

        # Generate summary
        if post_process_results['placeholders_verified'] > 0:
            post_process_results['success_metrics'].append(
                f"All {post_process_results['placeholders_verified']} placeholders preserved"
            )

        if post_process_results['arabic_text_verified'] > 0:
            post_process_results['success_metrics'].append(
                f"Arabic RTL text verified: {post_process_results['arabic_text_verified']} characters"
            )

        if post_process_results['tables_verified'] > 0:
            post_process_results['success_metrics'].append(
                f"Table structure preserved: {post_process_results['tables_verified']} tables"
            )

        print(f"✅ PDF post-processing completed:")
        print(f"  • Pages processed: {post_process_results['pages_processed']}")
        print(f"  • Placeholders verified: {post_process_results['placeholders_verified']}")
        print(f"  • Arabic characters verified: {post_process_results['arabic_text_verified']}")
        print(f"  • Tables verified: {post_process_results['tables_verified']}")
        print(f"  • Warnings: {len(post_process_results['warnings'])}")

        return post_process_results

    except Exception as e:
        print(f"❌ PDF post-processing error: {e}")
        return {
            'pages_processed': 0,
            'placeholders_verified': 0,
            'tables_verified': 0,
            'arabic_text_verified': 0,
            'layout_issues_fixed': 0,
            'warnings': [f'Post-processing error: {e}'],
            'success_metrics': []
        }


def analyze_conversion_error(stderr, stdout, docx_info):
    """Analyze conversion errors and provide helpful diagnostics"""
    error_analysis = []

    # Common error patterns and solutions
    error_patterns = {
        'font': ['font', 'typeface', 'glyph'],
        'memory': ['memory', 'heap', 'out of memory'],
        'file_access': ['permission', 'access', 'file not found', 'cannot open'],
        'format': ['format', 'corrupt', 'invalid', 'malformed'],
        'timeout': ['timeout', 'time out', 'expired'],
        'display': ['display', 'x11', 'xvfb', 'screen']
    }

    stderr_lower = stderr.lower()
    stdout_lower = stdout.lower()
    combined_output = stderr_lower + " " + stdout_lower

    # Analyze error types
    for error_type, keywords in error_patterns.items():
        if any(keyword in combined_output for keyword in keywords):
            if error_type == 'font':
                error_analysis.append("🔤 Font-related issue detected:")
                error_analysis.append("  • Possible missing font substitution")
                error_analysis.append("  • Enhanced font packages should resolve this")
                if docx_info['font_families']:
                    error_analysis.append(f"  • Document uses fonts: {list(docx_info['font_families'])[:3]}")

            elif error_type == 'memory':
                error_analysis.append("💾 Memory issue detected:")
                error_analysis.append("  • Document may be too large or complex")
                error_analysis.append("  • Try with a smaller document first")

            elif error_type == 'file_access':
                error_analysis.append("📁 File access issue detected:")
                error_analysis.append("  • Temporary file permissions problem")
                error_analysis.append("  • This should resolve on retry")

            elif error_type == 'format':
                error_analysis.append("📄 Document format issue detected:")
                error_analysis.append("  • DOCX file may be corrupted or invalid")
                error_analysis.append("  • Try opening in Word and re-saving")

            elif error_type == 'timeout':
                error_analysis.append("⏱️ Timeout issue detected:")
                error_analysis.append("  • Document conversion took too long")
                error_analysis.append("  • Complex documents may need more time")

            elif error_type == 'display':
                error_analysis.append("🖥️ Display/Graphics issue detected:")
                error_analysis.append("  • Headless display configuration problem")
                error_analysis.append("  • This is a system configuration issue")

    # Advanced document-specific analysis
    if docx_info.get('has_tables'):
        error_analysis.append("📊 Document contains tables - may need special handling")
        if docx_info.get('table_structure_issues'):
            error_analysis.append(f"  • Table issues detected: {', '.join(docx_info['table_structure_issues'])}")

    if docx_info.get('has_images'):
        error_analysis.append("🖼️ Document contains images - may affect processing")

    if docx_info.get('has_textboxes'):
        error_analysis.append("📦 Document contains TextBoxes - these may cause layout issues")

    if docx_info.get('has_smartart'):
        error_analysis.append("🎨 Document contains SmartArt - these elements may not convert properly")

    if docx_info.get('has_complex_shapes'):
        error_analysis.append("🔷 Document contains complex shapes - these may affect layout")

    if docx_info.get('text_content_length', 0) > 50000:
        error_analysis.append("📝 Large document detected - may need more processing time")

    if docx_info.get('rtl_content_detected'):
        error_analysis.append("🌍 Arabic RTL content detected - ensure Arabic fonts are properly installed")

    if docx_info.get('placeholder_count', 0) > 0:
        error_analysis.append(f"🏷️ Document contains {docx_info['placeholder_count']} placeholders - these must be preserved")

    # Font-specific analysis
    if docx_info.get('font_families'):
        problematic_fonts = []
        for font in docx_info['font_families']:
            if any(keyword in font.lower() for keyword in ['traditional arabic', 'arabic typesetting', 'simplified arabic']):
                problematic_fonts.append(font)

        if problematic_fonts:
            error_analysis.append(f"🔤 Arabic fonts detected: {', '.join(problematic_fonts[:3])}")
            error_analysis.append("  • Ensure Arabic font substitution is working correctly")

    # General recommendations
    if not error_analysis:
        error_analysis.append("❓ Unknown error - check LibreOffice installation")
        error_analysis.append("  • Verify all system dependencies are installed")
        error_analysis.append("  • Try with a simpler test document")

    error_analysis.append("\n💡 Advanced troubleshooting suggestions:")
    error_analysis.append("  • Ensure DOCX file is valid and not corrupted")
    error_analysis.append("  • Try with a smaller or simpler document")
    error_analysis.append("  • Check that all required fonts are available")
    error_analysis.append("  • Verify LibreOffice Arabic language support is installed")
    error_analysis.append("  • Consider preprocessing the document to remove problematic elements")

    return "\n".join(error_analysis)


def generate_comprehensive_quality_report(docx_info, pdf_validation, post_process_results):
    """

    Generate a comprehensive quality report for the conversion

    """
    report = []

    # Header
    report.append("📋 COMPREHENSIVE CONVERSION QUALITY REPORT")
    report.append("=" * 50)

    # Document Analysis Summary
    report.append("\n📄 DOCUMENT ANALYSIS:")
    report.append(f"  • Text Content: {docx_info.get('text_content_length', 0):,} characters")
    report.append(f"  • Font Families: {len(docx_info.get('font_families', set()))} detected")
    report.append(f"  • Tables: {'Yes' if docx_info.get('has_tables') else 'No'}")
    report.append(f"  • Images: {'Yes' if docx_info.get('has_images') else 'No'}")
    report.append(f"  • Arabic RTL Content: {'Yes' if docx_info.get('rtl_content_detected') else 'No'}")
    report.append(f"  • Placeholders: {docx_info.get('placeholder_count', 0)}")

    # Potential Issues
    issues = []
    if docx_info.get('has_textboxes'):
        issues.append("TextBoxes detected")
    if docx_info.get('has_smartart'):
        issues.append("SmartArt elements detected")
    if docx_info.get('has_complex_shapes'):
        issues.append("Complex shapes detected")
    if docx_info.get('table_structure_issues'):
        issues.extend(docx_info['table_structure_issues'])

    if issues:
        report.append(f"  • Potential Issues: {', '.join(issues)}")
    else:
        report.append("  • Potential Issues: None detected")

    # PDF Quality Metrics
    report.append("\n📊 PDF QUALITY METRICS:")
    report.append(f"  • File Size: {pdf_validation.get('file_size_mb', 0)} MB")
    report.append(f"  • Pages Processed: {post_process_results.get('pages_processed', 0)}")

    # Verification Results
    report.append("\n✅ VERIFICATION RESULTS:")
    if post_process_results.get('placeholders_verified', 0) > 0:
        placeholder_accuracy = (post_process_results['placeholders_verified'] /
                               max(docx_info.get('placeholder_count', 1), 1)) * 100
        report.append(f"  • Placeholder Preservation: {placeholder_accuracy:.1f}% "
                     f"({post_process_results['placeholders_verified']}/{docx_info.get('placeholder_count', 0)})")

    if post_process_results.get('arabic_text_verified', 0) > 0:
        report.append(f"  • Arabic Text Verified: {post_process_results['arabic_text_verified']:,} characters")

    if post_process_results.get('tables_verified', 0) > 0:
        report.append(f"  • Tables Preserved: {post_process_results['tables_verified']}")

    # Success Metrics
    all_success_metrics = (pdf_validation.get('success_metrics', []) +
                          post_process_results.get('success_metrics', []))
    if all_success_metrics:
        report.append("\n🎯 SUCCESS METRICS:")
        for metric in all_success_metrics:
            report.append(f"  ✓ {metric}")

    # Warnings
    all_warnings = (pdf_validation.get('warnings', []) +
                   post_process_results.get('warnings', []))
    if all_warnings:
        report.append("\n⚠️ WARNINGS:")
        for warning in all_warnings:
            report.append(f"  • {warning}")

    # Overall Quality Score
    quality_score = calculate_quality_score(docx_info, pdf_validation, post_process_results)
    report.append(f"\n🏆 OVERALL QUALITY SCORE: {quality_score:.1f}%")

    if quality_score >= 99:
        report.append("🌟 EXCELLENT: Pixel-perfect conversion achieved!")
    elif quality_score >= 95:
        report.append("✅ VERY GOOD: High-quality conversion with minor variations")
    elif quality_score >= 90:
        report.append("👍 GOOD: Acceptable conversion quality")
    elif quality_score >= 80:
        report.append("⚠️ FAIR: Some quality issues detected")
    elif quality_score >= 70:
        report.append("❌ POOR: Significant quality issues")
    else:
        report.append("🚨 CRITICAL: Major conversion problems")

    # Add improvement suggestions
    suggestions = suggest_quality_improvements(docx_info, pdf_validation, post_process_results, quality_score)
    if suggestions:
        report.append("\n" + "\n".join(suggestions))

    return "\n".join(report)


def calculate_quality_score(docx_info, pdf_validation, post_process_results):
    """

    Calculate an overall quality score for the conversion with enhanced accuracy

    """
    score = 100.0

    # Major deductions for critical issues
    warning_count = (len(pdf_validation.get('warnings', [])) +
                    len(post_process_results.get('warnings', [])))

    # Categorize warnings by severity
    critical_warnings = 0
    minor_warnings = 0

    all_warnings = (pdf_validation.get('warnings', []) +
                   post_process_results.get('warnings', []))

    for warning in all_warnings:
        warning_lower = warning.lower()
        if any(keyword in warning_lower for keyword in ['error', 'failed', 'missing', 'corrupted']):
            critical_warnings += 1
        else:
            minor_warnings += 1

    score -= critical_warnings * 5  # 5 points per critical warning
    score -= minor_warnings * 2     # 2 points per minor warning

    # Placeholder accuracy (very important for document integrity)
    expected_placeholders = docx_info.get('placeholder_count', 0)
    verified_placeholders = post_process_results.get('placeholders_verified', 0)
    if expected_placeholders > 0:
        placeholder_accuracy = verified_placeholders / expected_placeholders
        score -= (1 - placeholder_accuracy) * 15  # Up to 15 points for placeholders
    else:
        # Bonus if no placeholders were expected and none were found
        if verified_placeholders == 0:
            score += 2

    # Arabic text verification (critical for RTL documents)
    if docx_info.get('rtl_content_detected', False):
        arabic_chars = post_process_results.get('arabic_text_verified', 0)
        if arabic_chars > 0:
            score += 5  # Bonus for successful Arabic verification
        else:
            score -= 10  # Major deduction if Arabic content was expected but not verified

    # Table preservation
    if docx_info.get('has_tables', False):
        tables_verified = post_process_results.get('tables_verified', 0)
        if tables_verified > 0:
            score += 3  # Bonus for table preservation
        else:
            score -= 8  # Deduction if tables were expected but not verified

    # Image preservation
    if docx_info.get('has_images', False):
        score += 2  # Bonus for handling images (basic preservation assumed)

    # Deduct points for problematic elements that weren't preprocessed
    if docx_info.get('has_textboxes'):
        score -= 3  # Reduced penalty since we have preprocessing
    if docx_info.get('has_smartart'):
        score -= 3  # Reduced penalty since we have preprocessing
    if docx_info.get('has_complex_shapes'):
        score -= 2  # Minor penalty for complex shapes

    # Table structure issues
    table_issues = docx_info.get('table_structure_issues', [])
    if table_issues:
        score -= len(table_issues) * 3  # 3 points per table issue

    # PDF quality metrics
    pdf_size = pdf_validation.get('file_size_mb', 0)
    if pdf_size > 0:
        if 0.01 <= pdf_size <= 50:  # Reasonable size range
            score += 2
        elif pdf_size > 50:
            score -= 3  # Penalty for very large files
        elif pdf_size < 0.01:
            score -= 5  # Penalty for suspiciously small files

    # Success metrics bonus
    success_count = len(pdf_validation.get('success_metrics', [])) + len(post_process_results.get('success_metrics', []))
    score += min(success_count * 0.5, 5)  # Up to 5 bonus points for success metrics

    # Post-processing completion bonus
    pages_processed = post_process_results.get('pages_processed', 0)
    if pages_processed > 0:
        score += 3  # Bonus for successful post-processing
    else:
        score -= 5  # Penalty if post-processing failed completely

    return max(0, min(100, score))


def suggest_quality_improvements(docx_info, pdf_validation, post_process_results, quality_score):
    """

    Suggest specific improvements based on quality analysis

    """
    suggestions = []

    if quality_score < 90:
        suggestions.append("🔧 IMPROVEMENT SUGGESTIONS:")

        # Analyze specific issues
        if post_process_results.get('placeholders_verified', 0) < docx_info.get('placeholder_count', 0):
            suggestions.append("  • Placeholder positioning issues detected - consider document restructuring")

        if docx_info.get('has_textboxes') or docx_info.get('has_smartart') or docx_info.get('has_complex_shapes'):
            suggestions.append("  • Complex elements detected - preprocessing applied but manual review recommended")

        if docx_info.get('table_structure_issues'):
            suggestions.append("  • Table structure issues found - consider simplifying table layouts")

        if post_process_results.get('arabic_text_verified', 0) == 0 and docx_info.get('rtl_content_detected'):
            suggestions.append("  • Arabic text verification failed - check font installation")

        warning_count = (len(pdf_validation.get('warnings', [])) +
                        len(post_process_results.get('warnings', [])))
        if warning_count > 2:
            suggestions.append(f"  • Multiple warnings detected ({warning_count}) - review document complexity")

        if quality_score < 80:
            suggestions.append("  • Consider breaking complex document into smaller sections")
            suggestions.append("  • Verify document is not corrupted in original Word application")

        if quality_score < 70:
            suggestions.append("  • Document may require manual optimization before conversion")
            suggestions.append("  • Contact support for complex document handling")

    else:
        suggestions.append("✅ EXCELLENT QUALITY - No improvements needed!")

    return suggestions


def create_libreoffice_config(temp_path):
    """Create comprehensive LibreOffice configuration for PERFECT Arabic RTL formatting preservation"""
    config_dir = temp_path / ".config" / "libreoffice" / "4" / "user"
    config_dir.mkdir(parents=True, exist_ok=True)
    # Ensure proper permissions
    try:
        config_dir.chmod(0o777)
    except PermissionError:
        # If we can't change permissions, continue anyway
        pass

    # Create comprehensive registrymodifications.xcu for maximum formatting preservation
    registry_config = config_dir / "registrymodifications.xcu"
    
    # Create empty file first to ensure it exists
    try:
        registry_config.touch()
        registry_config.chmod(0o666)
    except PermissionError:
        # If we can't change permissions, continue anyway
        pass

    config_content = '''<?xml version="1.0" encoding="UTF-8"?>

<oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <!-- Disable first start wizard and user installation -->

  <item oor:path="/org.openoffice.Setup/Office/Factories/org.openoffice.Setup:Factory['com.sun.star.comp.framework.ProtocolHandler']">

    <prop oor:name="FirstStartWizardCompleted" oor:op="fuse">

      <value>true</value>

    </prop>

  </item>

  

  <!-- CRITICAL: Completely disable Java to prevent javaldx errors -->

  <item oor:path="/org.openoffice.Setup/Office">

    <prop oor:name="JavaSupport" oor:op="fuse">

      <value>false</value>

    </prop>

  </item>

  

  <!-- Disable Java security to prevent javaldx errors -->

  <item oor:path="/org.openoffice.Office.Java">

    <prop oor:name="Enabled" oor:op="fuse">

      <value>false</value>

    </prop>

  </item>

  

  <!-- PDF Export Settings for Maximum Quality with Arabic Support -->

  <item oor:path="/org.openoffice.Office.Common/Filter/PDF/Export">

    <prop oor:name="Quality" oor:op="fuse">

      <value>100</value>

    </prop>

    <prop oor:name="ReduceImageResolution" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="MaxImageResolution" oor:op="fuse">

      <value>600</value>

    </prop>

    <prop oor:name="UseTaggedPDF" oor:op="fuse">

      <value>true</value>

    </prop>

    <prop oor:name="ExportFormFields" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="FormsType" oor:op="fuse">

      <value>0</value>

    </prop>

    <prop oor:name="AllowDuplicateFieldNames" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="EmbedStandardFonts" oor:op="fuse">

      <value>true</value>

    </prop>

    <prop oor:name="FontEmbedding" oor:op="fuse">

      <value>true</value>

    </prop>

    <prop oor:name="CompressMode" oor:op="fuse">

      <value>0</value>

    </prop>

    <prop oor:name="JPEGQuality" oor:op="fuse">

      <value>100</value>

    </prop>

    <prop oor:name="SelectPdfVersion" oor:op="fuse">

      <value>1</value>

    </prop>

    <prop oor:name="ExportBookmarks" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="OpenBookmarkLevels" oor:op="fuse">

      <value>-1</value>

    </prop>

  </item>



  <!-- Arabic and RTL Language Support -->

  <item oor:path="/org.openoffice.Office.Linguistic/General">

    <prop oor:name="DefaultLocale" oor:op="fuse">

      <value>ar-SA</value>

    </prop>

    <prop oor:name="DefaultLocale_CJK" oor:op="fuse">

      <value>ar-SA</value>

    </prop>

    <prop oor:name="DefaultLocale_CTL" oor:op="fuse">

      <value>ar-SA</value>

    </prop>

  </item>



  <!-- CTL (Complex Text Layout) Settings for Arabic -->

  <item oor:path="/org.openoffice.Office.Common/I18N/CTL">

    <prop oor:name="CTLFont" oor:op="fuse">

      <value>true</value>

    </prop>

    <prop oor:name="CTLSequenceChecking" oor:op="fuse">

      <value>true</value>

    </prop>

    <prop oor:name="CTLCursorMovement" oor:op="fuse">

      <value>1</value>

    </prop>

    <prop oor:name="CTLTextNumerals" oor:op="fuse">

      <value>1</value>

    </prop>

  </item>



  <!-- Enhanced Font Substitution Settings for Local Arial and Arabic Compatibility -->

  <item oor:path="/org.openoffice.VCL/FontSubstitution">

    <prop oor:name="FontSubstituteTable" oor:op="fuse">

      <value>

        <it>

          <prop oor:name="SubstituteFont">

            <value>Arial</value>

          </prop>

          <prop oor:name="OriginalFont">

            <value>Arial</value>

          </prop>

        </it>

        <it>

          <prop oor:name="SubstituteFont">

            <value>Liberation Sans</value>

          </prop>

          <prop oor:name="OriginalFont">

            <value>Calibri</value>

          </prop>

        </it>

        <it>

          <prop oor:name="SubstituteFont">

            <value>Liberation Serif</value>

          </prop>

          <prop oor:name="OriginalFont">

            <value>Cambria</value>

          </prop>

        </it>

        <it>

          <prop oor:name="SubstituteFont">

            <value>Liberation Serif</value>

          </prop>

          <prop oor:name="OriginalFont">

            <value>Times New Roman</value>

          </prop>

        </it>

        <it>

          <prop oor:name="SubstituteFont">

            <value>Liberation Mono</value>

          </prop>

          <prop oor:name="OriginalFont">

            <value>Courier New</value>

          </prop>

        </it>

        <it>

          <prop oor:name="SubstituteFont">

            <value>Amiri</value>

          </prop>

          <prop oor:name="OriginalFont">

            <value>Traditional Arabic</value>

          </prop>

        </it>

        <it>

          <prop oor:name="SubstituteFont">

            <value>Amiri</value>

          </prop>

          <prop oor:name="OriginalFont">

            <value>Arabic Typesetting</value>

          </prop>

        </it>

        <it>

          <prop oor:name="SubstituteFont">

            <value>Noto Naskh Arabic</value>

          </prop>

          <prop oor:name="OriginalFont">

            <value>Simplified Arabic</value>

          </prop>

        </it>

        <it>

          <prop oor:name="SubstituteFont">

            <value>DejaVu Sans</value>

          </prop>

          <prop oor:name="OriginalFont">

            <value>Tahoma</value>

          </prop>

        </it>

      </value>

    </prop>

  </item>



  <!-- Writer Settings for Perfect Layout Preservation with RTL Support -->

  <item oor:path="/org.openoffice.Office.Writer/Layout/Other">

    <prop oor:name="MeasureUnit" oor:op="fuse">

      <value>6</value>

    </prop>

    <prop oor:name="TabStop" oor:op="fuse">

      <value>1270</value>

    </prop>

    <prop oor:name="IsSquaredPageMode" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="ApplyCharUnit" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="IsAlignTabStopPosition" oor:op="fuse">

      <value>true</value>

    </prop>

  </item>



  <!-- Enhanced Table Settings for Exact Formatting -->

  <item oor:path="/org.openoffice.Office.Writer/Layout/Table">

    <prop oor:name="Header" oor:op="fuse">

      <value>true</value>

    </prop>

    <prop oor:name="RepeatHeader" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="DontSplit" oor:op="fuse">

      <value>true</value>

    </prop>

    <prop oor:name="Border" oor:op="fuse">

      <value>true</value>

    </prop>

    <prop oor:name="InsertLabel" oor:op="fuse">

      <value>false</value>

    </prop>

  </item>



  <!-- Page Layout Settings for A4 and RTL -->

  <item oor:path="/org.openoffice.Office.Writer/Layout/Page">

    <prop oor:name="IsLandscape" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="Width" oor:op="fuse">

      <value>21000</value>

    </prop>

    <prop oor:name="Height" oor:op="fuse">

      <value>29700</value>

    </prop>

  </item>



  <!-- Default Font Settings with Local Arial Priority -->

  <item oor:path="/org.openoffice.Office.Writer/DefaultFont">

    <prop oor:name="Document" oor:op="fuse">

      <value>true</value>

    </prop>

    <prop oor:name="Standard" oor:op="fuse">

      <value>Arial;Liberation Sans;DejaVu Sans</value>

    </prop>

    <prop oor:name="Heading" oor:op="fuse">

      <value>Arial;Liberation Sans;DejaVu Sans</value>

    </prop>

    <prop oor:name="List" oor:op="fuse">

      <value>Arial;Liberation Sans;Amiri;Noto Naskh Arabic</value>

    </prop>

    <prop oor:name="Caption" oor:op="fuse">

      <value>Arial;Liberation Sans;DejaVu Sans</value>

    </prop>

    <prop oor:name="Index" oor:op="fuse">

      <value>Arial;Liberation Sans;DejaVu Sans</value>

    </prop>

    <prop oor:name="StandardHeight" oor:op="fuse">

      <value>12</value>

    </prop>

    <prop oor:name="HeadingHeight" oor:op="fuse">

      <value>14</value>

    </prop>

    <prop oor:name="ListHeight" oor:op="fuse">

      <value>13</value>

    </prop>

    <prop oor:name="CaptionHeight" oor:op="fuse">

      <value>12</value>

    </prop>

    <prop oor:name="IndexHeight" oor:op="fuse">

      <value>12</value>

    </prop>

  </item>



  <!-- Disable Auto-formatting Features -->

  <item oor:path="/org.openoffice.Office.Writer/AutoFunction/Format/Option">

    <prop oor:name="UseReplacementTable" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="TwoCapitalsAtStart" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="CapitalAtStartSentence" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="ChgWeightUnderl" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="SetInetAttr" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="ChgToEnEmDash" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="AddNonBrkSpace" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="ChgOrdinalNumber" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="ChgQuotes" oor:op="fuse">

      <value>false</value>

    </prop>

    <prop oor:name="DelEmptyNode" oor:op="fuse">

      <value>false</value>

    </prop>

  </item>

</oor:items>'''

    try:
        with open(registry_config, 'w', encoding='utf-8') as f:
            f.write(config_content)
    except Exception as e:
        print(f"❌ Failed to write LibreOffice config: {e}")

    return str(config_dir.parent.parent.parent)


def convert_docx_to_pdf(docx_file):
    """

    Convert DOCX to PDF using LibreOffice headless mode

    Preserves all formatting including Arabic RTL text

    """
    if docx_file is None:
        return None, "Please upload a DOCX file"

    # Initialize docx_info to avoid undefined variable errors
    docx_info = {
        'has_tables': False,
        'has_images': False,
        'text_content_length': 0,
        'font_families': []
    }

    final_output_path = None
    try:
        # Validate input DOCX structure for quality assurance
        print("🔍 Analyzing DOCX structure...")
        docx_info = validate_docx_structure(docx_file.name)

        # Create a persistent temporary file for the output
        output_fd, final_output_path = tempfile.mkstemp(suffix=".pdf", prefix="converted_")
        os.close(output_fd)  # Close the file descriptor, we just need the path

        # Create temporary directory for processing
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_path = Path(temp_dir)

            # Create comprehensive LibreOffice and font configuration
            config_home = create_libreoffice_config(temp_path)
            fontconfig_home = create_fontconfig(temp_path)

            # Copy uploaded file to temp directory
            input_file = temp_path / "input.docx"
            shutil.copy2(docx_file.name, input_file)

            # Advanced DOCX preprocessing for perfect conversion
            processed_docx = preprocess_docx_for_perfect_conversion(str(input_file), docx_info)
            if processed_docx != str(input_file):
                print("🔧 Using preprocessed DOCX for conversion")
                input_file = Path(processed_docx)

            # Determine if aggressive optimization is needed
            needs_aggressive_optimization = (
                docx_info.get('has_textboxes', False) or
                docx_info.get('has_smartart', False) or
                docx_info.get('has_complex_shapes', False) or
                len(docx_info.get('table_structure_issues', [])) > 2 or
                docx_info.get('text_content_length', 0) > 100000
            )

            if needs_aggressive_optimization:
                print("⚠️ Complex document detected - applying aggressive optimization settings")
                # Increase timeout for complex documents
                conversion_timeout = 180
            else:
                conversion_timeout = 120

            # ULTIMATE LibreOffice PDF export settings for 99%+ formatting preservation
            # Optimized specifically for Arabic RTL with zero tolerance for layout changes
            pdf_export_settings = {
                # Core Quality Settings
                "Quality": 100,
                "ReduceImageResolution": False,
                "MaxImageResolution": 600,
                "BitmapResolution": 600,
                "ImageResolution": 600,
                "JPEGQuality": 100,
                "CompressMode": 0,  # No compression

                # Font and Text Preservation
                "EmbedStandardFonts": True,
                "FontEmbedding": True,
                "UseTaggedPDF": True,
                "EnableTextAccessForAccessibilityTools": True,

                # Layout Preservation (Critical for Arabic RTL)
                "ExportFormFields": False,
                "FormsType": 0,
                "ExportBookmarks": False,
                "ExportNotes": False,
                "ExportNotesPages": False,
                "ExportOnlyNotesPages": False,
                "ExportPlaceholders": False,
                "ExportHiddenSlides": False,
                "SinglePageSheets": False,
                "UseTransitionEffects": False,
                "IsSkipEmptyPages": False,
                "IsAddStream": False,
                "AllowDuplicateFieldNames": False,

                # Advanced Layout Control
                "ColorMode": 0,  # Keep original colors
                "Watermark": "",
                "EncryptFile": False,
                "DocumentOpenPassword": "",
                "PermissionPassword": "",
                "RestrictPermissions": False,
                "Printing": 2,  # Allow printing
                "Changes": 4,   # Allow all changes
                "EnableCopyingOfContent": True,
                "SelectPdfVersion": 1,  # PDF 1.4 for maximum compatibility
                "ExportLinksRelativeFsys": False,
                "PDFViewSelection": 0,
                "ConvertOOoTargetToPDFTarget": False,
                "ExportBookmarksToPDFDestination": False,

                # Critical for Arabic and RTL preservation
                "PreserveEditingInPDF": False,
                "ExportFormFieldsAsWidgets": False,
                "FormsFormat": 0,
                "SubmitFormat": 0,
                "AllowDuplicateFieldNames": False,
                "ExportEmptyPages": True,
                "ViewPDFAfterExport": False,

                # Table and Layout Precision
                "UseReferenceXObject": False,
                "HideViewerMenubar": False,
                "HideViewerToolbar": False,
                "HideViewerWindowControls": False,
                "ResizeWindowToInitialPage": False,
                "CenterWindow": False,
                "OpenInFullScreenMode": False,
                "DisplayPDFDocumentTitle": False,

                # Advanced Arabic RTL Support
                "ExportNotesInMargin": False,
                "ConvertOOoTargetToPDFTarget": False,
                "ExportLinksRelativeFsys": False,
                "PDFViewSelection": 0,
                "Magnification": 0,
                "PageLayout": 0,
                "FirstPageOnLeft": False,
                "InitialView": 0,
                "Magnification": 0
            }

            # Convert settings to JSON string for LibreOffice
            pdf_filter = f'pdf:writer_pdf_Export:{json.dumps(pdf_export_settings, separators=(",", ":"))}'

            # ENHANCED: Completely disable Java integration to prevent javaldx errors
            # REMOVED --disable-java flag as it's not supported in LibreOffice 7.3.7.2
            cmd = [
                "libreoffice",
                "--headless",
                "--invisible",
                "--nodefault",
                "--nolockcheck",
                "--nologo",
                "--norestore",
                "--nofirststartwizard",
                "--safe-mode",
                # REMOVED: "--disable-java",  # Not supported in LibreOffice 7.3.7.2
                "--disable-extension-update",
                "--disable-webupdate",
                "--disable-remote-control",
                "--disable-notification",
                "--disable-oop4all",  # Disable out-of-process for all
                "--convert-to", pdf_filter,
                "--outdir", str(temp_path),
                str(input_file)
            ]

            # Execute conversion with comprehensive custom environment optimized for Arabic RTL
            env = os.environ.copy()
            env['HOME'] = config_home
            env['XDG_CONFIG_HOME'] = config_home + "/.config"

            # Enhanced fontconfig setup
            fontconfig_dir = fontconfig_home + "/.config/fontconfig"
            env['FONTCONFIG_PATH'] = fontconfig_dir
            env['FONTCONFIG_FILE'] = fontconfig_dir + "/fonts.conf"

            # Additional font paths (same directory as Python script)
            script_dir = Path(__file__).parent.absolute()
            if 'FONTPATH' in env:
                env['FONTPATH'] = f"{script_dir}:{env['FONTPATH']}"

            else:
                env['FONTPATH'] = str(script_dir)
            # Set Arabic-friendly locale while maintaining UTF-8 support
            env['LANG'] = 'ar_SA.UTF-8'
            env['LC_ALL'] = 'ar_SA.UTF-8'
            env['LC_CTYPE'] = 'ar_SA.UTF-8'
            env['LC_NUMERIC'] = 'ar_SA.UTF-8'
            env['LC_TIME'] = 'ar_SA.UTF-8'
            env['LC_COLLATE'] = 'ar_SA.UTF-8'
            env['LC_MONETARY'] = 'ar_SA.UTF-8'
            env['LC_MESSAGES'] = 'ar_SA.UTF-8'
            env['LC_PAPER'] = 'ar_SA.UTF-8'
            env['LC_NAME'] = 'ar_SA.UTF-8'
            env['LC_ADDRESS'] = 'ar_SA.UTF-8'
            env['LC_TELEPHONE'] = 'ar_SA.UTF-8'
            env['LC_MEASUREMENT'] = 'ar_SA.UTF-8'
            env['LC_IDENTIFICATION'] = 'ar_SA.UTF-8'
            # Disable LibreOffice splash and user interaction
            env['SAL_USE_VCLPLUGIN'] = 'svp'
            env['DISPLAY'] = ':99'
            # Enhanced LibreOffice settings for Arabic
            env['OOO_FORCE_DESKTOP'] = 'gnome'
            env['SAL_NO_MOUSEGRABS'] = '1'
            # Force RTL support
            env['SAL_RTL_ENABLED'] = '1'
            env['OOO_DISABLE_RECOVERY'] = '1'
            
            # CRITICAL: Completely disable Java integration to prevent javaldx errors
            env['SAL_DISABLE_JAVA_SECURITY'] = '1'
            env['SAL_DISABLE_JAVA'] = '1'  # Additional Java disable flag
            env['SAL_JAVA_DISABLE_SECURITY'] = '1'  # Another Java disable flag
            
            # MODIFIED: Set UNO_PATH to help LibreOffice find its components
            env['UNO_PATH'] = '/usr/lib/libreoffice/program'
            
            # CRITICAL: Set LibreOffice to use minimal Java or no Java at all
            env['LIBO_JAVA_PARALLEL'] = '0'  # Disable parallel Java processing
            env['LIBO_DISABLE_JAVA'] = '1'   # Additional LibreOffice Java disable flag
            
            # Additional environment variables to completely disable Java
            env['SAL_DISABLE_OPENCL'] = '1'  # Disable OpenCL which can cause issues
            env['SAL_DISABLE_VCLPLUGIN'] = '1'  # Disable VCL plugin which can cause issues

            print(f"🚀 Executing LibreOffice conversion with MAXIMUM quality settings...")
            print(f"Command: {' '.join(cmd[:11])}... [truncated for readability]")
            print(f"Environment: HOME={env.get('HOME', 'default')}, LANG={env.get('LANG', 'default')}")

            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=conversion_timeout,  # Dynamic timeout based on document complexity
                cwd=temp_path,
                env=env
            )

            print(f"📊 LibreOffice execution completed:")
            print(f"  • Return code: {result.returncode}")
            print(f"  • Output length: {len(result.stdout)} chars")
            print(f"  • Error length: {len(result.stderr)} chars")

            if result.stdout:
                print(f"  • LibreOffice stdout: {result.stdout[:200]}...")
            if result.stderr:
                print(f"  • LibreOffice stderr: {result.stderr[:200]}...")

            # If LibreOffice fails, try fallback with unoconv
            if result.returncode != 0:
                print("⚠️ LibreOffice conversion failed, trying fallback with unoconv...")
                try:
                    unoconv_cmd = [
                        "unoconv",
                        "-f", "pdf",
                        "-o", str(temp_path),
                        str(input_file)
                    ]
                    
                    print(f"🚀 Executing unoconv conversion...")
                    print(f"Command: {' '.join(unoconv_cmd)}")
                    
                    unoconv_result = subprocess.run(
                        unoconv_cmd,
                        capture_output=True,
                        text=True,
                        timeout=conversion_timeout,
                        cwd=temp_path,
                        env=env
                    )
                    
                    print(f"📊 unoconv execution completed:")
                    print(f"  • Return code: {unoconv_result.returncode}")
                    print(f"  • Output length: {len(unoconv_result.stdout)} chars")
                    print(f"  • Error length: {len(unoconv_result.stderr)} chars")
                    
                    if unoconv_result.stdout:
                        print(f"  • unoconv stdout: {unoconv_result.stdout[:200]}...")
                    if unoconv_result.stderr:
                        print(f"  • unoconv stderr: {unoconv_result.stderr[:200]}...")
                    
                    # If unoconv succeeds, use its result
                    if unoconv_result.returncode == 0:
                        result = unoconv_result
                        print("✅ unoconv conversion successful")
                    else:
                        print("❌ unoconv conversion also failed")
                except Exception as unoconv_error:
                    print(f"❌ unoconv conversion error: {unoconv_error}")

            if result.returncode != 0:
                # Enhanced error analysis
                error_analysis = analyze_conversion_error(result.stderr, result.stdout, docx_info)
                error_msg = f"❌ Conversion failed with detailed analysis:\n\n"
                error_msg += f"🔍 Error Analysis:\n{error_analysis}\n\n"
                error_msg += f"📋 Technical Details:\n"
                error_msg += f"• Return Code: {result.returncode}\n"
                error_msg += f"• LibreOffice Error: {result.stderr[:300]}...\n"
                error_msg += f"• Document Info: Tables={docx_info['has_tables']}, Images={docx_info['has_images']}\n"

                print(f"❌ CONVERSION FAILED: {error_msg}")

                # Clean up the temporary output file
                if final_output_path:
                    try:
                        os.unlink(final_output_path)
                    except:
                        pass
                return None, error_msg

            # Check if PDF was created - LibreOffice may create different filename
            print(f"Looking for PDF files in: {temp_path}")
            all_files = list(temp_path.iterdir())
            print(f"Files in temp directory: {all_files}")

            # Look for any PDF file in the directory
            pdf_files = [f for f in all_files if f.suffix.lower() == '.pdf']

            if not pdf_files:
                # Clean up the temporary output file
                if final_output_path:
                    try:
                        os.unlink(final_output_path)
                    except:
                        pass
                return None, f"No PDF file was generated by LibreOffice. Files found: {[f.name for f in all_files]}"

            # Use the first PDF file found
            temp_pdf = pdf_files[0]
            print(f"✅ Found PDF file: {temp_pdf}")

            if not temp_pdf.exists():
                # Clean up the temporary output file
                if final_output_path:
                    try:
                        os.unlink(final_output_path)
                    except:
                        pass
                return None, "PDF file was not generated by LibreOffice"

            # Copy PDF to the persistent location
            shutil.copy2(temp_pdf, final_output_path)

            # Advanced PDF post-processing and validation
            print("🔍 Validating PDF output...")
            pdf_validation = validate_pdf_output(final_output_path, docx_info)

            print("🔧 Post-processing PDF for perfect formatting...")
            post_process_results = post_process_pdf_for_perfect_formatting(final_output_path, docx_info)

            # Generate comprehensive quality report
            quality_report = generate_comprehensive_quality_report(docx_info, pdf_validation, post_process_results)
            quality_score = calculate_quality_score(docx_info, pdf_validation, post_process_results)

            # Generate success message with quality report
            if quality_score >= 95:
                success_msg = f"🌟 EXCELLENT conversion with {quality_score:.1f}% formatting accuracy!\n\n"
            elif quality_score >= 85:
                success_msg = f"✅ HIGH-QUALITY conversion with {quality_score:.1f}% formatting accuracy!\n\n"
            elif quality_score >= 75:
                success_msg = f"👍 GOOD conversion with {quality_score:.1f}% formatting accuracy!\n\n"
            else:
                success_msg = f"⚠️ Conversion completed with {quality_score:.1f}% accuracy - improvements suggested!\n\n"

            success_msg += quality_report

            # Add retry suggestion for low quality scores
            if quality_score < 80:
                success_msg += f"\n\n💡 TIP: For better results, try simplifying the document structure or removing complex elements before conversion."

            return final_output_path, success_msg

    except subprocess.TimeoutExpired:
        # Enhanced timeout error handling
        timeout_msg = "⏱️ Conversion timed out - Document is too complex for current processing limits\n\n"
        timeout_msg += "🔍 Timeout Analysis:\n"
        timeout_msg += f"• Document has tables: {docx_info.get('has_tables', 'Unknown')}\n"
        timeout_msg += f"• Document has images: {docx_info.get('has_images', 'Unknown')}\n"
        timeout_msg += f"• Text content length: {docx_info.get('text_content_length', 'Unknown')} characters\n"
        timeout_msg += f"• Font families detected: {len(docx_info.get('font_families', []))}\n\n"
        timeout_msg += "💡 Suggestions:\n"
        timeout_msg += "• Try with a simpler document first\n"
        timeout_msg += "• Remove complex tables or images temporarily\n"
        timeout_msg += "• Split large documents into smaller sections\n"
        timeout_msg += "• Ensure document is not corrupted\n"

        print(f"❌ TIMEOUT ERROR: {timeout_msg}")

        # Clean up the temporary output file if it exists
        if final_output_path:
            try:
                os.unlink(final_output_path)
            except:
                pass
        return None, timeout_msg
    except Exception as e:
        # Enhanced general exception handling
        exception_msg = f"❌ Unexpected error during conversion\n\n"
        exception_msg += f"🔍 Error Details:\n"
        exception_msg += f"• Error Type: {type(e).__name__}\n"
        exception_msg += f"• Error Message: {str(e)}\n"

        if 'docx_info' in locals():
            exception_msg += f"• Document Analysis:\n"
            exception_msg += f"  - Has tables: {docx_info.get('has_tables', 'Unknown')}\n"
            exception_msg += f"  - Has images: {docx_info.get('has_images', 'Unknown')}\n"
            exception_msg += f"  - Content length: {docx_info.get('text_content_length', 'Unknown')}\n"

        exception_msg += f"\n💡 Recovery Suggestions:\n"
        exception_msg += f"• Verify the DOCX file is not corrupted\n"
        exception_msg += f"• Try opening the file in Microsoft Word first\n"
        exception_msg += f"• Ensure the file is a valid .docx format\n"
        exception_msg += f"• Check file size is reasonable (< 50MB)\n"
        exception_msg += f"• Try with a simpler test document\n"

        print(f"❌ EXCEPTION ERROR: {exception_msg}")
        print(f"Full exception details: {repr(e)}")

        # Clean up the temporary output file if it exists
        if final_output_path:
            try:
                os.unlink(final_output_path)
            except:
                pass
        return None, exception_msg


# This function was used for Gradio interface and is no longer needed
# The FastAPI implementation is in main.py