html_renderer.py 191 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266
"""
基于章节IR的HTML/PDF渲染器,实现与示例报告一致的交互与视觉。

新增要点:
1. 内置Chart.js数据验证/修复(ChartValidator+LLM兜底),杜绝非法配置导致的注入或崩溃;
2. 将MathJax/Chart.js/html2canvas/jspdf等依赖内联并带CDN fallback,适配离线或被墙环境;
3. 预置思源宋体子集的Base64字体,用于PDF/HTML一体化导出,避免缺字或额外系统依赖。
"""

from __future__ import annotations

import ast
import copy
import html
import json
import os
import re
import base64
from pathlib import Path
from typing import Any, Dict, List
from loguru import logger

from ReportEngine.ir.schema import ENGINE_AGENT_TITLES
from ReportEngine.utils.chart_validator import (
    ChartValidator,
    ChartRepairer,
    create_chart_validator,
    create_chart_repairer
)
from ReportEngine.utils.chart_repair_api import create_llm_repair_functions


class HTMLRenderer:
    """
    Document IR → HTML 渲染器。

    - 读取 IR metadata/chapters,将结构映射为响应式HTML;
    - 动态构造目录、锚点、Chart.js脚本及互动逻辑;
    - 提供主题变量、编号映射等辅助功能。
    """

    CALLOUT_ALLOWED_TYPES = {
        "paragraph",
        "list",
        "table",
        "blockquote",
        "code",
        "math",
        "figure",
        "kpiGrid",
        "swotTable",
        "engineQuote",
    }
    INLINE_ARTIFACT_KEYS = {
        "props",
        "widgetId",
        "widgetType",
        "data",
        "dataRef",
        "datasets",
        "labels",
        "config",
        "options",
    }
    TABLE_COMPLEX_CHARS = set(
        "@%%()(),,。;;::、??!!·…-—_+<>[]{}|\\/\"'`~$^&*#"
    )

    def __init__(self, config: Dict[str, Any] | None = None):
        """初始化渲染器缓存并允许注入额外配置(如主题覆盖)"""
        self.config = config or {}
        self.document: Dict[str, Any] = {}
        self.widget_scripts: List[str] = []
        self.chart_counter = 0
        self.toc_entries: List[Dict[str, Any]] = []
        self.heading_counter = 0
        self.metadata: Dict[str, Any] = {}
        self.chapters: List[Dict[str, Any]] = []
        self.chapter_anchor_map: Dict[str, str] = {}
        self.heading_label_map: Dict[str, Dict[str, Any]] = {}
        self.primary_heading_index = 0
        self.secondary_heading_index = 0
        self.toc_rendered = False
        self.hero_kpi_signature: tuple | None = None
        self._current_chapter: Dict[str, Any] | None = None
        self._lib_cache: Dict[str, str] = {}
        self._pdf_font_base64: str | None = None

        # 初始化图表验证和修复器
        self.chart_validator = create_chart_validator()
        llm_repair_fns = create_llm_repair_functions()
        self.chart_repairer = create_chart_repairer(
            validator=self.chart_validator,
            llm_repair_fns=llm_repair_fns
        )
        # 记录修复失败的图表,避免多次触发LLM循环修复
        self._chart_failure_notes: Dict[str, str] = {}
        self._chart_failure_recorded: set[str] = set()

        # 统计信息
        self.chart_validation_stats = {
            'total': 0,
            'valid': 0,
            'repaired_locally': 0,
            'repaired_api': 0,
            'failed': 0
        }

    @staticmethod
    def _get_lib_path() -> Path:
        """获取第三方库文件的目录路径"""
        return Path(__file__).parent / "libs"

    @staticmethod
    def _get_font_path() -> Path:
        """返回PDF导出所需字体的路径(使用优化后的子集字体)"""
        return Path(__file__).parent / "assets" / "fonts" / "SourceHanSerifSC-Medium-Subset.ttf"

    def _load_lib(self, filename: str) -> str:
        """
        加载指定的第三方库文件内容

        参数:
            filename: 库文件名

        返回:
            str: 库文件的JavaScript代码内容
        """
        if filename in self._lib_cache:
            return self._lib_cache[filename]

        lib_path = self._get_lib_path() / filename
        try:
            with open(lib_path, 'r', encoding='utf-8') as f:
                content = f.read()
                self._lib_cache[filename] = content
                return content
        except FileNotFoundError:
            print(f"警告: 库文件 {filename} 未找到,将使用CDN备用链接")
            return ""
        except Exception as e:
            print(f"警告: 读取库文件 {filename} 时出错: {e}")
            return ""

    def _load_pdf_font_data(self) -> str:
        """加载PDF字体的Base64数据,避免重复读取大型文件"""
        if self._pdf_font_base64 is not None:
            return self._pdf_font_base64
        font_path = self._get_font_path()
        try:
            data = font_path.read_bytes()
            self._pdf_font_base64 = base64.b64encode(data).decode("ascii")
            return self._pdf_font_base64
        except FileNotFoundError:
            logger.warning("PDF字体文件缺失:%s", font_path)
        except Exception as exc:
            logger.warning("读取PDF字体文件失败:%s (%s)", font_path, exc)
        self._pdf_font_base64 = ""
        return self._pdf_font_base64

    def _build_script_with_fallback(
        self,
        inline_code: str,
        cdn_url: str,
        check_expression: str,
        lib_name: str,
        is_defer: bool = False
    ) -> str:
        """
        构建带有CDN fallback机制的script标签

        策略:
        1. 优先嵌入本地库代码
        2. 添加检测脚本,验证库是否成功加载
        3. 如果检测失败,动态加载CDN版本作为备用

        参数:
            inline_code: 本地库的JavaScript代码内容
            cdn_url: CDN备用链接
            check_expression: JavaScript表达式,用于检测库是否加载成功
            lib_name: 库名称(用于日志输出)
            is_defer: 是否使用defer属性

        返回:
            str: 完整的script标签HTML
        """
        defer_attr = ' defer' if is_defer else ''

        if inline_code:
            # 嵌入本地库代码,并添加fallback检测
            return f"""
  <script{defer_attr}>
    // {lib_name} - 嵌入式版本
    try {{
      {inline_code}
    }} catch (e) {{
      console.error('{lib_name}嵌入式加载失败:', e);
    }}
  </script>
  <script{defer_attr}>
    // {lib_name} - CDN Fallback检测
    (function() {{
      var checkLib = function() {{
        if (!({check_expression})) {{
          console.warn('{lib_name}本地版本加载失败,正在从CDN加载备用版本...');
          var script = document.createElement('script');
          script.src = '{cdn_url}';
          script.onerror = function() {{
            console.error('{lib_name} CDN备用加载也失败了');
          }};
          script.onload = function() {{
            console.log('{lib_name} CDN备用版本加载成功');
          }};
          document.head.appendChild(script);
        }}
      }};

      // 延迟检测,确保嵌入代码有时间执行
      if (document.readyState === 'loading') {{
        document.addEventListener('DOMContentLoaded', function() {{
          setTimeout(checkLib, 100);
        }});
      }} else {{
        setTimeout(checkLib, 100);
      }}
    }})();
  </script>""".strip()
        else:
            # 本地文件读取失败,直接使用CDN
            logger.warning(f"{lib_name}本地文件未找到或读取失败,将直接使用CDN")
            return f'  <script{defer_attr} src="{cdn_url}"></script>'

    # ====== 公共入口 ======

    def render(self, document_ir: Dict[str, Any]) -> str:
        """
        接收Document IR,重置内部状态并输出完整HTML。

        参数:
            document_ir: 由 DocumentComposer 生成的整本报告数据。

        返回:
            str: 可直接写入磁盘的完整HTML文档。
        """
        self.document = document_ir or {}
        self.widget_scripts = []
        self.chart_counter = 0
        self.heading_counter = 0
        self.metadata = self.document.get("metadata", {}) or {}
        raw_chapters = self.document.get("chapters", []) or []
        self.toc_rendered = False
        self.chapters = self._prepare_chapters(raw_chapters)
        self.chapter_anchor_map = {
            chapter.get("chapterId"): chapter.get("anchor")
            for chapter in self.chapters
            if chapter.get("chapterId") and chapter.get("anchor")
        }
        self.heading_label_map = self._compute_heading_labels(self.chapters)
        self.toc_entries = self._collect_toc_entries(self.chapters)

        # 重置图表验证统计
        self.chart_validation_stats = {
            'total': 0,
            'valid': 0,
            'repaired_locally': 0,
            'repaired_api': 0,
            'failed': 0
        }
        # 每次渲染重新统计失败计数,但保留失败原因,避免重复LLM调用
        self._chart_failure_recorded = set()

        metadata = self.metadata
        theme_tokens = metadata.get("themeTokens") or self.document.get("themeTokens", {})
        title = metadata.get("title") or metadata.get("query") or "智能舆情报告"
        hero_kpis = (metadata.get("hero") or {}).get("kpis")
        self.hero_kpi_signature = self._kpi_signature_from_items(hero_kpis)

        head = self._render_head(title, theme_tokens)
        body = self._render_body()

        # 输出图表验证统计
        self._log_chart_validation_stats()

        return f"<!DOCTYPE html>\n<html lang=\"zh-CN\" class=\"no-js\">\n{head}\n{body}\n</html>"

    # ====== 头部 / 正文 ======

    def _resolve_color_value(self, value: Any, fallback: str) -> str:
        """从颜色token中提取字符串值"""
        if isinstance(value, str):
            value = value.strip()
            return value or fallback
        if isinstance(value, dict):
            for key in ("main", "value", "color", "base", "default"):
                candidate = value.get(key)
                if isinstance(candidate, str) and candidate.strip():
                    return candidate.strip()
            for candidate in value.values():
                if isinstance(candidate, str) and candidate.strip():
                    return candidate.strip()
        return fallback

    def _resolve_color_family(self, value: Any, fallback: Dict[str, str]) -> Dict[str, str]:
        """解析主/亮/暗三色,缺失时回落到默认值"""
        result = {
            "main": fallback.get("main", "#007bff"),
            "light": fallback.get("light", fallback.get("main", "#007bff")),
            "dark": fallback.get("dark", fallback.get("main", "#007bff")),
        }
        if isinstance(value, str):
            stripped = value.strip()
            if stripped:
                result["main"] = stripped
            return result
        if isinstance(value, dict):
            result["main"] = self._resolve_color_value(value.get("main") or value, result["main"])
            result["light"] = self._resolve_color_value(value.get("light") or value.get("lighter"), result["light"])
            result["dark"] = self._resolve_color_value(value.get("dark") or value.get("darker"), result["dark"])
        return result

    def _render_head(self, title: str, theme_tokens: Dict[str, Any]) -> str:
        """
        渲染<head>部分,加载主题CSS与必要的脚本依赖。

        参数:
            title: 页面title标签内容。
            theme_tokens: 主题变量,用于注入CSS。

        返回:
            str: head片段HTML。
        """
        css = self._build_css(theme_tokens)

        # 加载第三方库
        chartjs = self._load_lib("chart.js")
        chartjs_sankey = self._load_lib("chartjs-chart-sankey.js")
        html2canvas = self._load_lib("html2canvas.min.js")
        jspdf = self._load_lib("jspdf.umd.min.js")
        mathjax = self._load_lib("mathjax.js")
        wordcloud2 = self._load_lib("wordcloud2.min.js")

        # 生成嵌入式script标签,并为每个库添加CDN fallback机制
        # Chart.js - 主要图表库
        chartjs_tag = self._build_script_with_fallback(
            inline_code=chartjs,
            cdn_url="https://cdn.jsdelivr.net/npm/chart.js",
            check_expression="typeof Chart !== 'undefined'",
            lib_name="Chart.js"
        )

        # Chart.js Sankey插件
        sankey_tag = self._build_script_with_fallback(
            inline_code=chartjs_sankey,
            cdn_url="https://cdn.jsdelivr.net/npm/chartjs-chart-sankey@4",
            check_expression="typeof Chart !== 'undefined' && Chart.controllers && Chart.controllers.sankey",
            lib_name="chartjs-chart-sankey"
        )

        # wordcloud2 - 词云渲染
        wordcloud_tag = self._build_script_with_fallback(
            inline_code=wordcloud2,
            cdn_url="https://cdnjs.cloudflare.com/ajax/libs/wordcloud2.js/1.2.2/wordcloud2.min.js",
            check_expression="typeof WordCloud !== 'undefined'",
            lib_name="wordcloud2"
        )

        # html2canvas - 用于截图
        html2canvas_tag = self._build_script_with_fallback(
            inline_code=html2canvas,
            cdn_url="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js",
            check_expression="typeof html2canvas !== 'undefined'",
            lib_name="html2canvas"
        )

        # jsPDF - 用于PDF导出
        jspdf_tag = self._build_script_with_fallback(
            inline_code=jspdf,
            cdn_url="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js",
            check_expression="typeof jspdf !== 'undefined'",
            lib_name="jsPDF"
        )

        # MathJax - 数学公式渲染
        mathjax_tag = self._build_script_with_fallback(
            inline_code=mathjax,
            cdn_url="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js",
            check_expression="typeof MathJax !== 'undefined'",
            lib_name="MathJax",
            is_defer=True
        )

        # PDF字体数据不再嵌入HTML,减小文件体积
        pdf_font_script = ""

        return f"""
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>{self._escape_html(title)}</title>
  {chartjs_tag}
  {sankey_tag}
  {wordcloud_tag}
  {html2canvas_tag}
  {jspdf_tag}
  <script>
    window.MathJax = {{
      tex: {{
        inlineMath: [['$', '$'], ['\\\\(', '\\\\)']],
        displayMath: [['$$','$$'], ['\\\\[','\\\\]']]
      }},
      options: {{
        skipHtmlTags: ['script','noscript','style','textarea','pre','code'],
        processEscapes: true
      }}
    }};
  </script>
  {mathjax_tag}
  {pdf_font_script}
  <style>
{css}
  </style>
  <script>
    document.documentElement.classList.remove('no-js');
    document.documentElement.classList.add('js-ready');
  </script>
</head>""".strip()

    def _render_body(self) -> str:
        """
        拼装<body>结构,包含头部、导航、章节和脚本。
        新版本:移除独立的cover section,标题合并到hero section中。

        返回:
            str: body片段HTML。
        """
        header = self._render_header()
        # cover = self._render_cover()  # 不再单独渲染cover
        hero = self._render_hero()
        toc_section = self._render_toc_section()
        chapters = "".join(self._render_chapter(chapter) for chapter in self.chapters)
        widget_scripts = "\n".join(self.widget_scripts)
        hydration = self._hydration_script()
        overlay = """
<div id="export-overlay" class="export-overlay no-print" aria-hidden="true">
  <div class="export-dialog" role="status" aria-live="assertive">
    <div class="export-spinner" aria-hidden="true"></div>
    <p class="export-status">正在导出PDF,请稍候...</p>
    <div class="export-progress" role="progressbar" aria-valuetext="正在导出">
      <div class="export-progress-bar"></div>
    </div>
  </div>
</div>
""".strip()

        return f"""
<body>
{header}
{overlay}
<main>
{hero}
{toc_section}
{chapters}
</main>
{widget_scripts}
{hydration}
</body>""".strip()

    # ====== 页眉 / 元信息 / 目录 ======

    def _render_header(self) -> str:
        """
        渲染吸顶头部,包含标题、副标题与功能按钮。

        返回:
            str: header HTML。
        """
        metadata = self.metadata
        title = metadata.get("title") or "智能舆情分析报告"
        subtitle = metadata.get("subtitle") or metadata.get("templateName") or "自动生成"
        return f"""
<header class="report-header no-print">
  <div>
    <h1>{self._escape_html(title)}</h1>
    <p class="subtitle">{self._escape_html(subtitle)}</p>
    {self._render_tagline()}
  </div>
  <div class="header-actions">
    <theme-button value="light" id="theme-toggle" size="1.5"></theme-button>
    <button id="print-btn" class="action-btn" type="button">打印页面</button>
    <button id="export-btn" class="action-btn" type="button" style="display: none;">⬇️ 导出PDF</button>
  </div>
</header>
""".strip()

    def _render_tagline(self) -> str:
        """
        渲染标题下方的标语,如无标语则返回空字符串。

        返回:
            str: tagline HTML或空串。
        """
        tagline = self.metadata.get("tagline")
        if not tagline:
            return ""
        return f'<p class="tagline">{self._escape_html(tagline)}</p>'

    def _render_cover(self) -> str:
        """
        文章开头的封面区,居中展示标题与“文章总览”提示。

        返回:
            str: cover section HTML。
        """
        title = self.metadata.get("title") or "智能舆情报告"
        subtitle = self.metadata.get("subtitle") or self.metadata.get("templateName") or ""
        overview_hint = "文章总览"
        return f"""
<section class="cover">
  <p class="cover-hint">{overview_hint}</p>
  <h1>{self._escape_html(title)}</h1>
  <p class="cover-subtitle">{self._escape_html(subtitle)}</p>
</section>
""".strip()

    def _render_hero(self) -> str:
        """
        根据layout中的hero字段输出摘要/KPI/亮点区。
        新版本:将标题和总览合并在一起,去掉椭圆背景。

        返回:
            str: hero区HTML,若无数据则为空字符串。
        """
        hero = self.metadata.get("hero") or {}
        if not hero:
            return ""

        # 获取标题和副标题
        title = self.metadata.get("title") or "智能舆情报告"
        subtitle = self.metadata.get("subtitle") or self.metadata.get("templateName") or ""

        summary = hero.get("summary")
        summary_html = f'<p class="hero-summary">{self._escape_html(summary)}</p>' if summary else ""
        highlights = hero.get("highlights") or []
        highlight_html = "".join(
            f'<li><span class="badge">{self._escape_html(text)}</span></li>'
            for text in highlights
        )
        actions = hero.get("actions") or []
        actions_html = "".join(
            f'<button class="ghost-btn" type="button">{self._escape_html(text)}</button>'
            for text in actions
        )
        kpi_cards = ""
        for item in hero.get("kpis", []):
            delta = item.get("delta")
            tone = item.get("tone") or "neutral"
            delta_html = f'<span class="delta {tone}">{self._escape_html(delta)}</span>' if delta else ""
            kpi_cards += f"""
            <div class="hero-kpi">
                <div class="label">{self._escape_html(item.get("label"))}</div>
                <div class="value">{self._escape_html(item.get("value"))}</div>
                {delta_html}
            </div>
            """

        return f"""
<section class="hero-section-combined">
  <div class="hero-header">
    <p class="hero-hint">文章总览</p>
    <h1 class="hero-title">{self._escape_html(title)}</h1>
    <p class="hero-subtitle">{self._escape_html(subtitle)}</p>
  </div>
  <div class="hero-body">
    <div class="hero-content">
      {summary_html}
      <ul class="hero-highlights">{highlight_html}</ul>
      <div class="hero-actions">{actions_html}</div>
    </div>
    <div class="hero-side">
      {kpi_cards}
    </div>
  </div>
</section>
""".strip()

    def _render_meta_panel(self) -> str:
        """当前需求不展示元信息,保留方法便于后续扩展"""
        return ""

    def _render_toc_section(self) -> str:
        """
        生成目录模块,如无目录数据则返回空字符串。

        返回:
            str: toc HTML结构。
        """
        if not self.toc_entries:
            return ""
        if self.toc_rendered:
            return ""
        toc_config = self.metadata.get("toc") or {}
        toc_title = toc_config.get("title") or "📚 目录"
        toc_items = "".join(
            self._format_toc_entry(entry)
            for entry in self.toc_entries
        )
        self.toc_rendered = True
        return f"""
<nav class="toc">
  <div class="toc-title">{self._escape_html(toc_title)}</div>
  <ul>
    {toc_items}
  </ul>
</nav>
""".strip()

    def _collect_toc_entries(self, chapters: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        根据metadata中的tocPlan或章节heading收集目录项。

        参数:
            chapters: Document IR中的章节数组。

        返回:
            list[dict]: 规范化后的目录条目,包含level/text/anchor/description。
        """
        metadata = self.metadata
        toc_config = metadata.get("toc") or {}
        custom_entries = toc_config.get("customEntries")
        entries: List[Dict[str, Any]] = []

        if custom_entries:
            for entry in custom_entries:
                anchor = entry.get("anchor") or self.chapter_anchor_map.get(entry.get("chapterId"))

                # 验证anchor是否有效
                if not anchor:
                    logger.warning(
                        f"目录项 '{entry.get('display') or entry.get('title')}' "
                        f"缺少有效的anchor,已跳过"
                    )
                    continue

                # 验证anchor是否在chapter_anchor_map中或在chapters的blocks中
                anchor_valid = self._validate_toc_anchor(anchor, chapters)
                if not anchor_valid:
                    logger.warning(
                        f"目录项 '{entry.get('display') or entry.get('title')}' "
                        f"的anchor '{anchor}' 在文档中未找到对应的章节"
                    )

                # 清理描述文本
                description = entry.get("description")
                if description:
                    description = self._clean_text_from_json_artifacts(description)

                entries.append(
                    {
                        "level": entry.get("level", 2),
                        "text": entry.get("display") or entry.get("title") or "",
                        "anchor": anchor,
                        "description": description,
                    }
                )
            return entries

        for chapter in chapters or []:
            for block in chapter.get("blocks", []):
                if block.get("type") == "heading":
                    anchor = block.get("anchor") or chapter.get("anchor") or ""
                    if not anchor:
                        continue
                    mapped = self.heading_label_map.get(anchor, {})
                    # 清理描述文本
                    description = mapped.get("description")
                    if description:
                        description = self._clean_text_from_json_artifacts(description)
                    entries.append(
                        {
                            "level": block.get("level", 2),
                            "text": mapped.get("display") or block.get("text", ""),
                            "anchor": anchor,
                            "description": description,
                        }
                    )
        return entries

    def _validate_toc_anchor(self, anchor: str, chapters: List[Dict[str, Any]]) -> bool:
        """
        验证目录anchor是否在文档中存在对应的章节或heading。

        参数:
            anchor: 需要验证的anchor
            chapters: Document IR中的章节数组

        返回:
            bool: anchor是否有效
        """
        # 检查是否是章节anchor
        if anchor in self.chapter_anchor_map.values():
            return True

        # 检查是否在heading_label_map中
        if anchor in self.heading_label_map:
            return True

        # 检查章节的blocks中是否有这个anchor
        for chapter in chapters or []:
            chapter_anchor = chapter.get("anchor")
            if chapter_anchor == anchor:
                return True

            for block in chapter.get("blocks", []):
                block_anchor = block.get("anchor")
                if block_anchor == anchor:
                    return True

        return False

    def _prepare_chapters(self, chapters: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """复制章节并展开其中序列化的block,避免渲染缺失"""
        prepared: List[Dict[str, Any]] = []
        for chapter in chapters or []:
            chapter_copy = copy.deepcopy(chapter)
            chapter_copy["blocks"] = self._expand_blocks_in_place(chapter_copy.get("blocks", []))
            prepared.append(chapter_copy)
        return prepared

    def _expand_blocks_in_place(self, blocks: List[Dict[str, Any]] | None) -> List[Dict[str, Any]]:
        """遍历block列表,将内嵌JSON串拆解为独立block"""
        expanded: List[Dict[str, Any]] = []
        for block in blocks or []:
            extras = self._extract_embedded_blocks(block)
            expanded.append(block)
            if extras:
                expanded.extend(self._expand_blocks_in_place(extras))
        return expanded

    def _extract_embedded_blocks(self, block: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        在block内部查找被误写成字符串的block列表,并返回补充的block
        """
        extracted: List[Dict[str, Any]] = []

        def traverse(node: Any) -> None:
            """递归遍历block树,识别text字段内潜在的嵌套block JSON"""
            if isinstance(node, dict):
                for key, value in list(node.items()):
                    if key == "text" and isinstance(value, str):
                        decoded = self._decode_embedded_block_payload(value)
                        if decoded:
                            node[key] = ""
                            extracted.extend(decoded)
                        continue
                    traverse(value)
            elif isinstance(node, list):
                for item in node:
                    traverse(item)

        traverse(block)
        return extracted

    def _decode_embedded_block_payload(self, raw: str) -> List[Dict[str, Any]] | None:
        """
        将字符串形式的block描述恢复为结构化列表。
        """
        if not isinstance(raw, str):
            return None
        stripped = raw.strip()
        if not stripped or stripped[0] not in "{[":
            return None
        payload: Any | None = None
        decode_targets = [stripped]
        if stripped and stripped[0] != "[":
            decode_targets.append(f"[{stripped}]")
        for candidate in decode_targets:
            try:
                payload = json.loads(candidate)
                break
            except json.JSONDecodeError:
                continue
        if payload is None:
            for candidate in decode_targets:
                try:
                    payload = ast.literal_eval(candidate)
                    break
                except (ValueError, SyntaxError):
                    continue
        if payload is None:
            return None

        blocks = self._collect_blocks_from_payload(payload)
        return blocks or None

    @staticmethod
    def _looks_like_block(payload: Dict[str, Any]) -> bool:
        """粗略判断dict是否符合block结构"""
        if not isinstance(payload, dict):
            return False
        if "type" in payload and isinstance(payload["type"], str):
            return True
        structural_keys = {"blocks", "rows", "items", "widgetId", "widgetType", "data"}
        return any(key in payload for key in structural_keys)

    def _collect_blocks_from_payload(self, payload: Any) -> List[Dict[str, Any]]:
        """递归收集payload中的block节点"""
        collected: List[Dict[str, Any]] = []
        if isinstance(payload, dict):
            block_list = payload.get("blocks")
            block_type = payload.get("type")
            if isinstance(block_list, list) and not block_type:
                for candidate in block_list:
                    collected.extend(self._collect_blocks_from_payload(candidate))
                return collected
            if payload.get("cells") and not block_type:
                for cell in payload["cells"]:
                    collected.extend(self._collect_blocks_from_payload(cell.get("blocks")))
                return collected
            if payload.get("items") and not block_type:
                for item in payload["items"]:
                    collected.extend(self._collect_blocks_from_payload(item))
                return collected
            appended = False
            if block_type or payload.get("widgetId") or payload.get("rows"):
                coerced = self._coerce_block_dict(payload)
                if coerced:
                    collected.append(coerced)
                    appended = True
            items = payload.get("items")
            if isinstance(items, list) and not block_type:
                for item in items:
                    collected.extend(self._collect_blocks_from_payload(item))
                return collected
            if appended:
                return collected
        elif isinstance(payload, list):
            for item in payload:
                collected.extend(self._collect_blocks_from_payload(item))
        elif payload is None:
            return collected
        return collected

    def _coerce_block_dict(self, payload: Any) -> Dict[str, Any] | None:
        """尝试将dict补充为合法block结构"""
        if not isinstance(payload, dict):
            return None
        block = copy.deepcopy(payload)
        block_type = block.get("type")
        if not block_type:
            if "widgetId" in block:
                block_type = block["type"] = "widget"
            elif "rows" in block or "cells" in block:
                block_type = block["type"] = "table"
                if "rows" not in block and isinstance(block.get("cells"), list):
                    block["rows"] = [{"cells": block.pop("cells")}]
            elif "items" in block:
                block_type = block["type"] = "list"
        return block if block.get("type") else None

    def _format_toc_entry(self, entry: Dict[str, Any]) -> str:
        """
        将单个目录项转为带描述的HTML行。

        参数:
            entry: 目录条目,需包含 `text` 与 `anchor`。

        返回:
            str: `<li>` 形式的HTML。
        """
        desc = entry.get("description")
        # 清理描述文本中的JSON片段
        if desc:
            desc = self._clean_text_from_json_artifacts(desc)
        desc_html = f'<p class="toc-desc">{self._escape_html(desc)}</p>' if desc else ""
        level = entry.get("level", 2)
        css_level = 1 if level <= 2 else min(level, 4)
        return f'<li class="level-{css_level}"><a href="#{self._escape_attr(entry["anchor"])}">{self._escape_html(entry["text"])}</a>{desc_html}</li>'

    def _compute_heading_labels(self, chapters: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
        """
        预计算各级标题的编号(章:一、二;节:1.1;小节:1.1.1)。

        参数:
            chapters: Document IR中的章节数组。

        返回:
            dict: 锚点到编号/描述的映射,方便TOC与正文引用。
        """
        label_map: Dict[str, Dict[str, Any]] = {}

        for chap_idx, chapter in enumerate(chapters or [], start=1):
            chapter_heading_seen = False
            section_idx = 0
            subsection_idx = 0
            deep_counters: Dict[int, int] = {}

            for block in chapter.get("blocks", []):
                if block.get("type") != "heading":
                    continue
                level = block.get("level", 2)
                anchor = block.get("anchor") or chapter.get("anchor")
                if not anchor:
                    continue

                raw_text = block.get("text", "")
                clean_title = self._strip_order_prefix(raw_text)
                label = None
                display_text = raw_text

                if not chapter_heading_seen:
                    label = f"{self._to_chinese_numeral(chap_idx)}、"
                    display_text = f"{label} {clean_title}".strip()
                    chapter_heading_seen = True
                    section_idx = 0
                    subsection_idx = 0
                    deep_counters.clear()
                elif level <= 2:
                    section_idx += 1
                    subsection_idx = 0
                    deep_counters.clear()
                    label = f"{chap_idx}.{section_idx}"
                    display_text = f"{label} {clean_title}".strip()
                else:
                    if section_idx == 0:
                        section_idx = 1
                    if level == 3:
                        subsection_idx += 1
                        deep_counters.clear()
                        label = f"{chap_idx}.{section_idx}.{subsection_idx}"
                    else:
                        deep_counters[level] = deep_counters.get(level, 0) + 1
                        parts = [str(chap_idx), str(section_idx or 1), str(subsection_idx or 1)]
                        for lvl in sorted(deep_counters.keys()):
                            parts.append(str(deep_counters[lvl]))
                        label = ".".join(parts)
                    display_text = f"{label} {clean_title}".strip()

                label_map[anchor] = {
                    "level": level,
                    "display": display_text,
                    "label": label,
                    "title": clean_title,
                }
        return label_map

    @staticmethod
    def _strip_order_prefix(text: str) -> str:
        """移除形如“1.0 ”或“一、”的前缀,得到纯标题"""
        if not text:
            return ""
        separators = [" ", "、", ".", "."]
        stripped = text.lstrip()
        for sep in separators:
            parts = stripped.split(sep, 1)
            if len(parts) == 2 and parts[0]:
                return parts[1].strip()
        return stripped.strip()

    @staticmethod
    def _to_chinese_numeral(number: int) -> str:
        """将1/2/3映射为中文序号(十内)"""
        numerals = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]
        if number <= 10:
            return numerals[number]
        tens, ones = divmod(number, 10)
        if number < 20:
            return "十" + (numerals[ones] if ones else "")
        words = ""
        if tens > 0:
            words += numerals[tens] + "十"
        if ones:
            words += numerals[ones]
        return words

    # ====== 章节与块级渲染 ======

    def _render_chapter(self, chapter: Dict[str, Any]) -> str:
        """
        将章节blocks包裹进<section>,便于CSS控制。

        参数:
            chapter: 单个章节JSON。

        返回:
            str: section包裹的HTML。
        """
        section_id = self._escape_attr(chapter.get("anchor") or f"chapter-{chapter.get('chapterId', 'x')}")
        prev_chapter = self._current_chapter
        self._current_chapter = chapter
        try:
            blocks_html = self._render_blocks(chapter.get("blocks", []))
        finally:
            self._current_chapter = prev_chapter
        return f'<section id="{section_id}" class="chapter">\n{blocks_html}\n</section>'

    def _render_blocks(self, blocks: List[Dict[str, Any]]) -> str:
        """
        顺序渲染章节内所有block。

        参数:
            blocks: 章节内部的block数组。

        返回:
            str: 拼接后的HTML。
        """
        return "".join(self._render_block(block) for block in blocks or [])

    def _render_block(self, block: Dict[str, Any]) -> str:
        """
        根据block.type分派到不同的渲染函数。

        参数:
            block: 单个block对象。

        返回:
            str: 渲染后的HTML,未知类型会输出JSON调试信息。
        """
        block_type = block.get("type")
        handlers = {
            "heading": self._render_heading,
            "paragraph": self._render_paragraph,
            "list": self._render_list,
            "table": self._render_table,
            "swotTable": self._render_swot_table,
            "blockquote": self._render_blockquote,
            "engineQuote": self._render_engine_quote,
            "hr": lambda b: "<hr />",
            "code": self._render_code,
            "math": self._render_math,
            "figure": self._render_figure,
            "callout": self._render_callout,
            "kpiGrid": self._render_kpi_grid,
            "widget": self._render_widget,
            "toc": lambda b: self._render_toc_section(),
        }
        handler = handlers.get(block_type)
        if handler:
            html_fragment = handler(block)
            return self._wrap_error_block(html_fragment, block)
        # 兼容旧格式:缺少type但包含inlines时按paragraph处理
        if isinstance(block, dict) and block.get("inlines"):
            html_fragment = self._render_paragraph({"inlines": block.get("inlines")})
            return self._wrap_error_block(html_fragment, block)
        # 兼容直接传入字符串的场景
        if isinstance(block, str):
            html_fragment = self._render_paragraph({"inlines": [{"text": block}]})
            return self._wrap_error_block(html_fragment, {"meta": {}, "type": "paragraph"})
        if isinstance(block.get("blocks"), list):
            html_fragment = self._render_blocks(block["blocks"])
            return self._wrap_error_block(html_fragment, block)
        fallback = f'<pre class="unknown-block">{self._escape_html(json.dumps(block, ensure_ascii=False, indent=2))}</pre>'
        return self._wrap_error_block(fallback, block)

    def _wrap_error_block(self, html_fragment: str, block: Dict[str, Any]) -> str:
        """若block标记了error元数据,则包裹提示容器并注入tooltip。"""
        if not html_fragment:
            return html_fragment
        meta = block.get("meta") or {}
        log_ref = meta.get("errorLogRef")
        if not isinstance(log_ref, dict):
            return html_fragment
        raw_preview = (meta.get("rawJsonPreview") or "")[:1200]
        error_message = meta.get("errorMessage") or "LLM返回块解析错误"
        importance = meta.get("importance") or "standard"
        ref_label = ""
        if log_ref.get("relativeFile") and log_ref.get("entryId"):
            ref_label = f"{log_ref['relativeFile']}#{log_ref['entryId']}"
        tooltip = f"{error_message} | {ref_label}".strip()
        attr_raw = self._escape_attr(raw_preview or tooltip)
        attr_title = self._escape_attr(tooltip)
        class_suffix = self._escape_attr(importance)
        return (
            f'<div class="llm-error-block importance-{class_suffix}" '
            f'data-raw="{attr_raw}" title="{attr_title}">{html_fragment}</div>'
        )

    def _render_heading(self, block: Dict[str, Any]) -> str:
        """渲染heading block,确保锚点存在"""
        original_level = max(1, min(6, block.get("level", 2)))
        if original_level <= 2:
            level = 2
        elif original_level == 3:
            level = 3
        else:
            level = min(original_level, 6)
        anchor = block.get("anchor")
        if anchor:
            anchor_attr = self._escape_attr(anchor)
        else:
            self.heading_counter += 1
            anchor = f"heading-{self.heading_counter}"
            anchor_attr = self._escape_attr(anchor)
        mapping = self.heading_label_map.get(anchor, {})
        display_text = mapping.get("display") or block.get("text", "")
        subtitle = block.get("subtitle")
        subtitle_html = f'<small>{self._escape_html(subtitle)}</small>' if subtitle else ""
        return f'<h{level} id="{anchor_attr}">{self._escape_html(display_text)}{subtitle_html}</h{level}>'

    def _render_paragraph(self, block: Dict[str, Any]) -> str:
        """渲染段落,内部通过inline run保持混排样式"""
        inlines_data = block.get("inlines", [])
        # 仅包含单个display公式时直接渲染为块,避免<p>内嵌<div>
        if len(inlines_data) == 1:
            standalone = self._render_standalone_math_inline(inlines_data[0])
            if standalone:
                return standalone

        inlines = "".join(self._render_inline(run) for run in inlines_data)
        return f"<p>{inlines}</p>"

    def _render_standalone_math_inline(self, run: Dict[str, Any] | str) -> str | None:
        """当段落只包含单个display公式时,转为math-block避免破坏行内布局"""
        if isinstance(run, dict):
            text_value, marks = self._normalize_inline_payload(run)
            if marks:
                return None
            math_id_hint = run.get("mathIds") or run.get("mathId")
        else:
            text_value = "" if run is None else str(run)
            math_id_hint = None
            marks = []

        rendered = self._render_text_with_inline_math(
            text_value,
            math_id_hint,
            allow_display_block=True
        )
        if rendered and rendered.strip().startswith('<div class="math-block"'):
            return rendered
        return None

    def _render_list(self, block: Dict[str, Any]) -> str:
        """渲染有序/无序/任务列表"""
        list_type = block.get("listType", "bullet")
        tag = "ol" if list_type == "ordered" else "ul"
        extra_class = "task-list" if list_type == "task" else ""
        items_html = ""
        for item in block.get("items", []):
            content = self._render_blocks(item)
            if not content.strip():
                continue
            items_html += f"<li>{content}</li>"
        class_attr = f' class="{extra_class}"' if extra_class else ""
        return f'<{tag}{class_attr}>{items_html}</{tag}>'

    def _render_table(self, block: Dict[str, Any]) -> str:
        """
        渲染表格,同时保留caption与单元格属性。

        参数:
            block: table类型的block。

        返回:
            str: 包含<table>结构的HTML。
        """
        rows = self._normalize_table_rows(block.get("rows") or [])
        rows_html = ""
        for row in rows:
            row_cells = ""
            for cell in row.get("cells", []):
                cell_tag = "th" if cell.get("header") or cell.get("isHeader") else "td"
                attr = []
                if cell.get("rowspan"):
                    attr.append(f'rowspan="{int(cell["rowspan"])}"')
                if cell.get("colspan"):
                    attr.append(f'colspan="{int(cell["colspan"])}"')
                if cell.get("align"):
                    attr.append(f'class="align-{cell["align"]}"')
                attr_str = (" " + " ".join(attr)) if attr else ""
                content = self._render_blocks(cell.get("blocks", []))
                row_cells += f"<{cell_tag}{attr_str}>{content}</{cell_tag}>"
            rows_html += f"<tr>{row_cells}</tr>"
        caption = block.get("caption")
        caption_html = f"<caption>{self._escape_html(caption)}</caption>" if caption else ""
        return f'<div class="table-wrap"><table>{caption_html}<tbody>{rows_html}</tbody></table></div>'

    def _render_swot_table(self, block: Dict[str, Any]) -> str:
        """
        渲染四象限的SWOT分析,同时生成两种布局:
        1. 卡片布局(用于HTML网页显示)- 圆角矩形四象限
        2. 表格布局(用于PDF导出)- 结构化表格,支持分页
        
        PDF分页策略:
        - 使用表格形式,每个S/W/O/T象限为独立表格区块
        - 允许在不同象限之间分页
        - 每个象限内的条目尽量保持在一起
        """
        title = block.get("title") or "SWOT 分析"
        summary = block.get("summary")
        
        # ========== 卡片布局(HTML用)==========
        card_html = self._render_swot_card_layout(block, title, summary)
        
        # ========== 表格布局(PDF用)==========
        table_html = self._render_swot_pdf_table_layout(block, title, summary)
        
        # 返回包含两种布局的容器
        return f"""
        <div class="swot-container">
          {card_html}
          {table_html}
        </div>
        """
    
    def _render_swot_card_layout(self, block: Dict[str, Any], title: str, summary: str | None) -> str:
        """渲染SWOT卡片布局(用于HTML网页显示)"""
        quadrants = [
            ("strengths", "优势 Strengths", "S", "strength"),
            ("weaknesses", "劣势 Weaknesses", "W", "weakness"),
            ("opportunities", "机会 Opportunities", "O", "opportunity"),
            ("threats", "威胁 Threats", "T", "threat"),
        ]
        cells_html = ""
        for idx, (key, label, code, css) in enumerate(quadrants):
            items = self._normalize_swot_items(block.get(key))
            caption_text = f"{len(items)} 条要点" if items else "待补充"
            list_html = "".join(self._render_swot_item(item) for item in items) if items else '<li class="swot-empty">尚未填入要点</li>'
            first_cell_class = " swot-cell--first" if idx == 0 else ""
            cells_html += f"""
        <div class="swot-cell swot-cell--pageable {css}{first_cell_class}" data-swot-key="{key}">
          <div class="swot-cell__meta">
            <span class="swot-pill {css}">{self._escape_html(code)}</span>
            <div>
              <div class="swot-cell__title">{self._escape_html(label)}</div>
              <div class="swot-cell__caption">{self._escape_html(caption_text)}</div>
            </div>
          </div>
          <ul class="swot-list">{list_html}</ul>
        </div>"""
        summary_html = f'<p class="swot-card__summary">{self._escape_html(summary)}</p>' if summary else ""
        title_html = f'<div class="swot-card__title">{self._escape_html(title)}</div>' if title else ""
        legend = """
            <div class="swot-legend">
              <span class="swot-legend__item strength">S 优势</span>
              <span class="swot-legend__item weakness">W 劣势</span>
              <span class="swot-legend__item opportunity">O 机会</span>
              <span class="swot-legend__item threat">T 威胁</span>
            </div>
        """
        return f"""
        <div class="swot-card swot-card--html">
          <div class="swot-card__head">
            <div>{title_html}{summary_html}</div>
            {legend}
          </div>
          <div class="swot-grid">{cells_html}</div>
        </div>
        """
    
    def _render_swot_pdf_table_layout(self, block: Dict[str, Any], title: str, summary: str | None) -> str:
        """
        渲染SWOT表格布局(用于PDF导出)
        
        设计说明:
        - 整体为一个大表格,包含标题行和4个象限区域
        - 每个象限区域有自己的子标题行和内容行
        - 使用合并单元格来显示象限标题
        - 通过CSS控制分页行为
        """
        quadrants = [
            ("strengths", "S", "优势 Strengths", "swot-pdf-strength", "#1c7f6e"),
            ("weaknesses", "W", "劣势 Weaknesses", "swot-pdf-weakness", "#c0392b"),
            ("opportunities", "O", "机会 Opportunities", "swot-pdf-opportunity", "#1f5ab3"),
            ("threats", "T", "威胁 Threats", "swot-pdf-threat", "#b36b16"),
        ]
        
        # 标题和摘要
        summary_row = ""
        if summary:
            summary_row = f"""
            <tr class="swot-pdf-summary-row">
              <td colspan="4" class="swot-pdf-summary">{self._escape_html(summary)}</td>
            </tr>"""
        
        # 生成四个象限的表格内容
        quadrant_tables = ""
        for idx, (key, code, label, css_class, color) in enumerate(quadrants):
            items = self._normalize_swot_items(block.get(key))
            
            # 生成每个象限的内容行
            items_rows = ""
            if items:
                for item_idx, item in enumerate(items):
                    item_title = item.get("title") or item.get("label") or item.get("text") or "未命名要点"
                    item_detail = item.get("detail") or item.get("description") or ""
                    item_evidence = item.get("evidence") or item.get("source") or ""
                    item_impact = item.get("impact") or item.get("priority") or ""
                    item_score = item.get("score")
                    
                    # 构建详情内容
                    detail_parts = []
                    if item_detail:
                        detail_parts.append(item_detail)
                    if item_evidence:
                        detail_parts.append(f"佐证:{item_evidence}")
                    detail_text = "<br/>".join(detail_parts) if detail_parts else "-"
                    
                    # 构建标签
                    tags = []
                    if item_impact:
                        tags.append(f'<span class="swot-pdf-tag">{self._escape_html(item_impact)}</span>')
                    if item_score not in (None, ""):
                        tags.append(f'<span class="swot-pdf-tag swot-pdf-tag--score">评分 {self._escape_html(item_score)}</span>')
                    tags_html = " ".join(tags)
                    
                    # 第一行需要合并象限标题单元格
                    if item_idx == 0:
                        rowspan = len(items)
                        items_rows += f"""
            <tr class="swot-pdf-item-row {css_class}">
              <td rowspan="{rowspan}" class="swot-pdf-quadrant-label {css_class}">
                <span class="swot-pdf-code">{code}</span>
                <span class="swot-pdf-label-text">{self._escape_html(label.split()[0])}</span>
              </td>
              <td class="swot-pdf-item-num">{item_idx + 1}</td>
              <td class="swot-pdf-item-title">{self._escape_html(item_title)}</td>
              <td class="swot-pdf-item-detail">{detail_text}</td>
              <td class="swot-pdf-item-tags">{tags_html}</td>
            </tr>"""
                    else:
                        items_rows += f"""
            <tr class="swot-pdf-item-row {css_class}">
              <td class="swot-pdf-item-num">{item_idx + 1}</td>
              <td class="swot-pdf-item-title">{self._escape_html(item_title)}</td>
              <td class="swot-pdf-item-detail">{detail_text}</td>
              <td class="swot-pdf-item-tags">{tags_html}</td>
            </tr>"""
            else:
                # 没有内容时显示占位
                items_rows = f"""
            <tr class="swot-pdf-item-row {css_class}">
              <td class="swot-pdf-quadrant-label {css_class}">
                <span class="swot-pdf-code">{code}</span>
                <span class="swot-pdf-label-text">{self._escape_html(label.split()[0])}</span>
              </td>
              <td class="swot-pdf-item-num">-</td>
              <td colspan="3" class="swot-pdf-empty">暂无要点</td>
            </tr>"""
            
            # 每个象限作为一个独立的tbody,便于分页控制
            quadrant_tables += f"""
          <tbody class="swot-pdf-quadrant {css_class}">
            {items_rows}
          </tbody>"""
        
        return f"""
        <div class="swot-pdf-wrapper">
          <table class="swot-pdf-table">
            <caption class="swot-pdf-caption">{self._escape_html(title)}</caption>
            <thead class="swot-pdf-thead">
              <tr>
                <th class="swot-pdf-th-quadrant">象限</th>
                <th class="swot-pdf-th-num">序号</th>
                <th class="swot-pdf-th-title">要点</th>
                <th class="swot-pdf-th-detail">详细说明</th>
                <th class="swot-pdf-th-tags">影响/评分</th>
              </tr>
              {summary_row}
            </thead>
            {quadrant_tables}
          </table>
        </div>
        """

    def _normalize_swot_items(self, raw: Any) -> List[Dict[str, Any]]:
        """将SWOT条目规整为统一结构,兼容字符串/对象两种写法"""
        normalized: List[Dict[str, Any]] = []
        if raw is None:
            return normalized
        if isinstance(raw, (str, int, float)):
            text = self._safe_text(raw).strip()
            if text:
                normalized.append({"title": text})
            return normalized
        if not isinstance(raw, list):
            return normalized
        for entry in raw:
            if isinstance(entry, (str, int, float)):
                text = self._safe_text(entry).strip()
                if text:
                    normalized.append({"title": text})
                continue
            if not isinstance(entry, dict):
                continue
            title = entry.get("title") or entry.get("label") or entry.get("text")
            detail = entry.get("detail") or entry.get("description")
            evidence = entry.get("evidence") or entry.get("source")
            impact = entry.get("impact") or entry.get("priority")
            score = entry.get("score")
            if not title and isinstance(detail, str):
                title = detail
                detail = None
            if not (title or detail or evidence):
                continue
            normalized.append(
                {
                    "title": title,
                    "detail": detail,
                    "evidence": evidence,
                    "impact": impact,
                    "score": score,
                }
            )
        return normalized

    def _render_swot_item(self, item: Dict[str, Any]) -> str:
        """输出单个SWOT条目的HTML片段"""
        title = item.get("title") or item.get("label") or item.get("text") or "未命名要点"
        detail = item.get("detail") or item.get("description")
        evidence = item.get("evidence") or item.get("source")
        impact = item.get("impact") or item.get("priority")
        score = item.get("score")
        tags: List[str] = []
        if impact:
            tags.append(f'<span class="swot-tag">{self._escape_html(impact)}</span>')
        if score not in (None, ""):
            tags.append(f'<span class="swot-tag neutral">评分 {self._escape_html(score)}</span>')
        tags_html = f'<span class="swot-item-tags">{"".join(tags)}</span>' if tags else ""
        detail_html = f'<div class="swot-item-desc">{self._escape_html(detail)}</div>' if detail else ""
        evidence_html = f'<div class="swot-item-evidence">佐证:{self._escape_html(evidence)}</div>' if evidence else ""
        return f"""
            <li class="swot-item">
              <div class="swot-item-title">{self._escape_html(title)}{tags_html}</div>
              {detail_html}{evidence_html}
            </li>
        """

    def _normalize_table_rows(self, rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        检测并修正仅有单列的竖排表,转换为标准网格。

        参数:
            rows: 原始表格行。

        返回:
            list[dict]: 若检测到竖排表则返回转置后的行,否则原样返回。
        """
        if not rows:
            return []
        if not all(len((row.get("cells") or [])) == 1 for row in rows):
            return rows
        texts = [self._extract_row_text(row) for row in rows]
        header_span = self._detect_transposed_header_span(rows, texts)
        if not header_span:
            return rows
        normalized = self._transpose_single_cell_table(rows, header_span)
        return normalized or rows

    def _detect_transposed_header_span(self, rows: List[Dict[str, Any]], texts: List[str]) -> int:
        """推断竖排表头的行数,用于后续转置"""
        max_fields = min(8, len(rows) // 2)
        header_span = 0
        for idx, text in enumerate(texts):
            if idx >= max_fields:
                break
            if self._is_potential_table_header(text):
                header_span += 1
            else:
                break
        if header_span < 2:
            return 0
        remainder = texts[header_span:]
        if not remainder or (len(rows) - header_span) % header_span != 0:
            return 0
        if not any(self._looks_like_table_value(txt) for txt in remainder):
            return 0
        return header_span

    def _is_potential_table_header(self, text: str) -> bool:
        """根据长度与字符特征判断是否像表头字段"""
        if not text:
            return False
        stripped = text.strip()
        if not stripped or len(stripped) > 12:
            return False
        return not any(ch.isdigit() or ch in self.TABLE_COMPLEX_CHARS for ch in stripped)

    def _looks_like_table_value(self, text: str) -> bool:
        """判断该文本是否更像数据值,用于辅助判断转置"""
        if not text:
            return False
        stripped = text.strip()
        if len(stripped) >= 12:
            return True
        return any(ch.isdigit() or ch in self.TABLE_COMPLEX_CHARS for ch in stripped)

    def _transpose_single_cell_table(self, rows: List[Dict[str, Any]], span: int) -> List[Dict[str, Any]]:
        """将单列多行的表格转换为标准表头 + 若干数据行"""
        total = len(rows)
        if total <= span or (total - span) % span != 0:
            return []
        header_rows = rows[:span]
        data_rows = rows[span:]
        normalized: List[Dict[str, Any]] = []
        header_cells = []
        for row in header_rows:
            cell = copy.deepcopy((row.get("cells") or [{}])[0])
            cell["header"] = True
            header_cells.append(cell)
        normalized.append({"cells": header_cells})
        for start in range(0, len(data_rows), span):
            group = data_rows[start : start + span]
            if len(group) < span:
                break
            normalized.append(
                {
                    "cells": [
                        copy.deepcopy((item.get("cells") or [{}])[0])
                        for item in group
                    ]
                }
            )
        return normalized

    def _extract_row_text(self, row: Dict[str, Any]) -> str:
        """提取表格行中的纯文本,方便启发式分析"""
        cells = row.get("cells") or []
        if not cells:
            return ""
        cell = cells[0]
        texts: List[str] = []
        for block in cell.get("blocks", []):
            if isinstance(block, dict):
                if block.get("type") == "paragraph":
                    for inline in block.get("inlines") or []:
                        if isinstance(inline, dict):
                            value = inline.get("text")
                        else:
                            value = inline
                        if value is None:
                            continue
                        texts.append(str(value))
        return "".join(texts)

    def _render_blockquote(self, block: Dict[str, Any]) -> str:
        """渲染引用块,可嵌套其他block"""
        inner = self._render_blocks(block.get("blocks", []))
        return f"<blockquote>{inner}</blockquote>"

    def _render_engine_quote(self, block: Dict[str, Any]) -> str:
        """渲染单Engine发言块,带独立配色与标题"""
        engine_raw = (block.get("engine") or "").lower()
        engine = engine_raw if engine_raw in ENGINE_AGENT_TITLES else "insight"
        expected_title = ENGINE_AGENT_TITLES.get(engine, ENGINE_AGENT_TITLES["insight"])
        title_raw = block.get("title") if isinstance(block.get("title"), str) else ""
        title = title_raw if title_raw == expected_title else expected_title
        inner = self._render_blocks(block.get("blocks", []))
        return (
            f'<div class="engine-quote engine-{self._escape_attr(engine)}">'
            f'  <div class="engine-quote__header">'
            f'    <span class="engine-quote__dot"></span>'
            f'    <span class="engine-quote__title">{self._escape_html(title)}</span>'
            f'  </div>'
            f'  <div class="engine-quote__body">{inner}</div>'
            f'</div>'
        )

    def _render_code(self, block: Dict[str, Any]) -> str:
        """渲染代码块,附带语言信息"""
        lang = block.get("lang") or ""
        content = self._escape_html(block.get("content", ""))
        return f'<pre class="code-block" data-lang="{self._escape_attr(lang)}"><code>{content}</code></pre>'

    def _render_math(self, block: Dict[str, Any]) -> str:
        """渲染数学公式,占位符交给外部MathJax或后处理"""
        latex_raw = block.get("latex", "")
        latex = self._escape_html(self._normalize_latex_string(latex_raw))
        math_id = self._escape_attr(block.get("mathId", "")) if block.get("mathId") else ""
        id_attr = f' data-math-id="{math_id}"' if math_id else ""
        return f'<div class="math-block"{id_attr}>$$ {latex} $$</div>'

    def _render_figure(self, block: Dict[str, Any]) -> str:
        """根据新规范默认不渲染外部图片,改为友好提示"""
        caption = block.get("caption") or "图像内容已省略(仅允许HTML原生图表与表格)"
        return f'<div class="figure-placeholder">{self._escape_html(caption)}</div>'

    def _render_callout(self, block: Dict[str, Any]) -> str:
        """
        渲染高亮提示盒,tone决定颜色。

        参数:
            block: callout类型的block。

        返回:
            str: callout HTML,若内部包含不允许的块会被拆分。
        """
        tone = block.get("tone", "info")
        title = block.get("title")
        safe_blocks, trailing_blocks = self._split_callout_content(block.get("blocks"))
        inner = self._render_blocks(safe_blocks)
        title_html = f"<strong>{self._escape_html(title)}</strong>" if title else ""
        callout_html = f'<div class="callout tone-{tone}">{title_html}{inner}</div>'
        trailing_html = self._render_blocks(trailing_blocks) if trailing_blocks else ""
        return callout_html + trailing_html

    def _split_callout_content(
        self, blocks: List[Dict[str, Any]] | None
    ) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
        """限定callout内部仅包含轻量内容,其余块剥离到外层"""
        if not blocks:
            return [], []
        safe: List[Dict[str, Any]] = []
        trailing: List[Dict[str, Any]] = []
        for idx, child in enumerate(blocks):
            child_type = child.get("type")
            if child_type == "list":
                sanitized, overflow = self._sanitize_callout_list(child)
                if sanitized:
                    safe.append(sanitized)
                if overflow:
                    trailing.extend(overflow)
                    trailing.extend(copy.deepcopy(blocks[idx + 1 :]))
                    break
            elif child_type in self.CALLOUT_ALLOWED_TYPES:
                safe.append(child)
            else:
                trailing.extend(copy.deepcopy(blocks[idx:]))
                break
        else:
            return safe, []
        return safe, trailing

    def _sanitize_callout_list(
        self, block: Dict[str, Any]
    ) -> tuple[Dict[str, Any] | None, List[Dict[str, Any]]]:
        """当列表项包含结构型block时,将其截断移出callout"""
        items = block.get("items") or []
        if not items:
            return block, []
        sanitized_items: List[List[Dict[str, Any]]] = []
        trailing: List[Dict[str, Any]] = []
        for idx, item in enumerate(items):
            safe, overflow = self._split_callout_content(item)
            if safe:
                sanitized_items.append(safe)
            if overflow:
                trailing.extend(overflow)
                for rest in items[idx + 1 :]:
                    trailing.extend(copy.deepcopy(rest))
                break
        if not sanitized_items:
            return None, trailing
        new_block = copy.deepcopy(block)
        new_block["items"] = sanitized_items
        return new_block, trailing

    def _render_kpi_grid(self, block: Dict[str, Any]) -> str:
        """渲染KPI卡片栅格,包含指标值与涨跌幅"""
        if self._should_skip_overview_kpi(block):
            return ""
        cards = ""
        items = block.get("items", [])
        for item in items:
            delta = item.get("delta")
            delta_tone = item.get("deltaTone") or "neutral"
            delta_html = f'<span class="delta {delta_tone}">{self._escape_html(delta)}</span>' if delta else ""
            cards += f"""
            <div class="kpi-card">
              <div class="kpi-value">{self._escape_html(item.get("value", ""))}<small>{self._escape_html(item.get("unit", ""))}</small></div>
              <div class="kpi-label">{self._escape_html(item.get("label", ""))}</div>
              {delta_html}
            </div>
            """
        count_attr = f' data-kpi-count="{len(items)}"' if items else ""
        return f'<div class="kpi-grid"{count_attr}>{cards}</div>'

    def _merge_dicts(
        self, base: Dict[str, Any] | None, override: Dict[str, Any] | None
    ) -> Dict[str, Any]:
        """
        递归合并两个字典,override覆盖base,均为新副本,避免副作用。
        """
        result = copy.deepcopy(base) if isinstance(base, dict) else {}
        if not isinstance(override, dict):
            return result
        for key, value in override.items():
            if isinstance(value, dict) and isinstance(result.get(key), dict):
                result[key] = self._merge_dicts(result[key], value)
            else:
                result[key] = copy.deepcopy(value)
        return result

    def _looks_like_chart_dataset(self, candidate: Any) -> bool:
        """启发式判断对象是否包含Chart.js常见的labels/datasets结构"""
        if not isinstance(candidate, dict):
            return False
        labels = candidate.get("labels")
        datasets = candidate.get("datasets")
        return isinstance(labels, list) or isinstance(datasets, list)

    def _coerce_chart_data_structure(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        兼容LLM输出的Chart.js完整配置(含type/data/options)。
        若data中嵌套一个真正的labels/datasets结构,则提取并返回该结构。
        """
        if not isinstance(data, dict):
            return {}
        if self._looks_like_chart_dataset(data):
            return data
        for key in ("data", "chartData", "payload"):
            nested = data.get(key)
            if self._looks_like_chart_dataset(nested):
                return copy.deepcopy(nested)
        return data

    def _prepare_widget_payload(
        self, block: Dict[str, Any]
    ) -> tuple[Dict[str, Any], Dict[str, Any]]:
        """
        预处理widget数据,兼容部分block将Chart.js配置写入data字段的情况。

        返回:
            tuple(props, data): 归一化后的props与chart数据
        """
        props = copy.deepcopy(block.get("props") or {})
        raw_data = block.get("data")
        data_copy = copy.deepcopy(raw_data) if isinstance(raw_data, dict) else raw_data
        widget_type = block.get("widgetType") or ""
        chart_like = isinstance(widget_type, str) and widget_type.startswith("chart.js")

        if chart_like and isinstance(data_copy, dict):
            inline_options = data_copy.pop("options", None)
            inline_type = data_copy.pop("type", None)
            normalized_data = self._coerce_chart_data_structure(data_copy)
            if isinstance(inline_options, dict):
                props["options"] = self._merge_dicts(props.get("options"), inline_options)
            if isinstance(inline_type, str) and inline_type and not props.get("type"):
                props["type"] = inline_type
        elif isinstance(data_copy, dict):
            normalized_data = data_copy
        else:
            normalized_data = {}

        return props, normalized_data

    @staticmethod
    def _is_chart_data_empty(data: Dict[str, Any] | None) -> bool:
        """检查图表数据是否为空或缺少有效datasets"""
        if not isinstance(data, dict):
            return True

        datasets = data.get("datasets")
        if not isinstance(datasets, list) or len(datasets) == 0:
            return True

        for ds in datasets:
            if not isinstance(ds, dict):
                continue
            series = ds.get("data")
            if isinstance(series, list) and len(series) > 0:
                return False

        return True

    def _chart_cache_key(self, block: Dict[str, Any]) -> str:
        """使用修复器的缓存算法生成稳定的key,便于跨阶段共享结果"""
        if hasattr(self, "chart_repairer") and block:
            try:
                return self.chart_repairer.build_cache_key(block)
            except Exception:
                pass
        return str(id(block))

    def _note_chart_failure(self, cache_key: str, reason: str) -> None:
        """记录修复失败原因,后续渲染直接使用占位提示"""
        if not cache_key:
            return
        if not reason:
            reason = "LLM返回的图表信息格式有误,无法正常显示"
        self._chart_failure_notes[cache_key] = reason

    def _record_chart_failure_stat(self, cache_key: str | None = None) -> None:
        """确保失败计数只统计一次"""
        if cache_key and cache_key in self._chart_failure_recorded:
            return
        self.chart_validation_stats['failed'] += 1
        if cache_key:
            self._chart_failure_recorded.add(cache_key)

    def _format_chart_error_reason(
        self,
        validation_result: ValidationResult | None = None,
        fallback_reason: str | None = None
    ) -> str:
        """拼接友好的失败提示"""
        base = "LLM返回的图表信息格式有误,已尝试本地与多模型修复但仍无法正常显示。"
        detail = None
        if validation_result:
            if validation_result.errors:
                detail = validation_result.errors[0]
            elif validation_result.warnings:
                detail = validation_result.warnings[0]
        if not detail and fallback_reason:
            detail = fallback_reason
        if detail:
            text = f"{base} 提示:{detail}"
            return text[:180] + ("..." if len(text) > 180 else "")
        return base

    def _render_chart_error_placeholder(
        self,
        title: str | None,
        reason: str,
        widget_id: str | None = None
    ) -> str:
        """输出图表失败时的简洁占位提示,避免破坏HTML/PDF布局"""
        safe_title = self._escape_html(title or "图表未能展示")
        safe_reason = self._escape_html(reason)
        widget_attr = f' data-widget-id="{self._escape_attr(widget_id)}"' if widget_id else ""
        return f"""
        <div class="chart-card chart-card--error"{widget_attr}>
          <div class="chart-error">
            <div class="chart-error__icon">!</div>
            <div class="chart-error__body">
              <div class="chart-error__title">{safe_title}</div>
              <p class="chart-error__desc">{safe_reason}</p>
            </div>
          </div>
        </div>
        """

    def _has_chart_failure(self, block: Dict[str, Any]) -> tuple[bool, str | None]:
        """检查是否已有修复失败记录"""
        cache_key = self._chart_cache_key(block)
        if block.get("_chart_renderable") is False:
            return True, block.get("_chart_error_reason")
        if cache_key in self._chart_failure_notes:
            return True, self._chart_failure_notes.get(cache_key)
        return False, None

    def _normalize_chart_block(
        self,
        block: Dict[str, Any],
        chapter_context: Dict[str, Any] | None = None,
    ) -> None:
        """
        补全图表block中的缺失字段(如scales、datasets),提升容错性。

        - 将错误挂在block顶层的scales合并进props.options。
        - 当data缺失或datasets为空时,尝试使用章节级的data作为兜底。
        """

        if not isinstance(block, dict):
            return

        if block.get("type") != "widget":
            return

        widget_type = block.get("widgetType", "")
        if not (isinstance(widget_type, str) and widget_type.startswith("chart.js")):
            return

        # 确保props存在
        props = block.get("props")
        if not isinstance(props, dict):
            block["props"] = {}
            props = block["props"]

        # 将顶层scales合并进options,避免配置丢失
        scales = block.get("scales")
        if isinstance(scales, dict):
            options = props.get("options") if isinstance(props.get("options"), dict) else {}
            props["options"] = self._merge_dicts(options, {"scales": scales})

        # 确保data存在
        data = block.get("data")
        if not isinstance(data, dict):
            data = {}
            block["data"] = data

        # 如果datasets为空,尝试使用章节级data填充
        if chapter_context and self._is_chart_data_empty(data):
            chapter_data = chapter_context.get("data") if isinstance(chapter_context, dict) else None
            if isinstance(chapter_data, dict):
                fallback_ds = chapter_data.get("datasets")
                if isinstance(fallback_ds, list) and len(fallback_ds) > 0:
                    merged_data = copy.deepcopy(data)
                    merged_data["datasets"] = copy.deepcopy(fallback_ds)

                    if not merged_data.get("labels") and isinstance(chapter_data.get("labels"), list):
                        merged_data["labels"] = copy.deepcopy(chapter_data["labels"])

                    block["data"] = merged_data

        # 若仍缺少labels且数据点包含x值,自动生成便于fallback和坐标刻度
        data_ref = block.get("data")
        if isinstance(data_ref, dict) and not data_ref.get("labels"):
            datasets_ref = data_ref.get("datasets")
            if isinstance(datasets_ref, list) and datasets_ref:
                first_ds = datasets_ref[0]
                ds_data = first_ds.get("data") if isinstance(first_ds, dict) else None
                if isinstance(ds_data, list):
                    labels_from_data = []
                    for idx, point in enumerate(ds_data):
                        if isinstance(point, dict):
                            label_text = point.get("x") or point.get("label") or f"点{idx + 1}"
                        else:
                            label_text = f"点{idx + 1}"
                        labels_from_data.append(str(label_text))

                    if labels_from_data:
                        data_ref["labels"] = labels_from_data

    def _render_widget(self, block: Dict[str, Any]) -> str:
        """
        渲染Chart.js等交互组件的占位容器,并记录配置JSON。

        在渲染前进行图表验证和修复:
        1. 验证图表数据格式
        2. 如果无效,尝试本地修复
        3. 如果本地修复失败,尝试API修复
        4. 如果所有修复都失败,输出提示占位并跳过再次修复

        参数:
            block: widget类型的block,包含widgetId/props/data。

        返回:
            str: 含canvas与配置脚本的HTML。
        """
        # 先在block层面做一次容错补全(scales、章节级数据等)
        self._normalize_chart_block(block, getattr(self, "_current_chapter", None))

        # 统计
        widget_type = block.get('widgetType', '')
        is_chart = isinstance(widget_type, str) and widget_type.startswith('chart.js')
        is_wordcloud = isinstance(widget_type, str) and 'wordcloud' in widget_type.lower()
        widget_id = block.get('widgetId')
        cache_key = self._chart_cache_key(block) if is_chart else ""
        props_snapshot = block.get("props") if isinstance(block.get("props"), dict) else {}
        display_title = props_snapshot.get("title") or block.get("title") or widget_id or "图表"

        if is_chart:
            self.chart_validation_stats['total'] += 1

            # 词云使用专用渲染逻辑,不按Chart.js规则验证,直接跳过防止误判
            if is_wordcloud:
                self.chart_validation_stats['valid'] += 1
            else:
                # 如果此前已记录失败,直接使用占位提示,避免重复修复
                has_failed, cached_reason = self._has_chart_failure(block)
                if has_failed:
                    self._record_chart_failure_stat(cache_key)
                    reason = cached_reason or "LLM返回的图表信息格式有误,无法正常显示"
                    return self._render_chart_error_placeholder(display_title, reason, widget_id)

                # 验证图表数据
                validation_result = self.chart_validator.validate(block)

                if not validation_result.is_valid:
                    logger.warning(
                        f"图表 {block.get('widgetId', 'unknown')} 验证失败: {validation_result.errors}"
                    )

                    # 尝试修复
                    repair_result = self.chart_repairer.repair(block, validation_result)

                    if repair_result.success and repair_result.repaired_block:
                        # 修复成功,使用修复后的数据
                        block = repair_result.repaired_block
                        logger.info(
                            f"图表 {block.get('widgetId', 'unknown')} 修复成功 "
                            f"(方法: {repair_result.method}): {repair_result.changes}"
                        )

                        # 更新统计
                        if repair_result.method == 'local':
                            self.chart_validation_stats['repaired_locally'] += 1
                        elif repair_result.method == 'api':
                            self.chart_validation_stats['repaired_api'] += 1
                    else:
                        # 修复失败,记录失败并输出占位提示
                        fail_reason = self._format_chart_error_reason(validation_result)
                        block["_chart_renderable"] = False
                        block["_chart_error_reason"] = fail_reason
                        self._note_chart_failure(cache_key, fail_reason)
                        self._record_chart_failure_stat(cache_key)
                        logger.warning(
                            f"图表 {block.get('widgetId', 'unknown')} 修复失败,已跳过渲染: {fail_reason}"
                        )
                        return self._render_chart_error_placeholder(display_title, fail_reason, widget_id)
                else:
                    # 验证通过
                    self.chart_validation_stats['valid'] += 1
                    if validation_result.warnings:
                        logger.info(
                            f"图表 {block.get('widgetId', 'unknown')} 验证通过,"
                            f"但有警告: {validation_result.warnings}"
                        )

        # 渲染图表HTML
        self.chart_counter += 1
        canvas_id = f"chart-{self.chart_counter}"
        config_id = f"chart-config-{self.chart_counter}"

        props, normalized_data = self._prepare_widget_payload(block)
        payload = {
            "widgetId": block.get("widgetId"),
            "widgetType": block.get("widgetType"),
            "props": props,
            "data": normalized_data,
            "dataRef": block.get("dataRef"),
        }
        config_json = json.dumps(payload, ensure_ascii=False).replace("</", "<\\/")
        self.widget_scripts.append(
            f'<script type="application/json" id="{config_id}">{config_json}</script>'
        )

        title = props.get("title")
        title_html = f'<div class="chart-title">{self._escape_html(title)}</div>' if title else ""
        fallback_html = (
            self._render_wordcloud_fallback(props, block.get("widgetId"), block.get("data"))
            if is_wordcloud
            else self._render_widget_fallback(normalized_data, block.get("widgetId"))
        )
        return f"""
        <div class="chart-card{' wordcloud-card' if is_wordcloud else ''}">
          {title_html}
          <div class="chart-container">
            <canvas id="{canvas_id}" data-config-id="{config_id}"></canvas>
          </div>
          {fallback_html}
        </div>
        """

    def _render_widget_fallback(self, data: Dict[str, Any], widget_id: str | None = None) -> str:
        """渲染图表数据的文本兜底视图,避免Chart.js加载失败时出现空白"""
        if not isinstance(data, dict):
            return ""
        labels = data.get("labels") or []
        datasets = data.get("datasets") or []
        if not labels or not datasets:
            return ""

        widget_attr = f' data-widget-id="{self._escape_attr(widget_id)}"' if widget_id else ""
        header_cells = "".join(
            f"<th>{self._escape_html(ds.get('label') or f'系列{idx + 1}')}</th>"
            for idx, ds in enumerate(datasets)
        )
        body_rows = ""
        for idx, label in enumerate(labels):
            row_cells = [f"<td>{self._escape_html(label)}</td>"]
            for ds in datasets:
                series = ds.get("data") or []
                value = series[idx] if idx < len(series) else ""
                row_cells.append(f"<td>{self._escape_html(value)}</td>")
            body_rows += f"<tr>{''.join(row_cells)}</tr>"
        table_html = f"""
        <div class="chart-fallback" data-prebuilt="true"{widget_attr}>
          <table>
            <thead>
              <tr><th>类别</th>{header_cells}</tr>
            </thead>
            <tbody>
              {body_rows}
            </tbody>
          </table>
        </div>
        """
        return table_html

    def _render_wordcloud_fallback(
        self,
        props: Dict[str, Any] | None,
        widget_id: str | None = None,
        block_data: Any | None = None,
    ) -> str:
        """为词云提供表格兜底,避免WordCloud渲染失败后页面空白"""
        def _collect_items(raw: Any) -> list[dict]:
            """将多种词云输入格式(数组/对象/元组/纯文本)规整为统一的词条列表"""
            collected: list[dict] = []
            skip_keys = {"items", "data", "words", "labels", "datasets", "sourceData"}
            if isinstance(raw, list):
                for item in raw:
                    if isinstance(item, dict):
                        text = item.get("word") or item.get("text") or item.get("label")
                        weight = item.get("weight")
                        category = item.get("category") or ""
                        if text:
                            collected.append({"word": str(text), "weight": weight, "category": str(category)})
                        # 若嵌套了 items/words/data 列表,递归提取
                        for nested_key in ("items", "words", "data"):
                            nested = item.get(nested_key)
                            if isinstance(nested, list):
                                collected.extend(_collect_items(nested))
                    elif isinstance(item, (list, tuple)) and item:
                        text = item[0]
                        weight = item[1] if len(item) > 1 else None
                        category = item[2] if len(item) > 2 else ""
                        if text:
                            collected.append({"word": str(text), "weight": weight, "category": str(category)})
                    elif isinstance(item, str):
                        collected.append({"word": item, "weight": 1.0, "category": ""})
            elif isinstance(raw, dict):
                # 若包含 items/words/data 列表,优先递归提取,不把键名当词
                handled = False
                for nested_key in ("items", "words", "data"):
                    nested = raw.get(nested_key)
                    if isinstance(nested, list):
                        collected.extend(_collect_items(nested))
                        handled = True
                if handled:
                    return collected

                # 非Chart结构且不包含skip_keys时,把key/value当作词云条目
                if not {"labels", "datasets"}.intersection(raw.keys()):
                    for text, weight in raw.items():
                        if text in skip_keys:
                            continue
                        collected.append({"word": str(text), "weight": weight, "category": ""})
            return collected

        words: list[dict] = []
        seen: set[str] = set()
        candidates = []
        if isinstance(props, dict):
            # 仅接受明确的词条数组字段,避免将嵌套items误当作词条
            if "data" in props and isinstance(props.get("data"), list):
                candidates.append(props["data"])
            if "words" in props and isinstance(props.get("words"), list):
                candidates.append(props["words"])
            if "items" in props and isinstance(props.get("items"), list):
                candidates.append(props["items"])
        candidates.append((props or {}).get("sourceData"))

        # 允许使用block.data兜底,避免缺失props时出现空白
        if block_data is not None:
            if isinstance(block_data, dict) and "items" in block_data and isinstance(block_data.get("items"), list):
                candidates.append(block_data["items"])
            else:
                candidates.append(block_data)

        for raw in candidates:
            for item in _collect_items(raw):
                key = f"{item['word']}::{item.get('category','')}"
                if key in seen:
                    continue
                seen.add(key)
                words.append(item)

        if not words:
            return ""

        def _format_weight(value: Any) -> str:
            """统一格式化权重,支持百分比/数值与字符串回退"""
            if isinstance(value, (int, float)) and not isinstance(value, bool):
                if 0 <= value <= 1.5:
                    return f"{value * 100:.1f}%"
                return f"{value:.2f}".rstrip("0").rstrip(".")
            return str(value)

        widget_attr = f' data-widget-id="{self._escape_attr(widget_id)}"' if widget_id else ""
        rows = "".join(
            f"<tr><td>{self._escape_html(item['word'])}</td>"
            f"<td>{self._escape_html(_format_weight(item['weight']))}</td>"
            f"<td>{self._escape_html(item['category'] or '-')}</td></tr>"
            for item in words
        )
        return f"""
        <div class="chart-fallback" data-prebuilt="true"{widget_attr}>
          <table>
            <thead>
              <tr><th>关键词</th><th>权重</th><th>类别</th></tr>
            </thead>
            <tbody>
              {rows}
            </tbody>
          </table>
        </div>
        """

    def _log_chart_validation_stats(self):
        """输出图表验证统计信息"""
        stats = self.chart_validation_stats
        if stats['total'] == 0:
            return

        logger.info("=" * 60)
        logger.info("图表验证统计")
        logger.info("=" * 60)
        logger.info(f"总图表数量: {stats['total']}")
        logger.info(f"  ✓ 验证通过: {stats['valid']} ({stats['valid']/stats['total']*100:.1f}%)")

        if stats['repaired_locally'] > 0:
            logger.info(
                f"  ⚠ 本地修复: {stats['repaired_locally']} "
                f"({stats['repaired_locally']/stats['total']*100:.1f}%)"
            )

        if stats['repaired_api'] > 0:
            logger.info(
                f"  ⚠ API修复: {stats['repaired_api']} "
                f"({stats['repaired_api']/stats['total']*100:.1f}%)"
            )

        if stats['failed'] > 0:
            logger.warning(
                f"  ✗ 修复失败: {stats['failed']} "
                f"({stats['failed']/stats['total']*100:.1f}%) - "
                f"这些图表将展示简洁占位提示"
            )

        logger.info("=" * 60)

    # ====== 前置信息防护 ======

    def _kpi_signature_from_items(self, items: Any) -> tuple | None:
        """将KPI数组转换为可比较的签名"""
        if not isinstance(items, list):
            return None
        normalized = []
        for raw in items:
            normalized_item = self._normalize_kpi_item(raw)
            if normalized_item:
                normalized.append(normalized_item)
        return tuple(normalized) if normalized else None

    def _normalize_kpi_item(self, item: Any) -> tuple[str, str, str, str, str] | None:
        """
        将单条KPI记录规整为可对比的签名。

        参数:
            item: KPI数组中的原始字典,可能缺失字段或类型混杂。

        返回:
            tuple | None: (label, value, unit, delta, tone) 的五元组;若输入非法则为None。
        """
        if not isinstance(item, dict):
            return None

        def normalize(value: Any) -> str:
            """统一各类值的表现形式,便于生成稳定签名"""
            if value is None:
                return ""
            if isinstance(value, (int, float)):
                return str(value)
            return str(value).strip()

        label = normalize(item.get("label"))
        value = normalize(item.get("value"))
        unit = normalize(item.get("unit"))
        delta = normalize(item.get("delta"))
        tone = normalize(item.get("deltaTone") or item.get("tone"))
        return label, value, unit, delta, tone

    def _should_skip_overview_kpi(self, block: Dict[str, Any]) -> bool:
        """若KPI内容与封面一致,则判定为重复总览"""
        if not self.hero_kpi_signature:
            return False
        block_signature = self._kpi_signature_from_items(block.get("items"))
        if not block_signature:
            return False
        return block_signature == self.hero_kpi_signature

    # ====== 行内渲染 ======

    def _normalize_inline_payload(self, run: Dict[str, Any]) -> tuple[str, List[Dict[str, Any]]]:
        """将嵌套inline node展平成基础文本与marks"""
        if not isinstance(run, dict):
            return ("" if run is None else str(run)), []

        marks = list(run.get("marks") or [])
        text_value: Any = run.get("text", "")
        seen: set[int] = set()

        while isinstance(text_value, dict):
            obj_id = id(text_value)
            if obj_id in seen:
                text_value = ""
                break
            seen.add(obj_id)
            nested_marks = text_value.get("marks")
            if nested_marks:
                marks.extend(nested_marks)
            if "text" in text_value:
                text_value = text_value.get("text")
            else:
                text_value = json.dumps(text_value, ensure_ascii=False)
                break

        if text_value is None:
            text_value = ""
        elif isinstance(text_value, (int, float)):
            text_value = str(text_value)
        elif not isinstance(text_value, str):
            try:
                text_value = json.dumps(text_value, ensure_ascii=False)
            except TypeError:
                text_value = str(text_value)

        if isinstance(text_value, str):
            stripped = text_value.strip()
            if stripped.startswith("{") and stripped.endswith("}"):
                payload = None
                try:
                    payload = json.loads(stripped)
                except json.JSONDecodeError:
                    try:
                        payload = ast.literal_eval(stripped)
                    except (ValueError, SyntaxError):
                        payload = None
                if isinstance(payload, dict):
                    sentinel_keys = {"xrefs", "widgets", "footnotes", "errors", "metadata"}
                    if set(payload.keys()).issubset(sentinel_keys):
                        text_value = ""
                    else:
                        inline_payload = self._coerce_inline_payload(payload)
                        if inline_payload:
                            nested_text = inline_payload.get("text")
                            if nested_text is not None:
                                text_value = nested_text
                            nested_marks = inline_payload.get("marks")
                            if isinstance(nested_marks, list):
                                marks.extend(nested_marks)
                        elif any(key in payload for key in self.INLINE_ARTIFACT_KEYS):
                            text_value = ""

        return text_value, marks

    @staticmethod
    def _normalize_latex_string(raw: Any) -> str:
        """去除外层数学定界符,兼容 $...$、$$...$$、\\(\\)、\\[\\] 等格式"""
        if not isinstance(raw, str):
            return ""
        latex = raw.strip()
        patterns = [
            r'^\$\$(.*)\$\$$',
            r'^\$(.*)\$$',
            r'^\\\[(.*)\\\]$',
            r'^\\\((.*)\\\)$',
        ]
        for pat in patterns:
            m = re.match(pat, latex, re.DOTALL)
            if m:
                latex = m.group(1).strip()
                break
        return latex

    def _render_text_with_inline_math(
        self,
        text: Any,
        math_id: str | list | None = None,
        allow_display_block: bool = False
    ) -> str | None:
        """
        识别纯文本中的数学定界符并渲染为math-inline/math-block,提升兼容性。

        - 支持 $...$、$$...$$、\\(\\)、\\[\\]。
        - 若未检测到公式,返回None。
        """
        if not isinstance(text, str) or not text:
            return None

        pattern = re.compile(r'(\$\$(.+?)\$\$|\$(.+?)\$|\\\((.+?)\\\)|\\\[(.+?)\\\])', re.S)
        matches = list(pattern.finditer(text))
        if not matches:
            return None

        cursor = 0
        parts: List[str] = []
        id_iter = iter(math_id) if isinstance(math_id, list) else None

        for idx, m in enumerate(matches, start=1):
            start, end = m.span()
            prefix = text[cursor:start]
            raw = next(g for g in m.groups()[1:] if g is not None)
            latex = self._normalize_latex_string(raw)
            # 若已有math_id,直接使用,避免与SVG注入ID不一致;否则按局部序号生成
            if id_iter:
                mid = next(id_iter, f"auto-math-{idx}")
            else:
                mid = math_id or f"auto-math-{idx}"
            id_attr = f' data-math-id="{self._escape_attr(mid)}"'
            is_display = m.group(1).startswith('$$') or m.group(1).startswith('\\[')
            is_standalone = (
                len(matches) == 1 and
                not text[:start].strip() and
                not text[end:].strip()
            )
            use_block = allow_display_block and is_display and is_standalone
            if use_block:
                # 独立display公式,跳过两侧空白,直接渲染块级
                parts.append(f'<div class="math-block"{id_attr}>$$ {self._escape_html(latex)} $$</div>')
                cursor = len(text)
                break
            else:
                if prefix:
                    parts.append(self._escape_html(prefix))
                parts.append(f'<span class="math-inline"{id_attr}>\\( {self._escape_html(latex)} \\)</span>')
            cursor = end

        if cursor < len(text):
            parts.append(self._escape_html(text[cursor:]))
        return "".join(parts)

    @staticmethod
    def _coerce_inline_payload(payload: Dict[str, Any]) -> Dict[str, Any] | None:
        """尽力将字符串里的内联节点恢复为dict,修复渲染遗漏"""
        if not isinstance(payload, dict):
            return None
        inline_type = payload.get("type")
        if inline_type and inline_type not in {"inline", "text"}:
            return None
        if "text" not in payload and "marks" not in payload:
            return None
        return payload

    def _render_inline(self, run: Dict[str, Any]) -> str:
        """
        渲染单个inline run,支持多种marks叠加。

        参数:
            run: 含 text 与 marks 的内联节点。

        返回:
            str: 已包裹标签/样式的HTML片段。
        """
        text_value, marks = self._normalize_inline_payload(run)
        math_mark = next((mark for mark in marks if mark.get("type") == "math"), None)
        if math_mark:
            latex = self._normalize_latex_string(math_mark.get("value"))
            if not isinstance(latex, str) or not latex.strip():
                latex = self._normalize_latex_string(text_value)
            math_id = self._escape_attr(run.get("mathId", "")) if run.get("mathId") else ""
            id_attr = f' data-math-id="{math_id}"' if math_id else ""
            return f'<span class="math-inline"{id_attr}>\\( {self._escape_html(latex)} \\)</span>'

        # 尝试从纯文本中提取数学公式(即便没有math mark)
        math_id_hint = run.get("mathIds") or run.get("mathId")
        mathified = self._render_text_with_inline_math(text_value, math_id_hint)
        if mathified is not None:
            return mathified

        text = self._escape_html(text_value)
        styles: List[str] = []
        prefix: List[str] = []
        suffix: List[str] = []
        for mark in marks:
            mark_type = mark.get("type")
            if mark_type == "bold":
                prefix.append("<strong>")
                suffix.insert(0, "</strong>")
            elif mark_type == "italic":
                prefix.append("<em>")
                suffix.insert(0, "</em>")
            elif mark_type == "code":
                prefix.append("<code>")
                suffix.insert(0, "</code>")
            elif mark_type == "highlight":
                prefix.append("<mark>")
                suffix.insert(0, "</mark>")
            elif mark_type == "link":
                href_raw = mark.get("href")
                if href_raw and href_raw != "#":
                    href = self._escape_attr(href_raw)
                    title = self._escape_attr(mark.get("title") or "")
                    prefix.append(f'<a href="{href}" title="{title}" target="_blank" rel="noopener">')
                    suffix.insert(0, "</a>")
                else:
                    prefix.append('<span class="broken-link">')
                    suffix.insert(0, "</span>")
            elif mark_type == "color":
                value = mark.get("value")
                if value:
                    styles.append(f"color: {value}")
            elif mark_type == "font":
                family = mark.get("family")
                size = mark.get("size")
                weight = mark.get("weight")
                if family:
                    styles.append(f"font-family: {family}")
                if size:
                    styles.append(f"font-size: {size}")
                if weight:
                    styles.append(f"font-weight: {weight}")
            elif mark_type == "underline":
                styles.append("text-decoration: underline")
            elif mark_type == "strike":
                styles.append("text-decoration: line-through")
            elif mark_type == "subscript":
                prefix.append("<sub>")
                suffix.insert(0, "</sub>")
            elif mark_type == "superscript":
                prefix.append("<sup>")
                suffix.insert(0, "</sup>")

        if styles:
            style_attr = "; ".join(styles)
            prefix.insert(0, f'<span style="{style_attr}">')
            suffix.append("</span>")

        if not marks and "**" in (run.get("text") or ""):
            return self._render_markdown_bold_fallback(run.get("text", ""))

        return "".join(prefix) + text + "".join(suffix)

    def _render_markdown_bold_fallback(self, text: str) -> str:
        """在LLM未使用marks时兜底转换**粗体**"""
        if not text:
            return ""
        result: List[str] = []
        cursor = 0
        while True:
            start = text.find("**", cursor)
            if start == -1:
                result.append(html.escape(text[cursor:]))
                break
            end = text.find("**", start + 2)
            if end == -1:
                result.append(html.escape(text[cursor:]))
                break
            result.append(html.escape(text[cursor:start]))
            bold_content = html.escape(text[start + 2:end])
            result.append(f"<strong>{bold_content}</strong>")
            cursor = end + 2
        return "".join(result)

    # ====== 文本 / 安全工具 ======

    def _clean_text_from_json_artifacts(self, text: Any) -> str:
        """
        清理文本中的JSON片段和伪造的结构标记。

        LLM有时会在文本字段中混入未完成的JSON片段,如:
        "描述文本,{ \"chapterId\": \"S3" 或 "描述文本,{ \"level\": 2"

        此方法会:
        1. 移除不完整的JSON对象(以 { 开头但未正确闭合的)
        2. 移除不完整的JSON数组(以 [ 开头但未正确闭合的)
        3. 移除孤立的JSON键值对片段

        参数:
            text: 可能包含JSON片段的文本

        返回:
            str: 清理后的纯文本
        """
        if not text:
            return ""

        text_str = self._safe_text(text)

        # 模式1: 移除以逗号+空白+{开头的不完整JSON对象
        # 例如: "文本,{ \"key\": \"value\"" 或 "文本,{\\n  \"key\""
        text_str = re.sub(r',\s*\{[^}]*$', '', text_str)

        # 模式2: 移除以逗号+空白+[开头的不完整JSON数组
        text_str = re.sub(r',\s*\[[^\]]*$', '', text_str)

        # 模式3: 移除孤立的 { 加上后续内容(如果没有匹配的 })
        # 检查是否有未闭合的 {
        open_brace_pos = text_str.rfind('{')
        if open_brace_pos != -1:
            close_brace_pos = text_str.rfind('}')
            if close_brace_pos < open_brace_pos:
                # { 在 } 后面或没有 },说明是未闭合的
                # 截断到 { 之前
                text_str = text_str[:open_brace_pos].rstrip(',,、 \t\n')

        # 模式4: 类似处理 [
        open_bracket_pos = text_str.rfind('[')
        if open_bracket_pos != -1:
            close_bracket_pos = text_str.rfind(']')
            if close_bracket_pos < open_bracket_pos:
                # [ 在 ] 后面或没有 ],说明是未闭合的
                text_str = text_str[:open_bracket_pos].rstrip(',,、 \t\n')

        # 模式5: 移除看起来像JSON键值对的片段,如 "chapterId": "S3
        # 这种情况通常出现在上面的模式之后
        text_str = re.sub(r',?\s*"[^"]+"\s*:\s*"[^"]*$', '', text_str)
        text_str = re.sub(r',?\s*"[^"]+"\s*:\s*[^,}\]]*$', '', text_str)

        # 清理末尾的逗号和空白
        text_str = text_str.rstrip(',,、 \t\n')

        return text_str.strip()

    def _safe_text(self, value: Any) -> str:
        """将任意值安全转换为字符串,None与复杂对象容错"""
        if value is None:
            return ""
        if isinstance(value, str):
            return value
        if isinstance(value, (int, float, bool)):
            return str(value)
        try:
            return json.dumps(value, ensure_ascii=False)
        except (TypeError, ValueError):
            return str(value)

    def _escape_html(self, value: Any) -> str:
        """HTML文本上下文的转义"""
        return html.escape(self._safe_text(value), quote=False)

    def _escape_attr(self, value: Any) -> str:
        """HTML属性上下文转义并去掉危险换行"""
        escaped = html.escape(self._safe_text(value), quote=True)
        return escaped.replace("\n", " ").replace("\r", " ")

    # ====== CSS / JS(样式与脚本) ======

    def _build_css(self, tokens: Dict[str, Any]) -> str:
        """根据主题token拼接整页CSS,包括响应式与打印样式"""
        # 安全获取各个配置项,确保都是字典类型
        colors_raw = tokens.get("colors")
        colors = colors_raw if isinstance(colors_raw, dict) else {}

        typography_raw = tokens.get("typography")
        typography = typography_raw if isinstance(typography_raw, dict) else {}

        # 安全获取fonts,确保是字典类型
        fonts_raw = tokens.get("fonts") or typography.get("fonts")
        if isinstance(fonts_raw, dict):
            fonts = fonts_raw
        else:
            # 如果fonts是字符串或None,构造一个字典
            font_family = typography.get("fontFamily")
            if isinstance(font_family, str):
                fonts = {"body": font_family, "heading": font_family}
            else:
                fonts = {}

        spacing_raw = tokens.get("spacing")
        spacing = spacing_raw if isinstance(spacing_raw, dict) else {}

        primary_palette = self._resolve_color_family(
            colors.get("primary"),
            {"main": "#1a365d", "light": "#2d3748", "dark": "#0f1a2d"},
        )
        secondary_palette = self._resolve_color_family(
            colors.get("secondary"),
            {"main": "#e53e3e", "light": "#fc8181", "dark": "#c53030"},
        )
        bg = self._resolve_color_value(
            colors.get("bg") or colors.get("background") or colors.get("surface"),
            "#f8f9fa",
        )
        text_color = self._resolve_color_value(
            colors.get("text") or colors.get("onBackground"),
            "#212529",
        )
        card = self._resolve_color_value(
            colors.get("card") or colors.get("surfaceCard"),
            "#ffffff",
        )
        border = self._resolve_color_value(
            colors.get("border") or colors.get("divider"),
            "#dee2e6",
        )
        shadow = "rgba(0,0,0,0.08)"
        container_width = spacing.get("container") or spacing.get("containerWidth") or "1200px"
        gutter = spacing.get("gutter") or spacing.get("pagePadding") or "24px"
        body_font = fonts.get("body") or fonts.get("primary") or "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
        heading_font = fonts.get("heading") or fonts.get("primary") or fonts.get("secondary") or body_font

        return f"""
:root {{
  --bg-color: {bg};
  --text-color: {text_color};
  --primary-color: {primary_palette["main"]};
  --primary-color-light: {primary_palette["light"]};
  --primary-color-dark: {primary_palette["dark"]};
  --secondary-color: {secondary_palette["main"]};
  --secondary-color-light: {secondary_palette["light"]};
  --secondary-color-dark: {secondary_palette["dark"]};
  --card-bg: {card};
  --border-color: {border};
  --shadow-color: {shadow};
  --engine-insight-bg: #f4f7ff;
  --engine-insight-border: #dce7ff;
  --engine-insight-text: #1f4b99;
  --engine-media-bg: #fff6ec;
  --engine-media-border: #ffd9b3;
  --engine-media-text: #b65a1a;
  --engine-query-bg: #f1fbf5;
  --engine-query-border: #c7ebd6;
  --engine-query-text: #1d6b3f;
  --engine-quote-shadow: 0 12px 30px rgba(0,0,0,0.04);
  --swot-strength: #1c7f6e;
  --swot-weakness: #c0392b;
  --swot-opportunity: #1f5ab3;
  --swot-threat: #b36b16;
  --swot-on-light: #0f1b2b;
  --swot-on-dark: #f7fbff;
  --swot-text: var(--text-color);
  --swot-muted: rgba(0,0,0,0.58);
  --swot-surface: rgba(255,255,255,0.92);
  --swot-chip-bg: rgba(0,0,0,0.04);
  --swot-tag-border: var(--border-color);
  --swot-card-bg: linear-gradient(135deg, rgba(76,132,255,0.04), rgba(28,127,110,0.06)), var(--card-bg);
  --swot-card-border: var(--border-color);
  --swot-card-shadow: 0 14px 28px var(--shadow-color);
  --swot-card-blur: none;
  --swot-cell-base: linear-gradient(135deg, rgba(255,255,255,0.9), rgba(255,255,255,0.5));
  --swot-cell-border: rgba(0,0,0,0.04);
  --swot-cell-strength-bg: linear-gradient(135deg, rgba(28,127,110,0.07), rgba(255,255,255,0.78)), var(--card-bg);
  --swot-cell-weakness-bg: linear-gradient(135deg, rgba(192,57,43,0.07), rgba(255,255,255,0.78)), var(--card-bg);
  --swot-cell-opportunity-bg: linear-gradient(135deg, rgba(31,90,179,0.07), rgba(255,255,255,0.78)), var(--card-bg);
  --swot-cell-threat-bg: linear-gradient(135deg, rgba(179,107,22,0.07), rgba(255,255,255,0.78)), var(--card-bg);
  --swot-cell-strength-border: rgba(28,127,110,0.35);
  --swot-cell-weakness-border: rgba(192,57,43,0.35);
  --swot-cell-opportunity-border: rgba(31,90,179,0.35);
  --swot-cell-threat-border: rgba(179,107,22,0.35);
  --swot-item-border: rgba(0,0,0,0.05);
}}
.dark-mode {{
  --bg-color: #121212;
  --text-color: #e0e0e0;
  --primary-color: #6ea8fe;
  --primary-color-light: #91caff;
  --primary-color-dark: #1f6feb;
  --secondary-color: #f28b82;
  --secondary-color-light: #f9b4ae;
  --secondary-color-dark: #d9655c;
  --card-bg: #1f1f1f;
  --border-color: #2c2c2c;
  --shadow-color: rgba(0, 0, 0, 0.4);
  --engine-insight-bg: rgba(145, 202, 255, 0.08);
  --engine-insight-border: rgba(145, 202, 255, 0.45);
  --engine-insight-text: #9dc2ff;
  --engine-media-bg: rgba(255, 196, 138, 0.08);
  --engine-media-border: rgba(255, 196, 138, 0.45);
  --engine-media-text: #ffcb9b;
  --engine-query-bg: rgba(141, 215, 165, 0.08);
  --engine-query-border: rgba(141, 215, 165, 0.45);
  --engine-query-text: #a7e2ba;
  --engine-quote-shadow: 0 12px 28px rgba(0, 0, 0, 0.35);
  --swot-strength: #1c7f6e;
  --swot-weakness: #e06754;
  --swot-opportunity: #5a8cff;
  --swot-threat: #d48a2c;
  --swot-on-light: #0f1b2b;
  --swot-on-dark: #e6f0ff;
  --swot-text: #e6f0ff;
  --swot-muted: rgba(230,240,255,0.75);
  --swot-surface: rgba(255,255,255,0.08);
  --swot-chip-bg: rgba(255,255,255,0.14);
  --swot-tag-border: rgba(255,255,255,0.24);
  --swot-card-bg: radial-gradient(140% 140% at 18% 18%, rgba(110,168,254,0.18), transparent 55%), radial-gradient(120% 140% at 82% 0%, rgba(28,127,110,0.16), transparent 52%), linear-gradient(160deg, #0b1424 0%, #0b1f31 52%, #0a1626 100%);
  --swot-card-border: rgba(255,255,255,0.14);
  --swot-card-shadow: 0 24px 60px rgba(0, 0, 0, 0.58);
  --swot-card-blur: blur(12px);
  --swot-cell-base: linear-gradient(135deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02));
  --swot-cell-border: rgba(255,255,255,0.2);
  --swot-cell-strength-bg: linear-gradient(150deg, rgba(28,127,110,0.28), rgba(28,127,110,0.12)), var(--swot-cell-base);
  --swot-cell-weakness-bg: linear-gradient(150deg, rgba(192,57,43,0.32), rgba(192,57,43,0.14)), var(--swot-cell-base);
  --swot-cell-opportunity-bg: linear-gradient(150deg, rgba(31,90,179,0.28), rgba(31,90,179,0.12)), var(--swot-cell-base);
  --swot-cell-threat-bg: linear-gradient(150deg, rgba(179,107,22,0.32), rgba(179,107,22,0.14)), var(--swot-cell-base);
  --swot-cell-strength-border: rgba(28,127,110,0.65);
  --swot-cell-weakness-border: rgba(192,57,43,0.68);
  --swot-cell-opportunity-border: rgba(31,90,179,0.68);
  --swot-cell-threat-border: rgba(179,107,22,0.68);
  --swot-item-border: rgba(255,255,255,0.14);
}}
* {{ box-sizing: border-box; }}
body {{
  margin: 0;
  font-family: {body_font};
  background: linear-gradient(180deg, rgba(0,0,0,0.04), rgba(0,0,0,0)) fixed, var(--bg-color);
  color: var(--text-color);
  line-height: 1.7;
  min-height: 100vh;
  transition: background-color 0.45s ease, color 0.45s ease;
}}
.report-header, main, .hero-section, .chapter, .chart-card, .callout, .engine-quote, .kpi-card, .toc, .table-wrap {{
  transition: background-color 0.45s ease, color 0.45s ease, border-color 0.45s ease, box-shadow 0.45s ease;
}}
.report-header {{
  position: sticky;
  top: 0;
  z-index: 10;
  background: var(--card-bg);
  padding: 20px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  box-shadow: 0 2px 6px var(--shadow-color);
}}
.tagline {{
  margin: 4px 0 0;
  color: var(--secondary-color);
  font-size: 0.95rem;
}}
.hero-section {{
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  padding: 24px;
  border-radius: 20px;
  background: linear-gradient(135deg, rgba(0,123,255,0.1), rgba(23,162,184,0.1));
  border: 1px solid rgba(0,0,0,0.08);
  margin-bottom: 32px;
}}
.hero-content {{
  flex: 2;
  min-width: 260px;
}}
.hero-side {{
  flex: 1;
  min-width: 220px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 12px;
}}
.hero-kpi {{
  background: var(--card-bg);
  border-radius: 14px;
  padding: 16px;
  box-shadow: 0 6px 16px var(--shadow-color);
}}
.hero-kpi .label {{
  font-size: 0.9rem;
  color: var(--secondary-color);
}}
.hero-kpi .value {{
  font-size: 1.8rem;
  font-weight: 700;
}}
.hero-highlights {{
  list-style: none;
  padding: 0;
  margin: 16px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}}
.hero-highlights li {{
  margin: 0;
}}
.badge {{
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 999px;
  background: rgba(0,0,0,0.05);
  font-size: 0.9rem;
}}
.broken-link {{
  text-decoration: underline dotted;
  color: var(--primary-color);
}}
.hero-actions {{
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}}
.ghost-btn {{
  border: 1px solid var(--primary-color);
  background: transparent;
  color: var(--primary-color);
  border-radius: 999px;
  padding: 8px 16px;
  cursor: pointer;
}}
.hero-summary {{
  font-size: 1.05rem;
  font-weight: 500;
  margin-top: 0;
}}
.llm-error-block {{
  border: 1px dashed var(--secondary-color);
  border-radius: 12px;
  padding: 12px;
  margin: 12px 0;
  background: rgba(229,62,62,0.06);
  position: relative;
}}
.llm-error-block.importance-critical {{
  border-color: var(--secondary-color-dark);
  background: rgba(229,62,62,0.12);
}}
.llm-error-block::after {{
  content: attr(data-raw);
  white-space: pre-wrap;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 100%;
  max-height: 240px;
  overflow: auto;
  background: rgba(0,0,0,0.85);
  color: #fff;
  font-size: 0.85rem;
  padding: 12px;
  border-radius: 10px;
  margin-bottom: 8px;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s ease;
  z-index: 20;
}}
.llm-error-block:hover::after {{
  opacity: 1;
}}
.report-header h1 {{
  margin: 0;
  font-size: 1.6rem;
  color: var(--primary-color);
}}
.report-header .subtitle {{
  margin: 4px 0 0;
  color: var(--secondary-color);
}}
.header-actions {{
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}}
theme-button {{
  display: inline-block;
  vertical-align: middle;
}}
.cover {{
  text-align: center;
  margin: 20px 0 40px;
}}
.cover h1 {{
  font-size: 2.4rem;
  margin: 0.4em 0;
}}
.cover-hint {{
  letter-spacing: 0.4em;
  color: var(--secondary-color);
  font-size: 0.95rem;
}}
.cover-subtitle {{
  color: var(--secondary-color);
  margin: 0;
}}
.action-btn {{
  border: none;
  border-radius: 6px;
  background: var(--primary-color);
  color: #fff;
  padding: 10px 16px;
  cursor: pointer;
  font-size: 0.95rem;
  transition: transform 0.2s ease;
  min-width: 160px;
  white-space: nowrap;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}}
.action-btn:hover {{
  transform: translateY(-1px);
}}
body.exporting {{
  cursor: progress;
}}
.export-overlay {{
  position: fixed;
  inset: 0;
  background: rgba(3, 9, 26, 0.55);
  backdrop-filter: blur(2px);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.3s ease;
  z-index: 999;
}}
.export-overlay.active {{
  opacity: 1;
  pointer-events: all;
}}
.export-dialog {{
  background: rgba(12, 19, 38, 0.92);
  padding: 24px 32px;
  border-radius: 18px;
  color: #fff;
  text-align: center;
  min-width: 280px;
  box-shadow: 0 16px 40px rgba(0,0,0,0.45);
}}
.export-spinner {{
  width: 48px;
  height: 48px;
  border-radius: 50%;
  border: 3px solid rgba(255,255,255,0.2);
  border-top-color: var(--secondary-color);
  margin: 0 auto 16px;
  animation: export-spin 1s linear infinite;
}}
.export-status {{
  margin: 0;
  font-size: 1rem;
}}
.exporting *,
.exporting *::before,
.exporting *::after {{
  animation: none !important;
  transition: none !important;
}}
.export-progress {{
  width: 220px;
  height: 6px;
  background: rgba(255,255,255,0.25);
  border-radius: 999px;
  overflow: hidden;
  margin: 20px auto 0;
  position: relative;
}}
.export-progress-bar {{
  position: absolute;
  top: 0;
  bottom: 0;
  width: 45%;
  border-radius: inherit;
  background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
  animation: export-progress 1.4s ease-in-out infinite;
}}
@keyframes export-spin {{
  from {{ transform: rotate(0deg); }}
  to {{ transform: rotate(360deg); }}
}}
@keyframes export-progress {{
  0% {{ left: -45%; }}
  50% {{ left: 20%; }}
  100% {{ left: 110%; }}
}}
main {{
  max-width: {container_width};
  margin: 40px auto;
  padding: {gutter};
  background: var(--card-bg);
  border-radius: 16px;
  box-shadow: 0 10px 30px var(--shadow-color);
}}
h1, h2, h3, h4, h5, h6 {{
  font-family: {heading_font};
  color: var(--text-color);
  margin-top: 2em;
  margin-bottom: 0.6em;
  line-height: 1.35;
}}
h2 {{
  font-size: 1.9rem;
}}
h3 {{
  font-size: 1.4rem;
}}
h4 {{
  font-size: 1.2rem;
}}
p {{
  margin: 1em 0;
  text-align: justify;
}}
ul, ol {{
  margin-left: 1.5em;
  padding-left: 0;
}}
img, canvas, svg {{
  max-width: 100%;
  height: auto;
}}
.meta-card {{
  background: rgba(0,0,0,0.02);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid var(--border-color);
}}
.meta-card ul {{
  list-style: none;
  padding: 0;
  margin: 0;
}}
.meta-card li {{
  display: flex;
  justify-content: space-between;
  border-bottom: 1px dashed var(--border-color);
  padding: 8px 0;
}}
.toc {{
  margin-top: 30px;
  border: 1px solid var(--border-color);
  border-radius: 12px;
  padding: 20px;
  background: rgba(0,0,0,0.01);
}}
.toc-title {{
  font-weight: 600;
  margin-bottom: 10px;
}}
.toc ul {{
  list-style: none;
  margin: 0;
  padding: 0;
}}
.toc li {{
  margin: 4px 0;
}}
.toc li.level-1 {{
  font-size: 1.05rem;
  font-weight: 600;
  margin-top: 12px;
}}
.toc li.level-2 {{
  margin-left: 12px;
}}
.toc li a {{
  color: var(--primary-color);
  text-decoration: none;
}}
.toc li.level-3 {{
  margin-left: 16px;
  font-size: 0.95em;
}}
.toc-desc {{
  margin: 2px 0 0;
  color: var(--secondary-color);
  font-size: 0.9rem;
}}
.toc-desc {{
  margin: 2px 0 0;
  color: var(--secondary-color);
  font-size: 0.9rem;
}}
.chapter {{
  margin-top: 40px;
  padding-top: 32px;
  border-top: 1px solid rgba(0,0,0,0.05);
}}
.chapter:first-of-type {{
  border-top: none;
  padding-top: 0;
}}
blockquote {{
  border-left: 4px solid var(--primary-color);
  padding: 12px 16px;
  background: rgba(0,0,0,0.04);
  border-radius: 0 8px 8px 0;
}}
.engine-quote {{
  --engine-quote-bg: var(--engine-insight-bg);
  --engine-quote-border: var(--engine-insight-border);
  --engine-quote-text: var(--engine-insight-text);
  margin: 22px 0;
  padding: 16px 18px;
  border-radius: 14px;
  border: 1px solid var(--engine-quote-border);
  background: var(--engine-quote-bg);
  box-shadow: var(--engine-quote-shadow);
  line-height: 1.65;
}}
.engine-quote__header {{
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 650;
  color: var(--engine-quote-text);
  margin-bottom: 8px;
  letter-spacing: 0.02em;
}}
.engine-quote__dot {{
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: var(--engine-quote-text);
  box-shadow: 0 0 0 8px rgba(0,0,0,0.02);
}}
.engine-quote__title {{
  font-size: 0.98rem;
}}
.engine-quote__body > *:first-child {{ margin-top: 0; }}
.engine-quote__body > *:last-child {{ margin-bottom: 0; }}
.engine-quote.engine-media {{
  --engine-quote-bg: var(--engine-media-bg);
  --engine-quote-border: var(--engine-media-border);
  --engine-quote-text: var(--engine-media-text);
}}
.engine-quote.engine-query {{
  --engine-quote-bg: var(--engine-query-bg);
  --engine-quote-border: var(--engine-query-border);
  --engine-quote-text: var(--engine-query-text);
}}
.table-wrap {{
  overflow-x: auto;
  margin: 20px 0;
}}
table {{
  width: 100%;
  border-collapse: collapse;
}}
table th, table td {{
  padding: 12px;
  border: 1px solid var(--border-color);
}}
table th {{
  background: rgba(0,0,0,0.03);
}}
.align-center {{ text-align: center; }}
.align-right {{ text-align: right; }}
.swot-card {{
  margin: 26px 0;
  padding: 18px 18px 14px;
  border-radius: 16px;
  border: 1px solid var(--swot-card-border);
  background: var(--swot-card-bg);
  box-shadow: var(--swot-card-shadow);
  color: var(--swot-text);
  backdrop-filter: var(--swot-card-blur);
  position: relative;
  overflow: hidden;
}}
.swot-card__head {{
  display: flex;
  justify-content: space-between;
  gap: 16px;
  align-items: flex-start;
  flex-wrap: wrap;
}}
.swot-card__title {{
  font-size: 1.15rem;
  font-weight: 750;
  margin-bottom: 4px;
}}
.swot-card__summary {{
  margin: 0;
  color: var(--swot-text);
  opacity: 0.82;
}}
.swot-legend {{
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}}
.swot-legend__item {{
  padding: 6px 12px;
  border-radius: 999px;
  font-weight: 700;
  color: var(--swot-on-dark);
  border: 1px solid var(--swot-tag-border);
  box-shadow: 0 4px 12px rgba(0,0,0,0.16);
  text-shadow: 0 1px 2px rgba(0,0,0,0.35);
}}
.swot-legend__item.strength {{ background: var(--swot-strength); }}
.swot-legend__item.weakness {{ background: var(--swot-weakness); }}
.swot-legend__item.opportunity {{ background: var(--swot-opportunity); }}
.swot-legend__item.threat {{ background: var(--swot-threat); }}
.swot-grid {{
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 12px;
  margin-top: 14px;
}}
.swot-cell {{
  border-radius: 14px;
  border: 1px solid var(--swot-cell-border);
  padding: 12px 12px 10px;
  background: var(--swot-cell-base);
  box-shadow: inset 0 1px 0 rgba(255,255,255,0.4);
}}
.swot-cell.strength {{ border-color: var(--swot-cell-strength-border); background: var(--swot-cell-strength-bg); }}
.swot-cell.weakness {{ border-color: var(--swot-cell-weakness-border); background: var(--swot-cell-weakness-bg); }}
.swot-cell.opportunity {{ border-color: var(--swot-cell-opportunity-border); background: var(--swot-cell-opportunity-bg); }}
.swot-cell.threat {{ border-color: var(--swot-cell-threat-border); background: var(--swot-cell-threat-bg); }}
.swot-cell__meta {{
  display: flex;
  gap: 10px;
  align-items: flex-start;
  margin-bottom: 8px;
}}
.swot-pill {{
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 12px;
  font-weight: 800;
  color: var(--swot-on-dark);
  border: 1px solid var(--swot-tag-border);
  box-shadow: 0 8px 20px rgba(0,0,0,0.18);
}}
.swot-pill.strength {{ background: var(--swot-strength); }}
.swot-pill.weakness {{ background: var(--swot-weakness); }}
.swot-pill.opportunity {{ background: var(--swot-opportunity); }}
.swot-pill.threat {{ background: var(--swot-threat); }}
.swot-cell__title {{
  font-weight: 750;
  letter-spacing: 0.01em;
  color: var(--swot-text);
}}
.swot-cell__caption {{
  font-size: 0.9rem;
  color: var(--swot-text);
  opacity: 0.7;
}}
.swot-list {{
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}}
.swot-item {{
  padding: 10px 12px;
  border-radius: 12px;
  background: var(--swot-surface);
  border: 1px solid var(--swot-item-border);
  box-shadow: 0 12px 22px rgba(0,0,0,0.08);
}}
.swot-item-title {{
  display: flex;
  justify-content: space-between;
  gap: 8px;
  font-weight: 650;
  color: var(--swot-text);
}}
.swot-item-tags {{
  display: inline-flex;
  gap: 6px;
  flex-wrap: wrap;
  font-size: 0.85rem;
}}
.swot-tag {{
  display: inline-block;
  padding: 4px 8px;
  border-radius: 10px;
  background: var(--swot-chip-bg);
  color: var(--swot-text);
  border: 1px solid var(--swot-tag-border);
  box-shadow: 0 6px 14px rgba(0,0,0,0.12);
  line-height: 1.2;
}}
.swot-tag.neutral {{
  opacity: 0.9;
}}
.swot-item-desc {{
  margin-top: 4px;
  color: var(--swot-text);
  opacity: 0.92;
}}
.swot-item-evidence {{
  margin-top: 4px;
  font-size: 0.9rem;
  color: var(--secondary-color);
  opacity: 0.94;
}}
.swot-empty {{
  padding: 12px;
  border-radius: 12px;
  border: 1px dashed var(--swot-card-border);
  text-align: center;
  color: var(--swot-muted);
  opacity: 0.7;
}}

/* ========== SWOT PDF表格布局样式(默认隐藏)========== */
.swot-pdf-wrapper {{
  display: none;
}}

/* SWOT PDF表格样式定义(用于PDF渲染时显示) */
.swot-pdf-table {{
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
  font-size: 13px;
  table-layout: fixed;
}}
.swot-pdf-caption {{
  caption-side: top;
  text-align: left;
  font-size: 1.15rem;
  font-weight: 700;
  padding: 12px 0;
  color: var(--text-color);
}}
.swot-pdf-thead th {{
  background: #f8f9fa;
  padding: 10px 8px;
  text-align: left;
  font-weight: 600;
  border: 1px solid #dee2e6;
  color: #495057;
}}
.swot-pdf-th-quadrant {{ width: 80px; }}
.swot-pdf-th-num {{ width: 50px; text-align: center; }}
.swot-pdf-th-title {{ width: 22%; }}
.swot-pdf-th-detail {{ width: auto; }}
.swot-pdf-th-tags {{ width: 100px; text-align: center; }}
.swot-pdf-summary {{
  padding: 12px;
  background: #f8f9fa;
  color: #666;
  font-style: italic;
  border: 1px solid #dee2e6;
}}
.swot-pdf-quadrant {{
  break-inside: avoid;
  page-break-inside: avoid;
}}
.swot-pdf-quadrant-label {{
  text-align: center;
  vertical-align: middle;
  padding: 12px 8px;
  font-weight: 700;
  border: 1px solid #dee2e6;
  writing-mode: horizontal-tb;
}}
.swot-pdf-quadrant-label.swot-pdf-strength {{ background: rgba(28,127,110,0.15); color: #1c7f6e; border-left: 4px solid #1c7f6e; }}
.swot-pdf-quadrant-label.swot-pdf-weakness {{ background: rgba(192,57,43,0.12); color: #c0392b; border-left: 4px solid #c0392b; }}
.swot-pdf-quadrant-label.swot-pdf-opportunity {{ background: rgba(31,90,179,0.12); color: #1f5ab3; border-left: 4px solid #1f5ab3; }}
.swot-pdf-quadrant-label.swot-pdf-threat {{ background: rgba(179,107,22,0.12); color: #b36b16; border-left: 4px solid #b36b16; }}
.swot-pdf-code {{
  display: block;
  font-size: 1.5rem;
  font-weight: 800;
  margin-bottom: 4px;
}}
.swot-pdf-label-text {{
  display: block;
  font-size: 0.75rem;
  font-weight: 600;
  letter-spacing: 0.02em;
}}
.swot-pdf-item-row td {{
  padding: 10px 8px;
  border: 1px solid #dee2e6;
  vertical-align: top;
}}
.swot-pdf-item-row.swot-pdf-strength td {{ background: rgba(28,127,110,0.03); }}
.swot-pdf-item-row.swot-pdf-weakness td {{ background: rgba(192,57,43,0.03); }}
.swot-pdf-item-row.swot-pdf-opportunity td {{ background: rgba(31,90,179,0.03); }}
.swot-pdf-item-row.swot-pdf-threat td {{ background: rgba(179,107,22,0.03); }}
.swot-pdf-item-num {{
  text-align: center;
  font-weight: 600;
  color: #6c757d;
}}
.swot-pdf-item-title {{
  font-weight: 600;
  color: #212529;
}}
.swot-pdf-item-detail {{
  color: #495057;
  line-height: 1.5;
}}
.swot-pdf-item-tags {{
  text-align: center;
}}
.swot-pdf-tag {{
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 0.75rem;
  background: #e9ecef;
  color: #495057;
  margin: 2px;
}}
.swot-pdf-tag--score {{
  background: #fff3cd;
  color: #856404;
}}
.swot-pdf-empty {{
  text-align: center;
  color: #adb5bd;
  font-style: italic;
}}

/* 打印模式下的SWOT分页控制(保留卡片布局的打印支持) */
@media print {{
  .swot-card {{
    break-inside: auto;
    page-break-inside: auto;
  }}
  .swot-card__head {{
    break-after: avoid;
    page-break-after: avoid;
  }}
  .swot-pdf-quadrant {{
    break-inside: avoid;
    page-break-inside: avoid;
  }}
}}
.callout {{
  border-left: 4px solid var(--primary-color);
  padding: 16px;
  border-radius: 8px;
  margin: 20px 0;
  background: rgba(0,0,0,0.02);
}}
.callout.tone-warning {{ border-color: #ff9800; }}
.callout.tone-success {{ border-color: #2ecc71; }}
.callout.tone-danger {{ border-color: #e74c3c; }}
.kpi-grid {{
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
  margin: 20px 0;
}}
.kpi-card {{
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 16px;
  border-radius: 12px;
  background: rgba(0,0,0,0.02);
  border: 1px solid var(--border-color);
  align-items: flex-start;
}}
.kpi-value {{
  font-size: 2rem;
  font-weight: 700;
  display: flex;
  flex-wrap: nowrap;
  gap: 4px 6px;
  line-height: 1.25;
  word-break: break-word;
  overflow-wrap: break-word;
}}
.kpi-value small {{
  font-size: 0.65em;
  align-self: baseline;
  white-space: nowrap;
}}
.kpi-label {{
  color: var(--secondary-color);
  line-height: 1.35;
  word-break: break-word;
  overflow-wrap: break-word;
  max-width: 100%;
}}
.delta.up {{ color: #27ae60; }}
.delta.down {{ color: #e74c3c; }}
.delta.neutral {{ color: var(--secondary-color); }}
.delta {{
  display: block;
  line-height: 1.3;
  word-break: break-word;
  overflow-wrap: break-word;
}}
.chart-card {{
  margin: 30px 0;
  padding: 20px;
  border: 1px solid var(--border-color);
  border-radius: 12px;
  background: rgba(0,0,0,0.01);
}}
.chart-card.chart-card--error {{
  border-style: dashed;
  background: linear-gradient(135deg, rgba(0,0,0,0.015), rgba(0,0,0,0.04));
}}
.chart-error {{
  display: flex;
  gap: 12px;
  padding: 14px 12px;
  border-radius: 10px;
  align-items: flex-start;
  background: rgba(0,0,0,0.03);
  color: var(--secondary-color);
}}
.chart-error__icon {{
  width: 28px;
  height: 28px;
  flex-shrink: 0;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  color: var(--secondary-color-dark);
  background: rgba(0,0,0,0.06);
  font-size: 0.9rem;
}}
.chart-error__title {{
  font-weight: 600;
  color: var(--text-color);
}}
.chart-error__desc {{
  margin: 4px 0 0;
  color: var(--secondary-color);
  line-height: 1.6;
}}
.chart-card.wordcloud-card .chart-container {{
  min-height: 180px;
}}
.chart-container {{
  position: relative;
  min-height: 220px;
}}
.chart-fallback {{
  display: none;
  margin-top: 12px;
  font-size: 0.85rem;
  overflow-x: auto;
}}
.no-js .chart-fallback {{
  display: block;
}}
.no-js .chart-container {{
  display: none;
}}
.chart-fallback table {{
  width: 100%;
  border-collapse: collapse;
}}
.chart-fallback th,
.chart-fallback td {{
  border: 1px solid var(--border-color);
  padding: 6px 8px;
  text-align: left;
}}
.chart-fallback th {{
  background: rgba(0,0,0,0.04);
}}
.wordcloud-fallback .wordcloud-badges {{
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 6px;
}}
.wordcloud-badge {{
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 999px;
  border: 1px solid rgba(74, 144, 226, 0.35);
  color: var(--text-color);
  background: linear-gradient(135deg, rgba(74, 144, 226, 0.14) 0%, rgba(74, 144, 226, 0.24) 100%);
  box-shadow: 0 4px 10px rgba(15, 23, 42, 0.06);
}}
.dark-mode .wordcloud-badge {{
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.35);
}}
.wordcloud-badge small {{
  color: var(--secondary-color);
  font-weight: 600;
  font-size: 0.75rem;
}}
.chart-note {{
  margin-top: 8px;
  font-size: 0.85rem;
  color: var(--secondary-color);
}}
figure {{
  margin: 20px 0;
  text-align: center;
}}
figure img {{
  max-width: 100%;
  border-radius: 12px;
}}
.figure-placeholder {{
  padding: 16px;
  border: 1px dashed var(--border-color);
  border-radius: 12px;
  color: var(--secondary-color);
  text-align: center;
  font-size: 0.95rem;
  margin: 20px 0;
}}
.math-block {{
  text-align: center;
  font-size: 1.1rem;
  margin: 24px 0;
}}
.math-inline {{
  font-family: {fonts.get("heading", fonts.get("body", "sans-serif"))};
  font-style: italic;
  white-space: nowrap;
  padding: 0 0.15em;
}}
pre.code-block {{
  background: #1e1e1e;
  color: #fff;
  padding: 16px;
  border-radius: 12px;
  overflow-x: auto;
}}
@media (max-width: 768px) {{
  .report-header {{
    flex-direction: column;
    align-items: flex-start;
  }}
  main {{
    margin: 0;
    border-radius: 0;
  }}
}}
@media print {{
  .no-print {{ display: none !important; }}
  body {{
    background: #fff;
  }}
  main {{
    box-shadow: none;
    margin: 0;
    max-width: 100%;
  }}
  .chapter > *,
  .hero-section,
  .callout,
  .engine-quote,
  .chart-card,
  .kpi-grid,
.swot-card,
.table-wrap,
figure,
blockquote {{
  break-inside: avoid;
    page-break-inside: avoid;
    max-width: 100%;
  }}
  .chapter h2,
  .chapter h3,
  .chapter h4 {{
    break-after: avoid;
    page-break-after: avoid;
    break-inside: avoid;
  }}
  .chart-card,
  .table-wrap {{
    overflow: visible !important;
    max-width: 100% !important;
    box-sizing: border-box;
  }}
  .chart-card canvas {{
    width: 100% !important;
    height: auto !important;
    max-width: 100% !important;
  }}
  .swot-card,
  .swot-cell {{
    break-inside: avoid;
    page-break-inside: avoid;
  }}
  .swot-card {{
    color: var(--swot-text);
    /* 允许卡片内部分页,避免整体被抬到下一页 */
    break-inside: auto !important;
    page-break-inside: auto !important;
  }}
  .swot-card__head {{
    break-after: avoid;
    page-break-after: avoid;
  }}
  .swot-grid {{
    break-before: avoid;
    page-break-before: avoid;
    break-inside: auto;
    page-break-inside: auto;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: stretch;
  }}
  .swot-grid .swot-cell {{
    break-inside: avoid;
    page-break-inside: avoid;
  }}
  .swot-legend {{
    display: none !important;
  }}
  .swot-grid .swot-cell {{
    flex: 1 1 320px;
    min-width: 240px;
    height: auto;
  }}
.table-wrap {{
  overflow-x: auto;
  max-width: 100%;
}}
.table-wrap table {{
  table-layout: fixed;
  width: 100%;
  max-width: 100%;
}}
.table-wrap table th,
.table-wrap table td {{
  word-break: break-word;
  overflow-wrap: break-word;
}}
/* 防止图片和图表溢出 */
img, canvas, svg {{
  max-width: 100% !important;
  height: auto !important;
}}
/* 确保所有容器不超出页面宽度 */
* {{
  box-sizing: border-box;
  max-width: 100%;
}}
}}

"""

    def _hydration_script(self) -> str:
        """返回页面底部的JS,负责Chart.js注水与导出逻辑"""
        return """
<script>
document.documentElement.classList.remove('no-js');
document.documentElement.classList.add('js-ready');

/* ========== Theme Button Web Component ========== */
(() => {
  const themeButtonFunc = (root, initTheme, changeTheme) => {
    const $ = (s) => {
      let dom = root.querySelectorAll(s);
      return dom.length == 1 ? dom[0] : dom;
    };
    let mainButton = $(".main-button");
    let daytimeBackground = $(".daytime-background");
    let cloud = $(".cloud");
    let cloudList = $(".cloud-son");
    let cloudLight = $(".cloud-light");
    let components = $(".components");
    let moon = $(".moon");
    let stars = $(".stars");
    let star = $(".star");
    let isMoved = false;
    let isClicked = false;

    components.onclick = () => {
      if (isMoved) {
        mainButton.style.transform = "translateX(0)";
        mainButton.style.backgroundColor = "rgba(255, 195, 35,1)";
        mainButton.style.boxShadow = "3em 3em 5em rgba(0, 0, 0, 0.5), inset -3em -5em 3em -3em rgba(0, 0, 0, 0.5), inset 4em 5em 2em -2em rgba(255, 230, 80,1)";
        daytimeBackground[0].style.transform = "translateX(0)";
        daytimeBackground[1].style.transform = "translateX(0)";
        daytimeBackground[2].style.transform = "translateX(0)";
        cloud.style.transform = "translateY(10em)";
        cloudLight.style.transform = "translateY(10em)";
        components.style.backgroundColor = "rgba(70, 133, 192,1)";
        moon[0].style.opacity = "0";
        moon[1].style.opacity = "0";
        moon[2].style.opacity = "0";
        stars.style.transform = "translateY(-125em)";
        stars.style.opacity = "0";
        changeTheme("light");
      } else {
        mainButton.style.transform = "translateX(110em)";
        mainButton.style.backgroundColor = "rgba(195, 200,210,1)";
        mainButton.style.boxShadow = "3em 3em 5em rgba(0, 0, 0, 0.5), inset -3em -5em 3em -3em rgba(0, 0, 0, 0.5), inset 4em 5em 2em -2em rgba(255, 255, 210,1)";
        daytimeBackground[0].style.transform = "translateX(110em)";
        daytimeBackground[1].style.transform = "translateX(80em)";
        daytimeBackground[2].style.transform = "translateX(50em)";
        cloud.style.transform = "translateY(80em)";
        cloudLight.style.transform = "translateY(80em)";
        components.style.backgroundColor = "rgba(25,30,50,1)";
        moon[0].style.opacity = "1";
        moon[1].style.opacity = "1";
        moon[2].style.opacity = "1";
        stars.style.transform = "translateY(-62.5em)";
        stars.style.opacity = "1";
        changeTheme("dark");
      }
      isClicked = true;
      setTimeout(function () { isClicked = false; }, 500);
      isMoved = !isMoved;
    };

    mainButton.addEventListener("mousemove", function () {
      if (isClicked) return;
      if (isMoved) {
        mainButton.style.transform = "translateX(100em)";
        daytimeBackground[0].style.transform = "translateX(100em)";
        daytimeBackground[1].style.transform = "translateX(73em)";
        daytimeBackground[2].style.transform = "translateX(46em)";
        star[0].style.top = "10em"; star[0].style.left = "36em";
        star[1].style.top = "40em"; star[1].style.left = "87em";
        star[2].style.top = "26em"; star[2].style.left = "16em";
        star[3].style.top = "38em"; star[3].style.left = "63em";
        star[4].style.top = "20.5em"; star[4].style.left = "72em";
        star[5].style.top = "51.5em"; star[5].style.left = "35em";
      } else {
        mainButton.style.transform = "translateX(10em)";
        daytimeBackground[0].style.transform = "translateX(10em)";
        daytimeBackground[1].style.transform = "translateX(7em)";
        daytimeBackground[2].style.transform = "translateX(4em)";
        cloudList[0].style.right = "-24em"; cloudList[0].style.bottom = "10em";
        cloudList[1].style.right = "-12em"; cloudList[1].style.bottom = "-27em";
        cloudList[2].style.right = "17em"; cloudList[2].style.bottom = "-43em";
        cloudList[3].style.right = "46em"; cloudList[3].style.bottom = "-39em";
        cloudList[4].style.right = "70em"; cloudList[4].style.bottom = "-65em";
        cloudList[5].style.right = "109em"; cloudList[5].style.bottom = "-54em";
        cloudList[6].style.right = "-23em"; cloudList[6].style.bottom = "10em";
        cloudList[7].style.right = "-11em"; cloudList[7].style.bottom = "-26em";
        cloudList[8].style.right = "18em"; cloudList[8].style.bottom = "-42em";
        cloudList[9].style.right = "47em"; cloudList[9].style.bottom = "-38em";
        cloudList[10].style.right = "74em"; cloudList[10].style.bottom = "-64em";
        cloudList[11].style.right = "110em"; cloudList[11].style.bottom = "-55em";
      }
    });

    mainButton.addEventListener("mouseout", function () {
      if (isClicked) return;
      if (isMoved) {
        mainButton.style.transform = "translateX(110em)";
        daytimeBackground[0].style.transform = "translateX(110em)";
        daytimeBackground[1].style.transform = "translateX(80em)";
        daytimeBackground[2].style.transform = "translateX(50em)";
        star[0].style.top = "11em"; star[0].style.left = "39em";
        star[1].style.top = "39em"; star[1].style.left = "91em";
        star[2].style.top = "26em"; star[2].style.left = "19em";
        star[3].style.top = "37em"; star[3].style.left = "66em";
        star[4].style.top = "21em"; star[4].style.left = "75em";
        star[5].style.top = "51em"; star[5].style.left = "38em";
      } else {
        mainButton.style.transform = "translateX(0em)";
        daytimeBackground[0].style.transform = "translateX(0em)";
        daytimeBackground[1].style.transform = "translateX(0em)";
        daytimeBackground[2].style.transform = "translateX(0em)";
        cloudList[0].style.right = "-20em"; cloudList[0].style.bottom = "10em";
        cloudList[1].style.right = "-10em"; cloudList[1].style.bottom = "-25em";
        cloudList[2].style.right = "20em"; cloudList[2].style.bottom = "-40em";
        cloudList[3].style.right = "50em"; cloudList[3].style.bottom = "-35em";
        cloudList[4].style.right = "75em"; cloudList[4].style.bottom = "-60em";
        cloudList[5].style.right = "110em"; cloudList[5].style.bottom = "-50em";
        cloudList[6].style.right = "-20em"; cloudList[6].style.bottom = "10em";
        cloudList[7].style.right = "-10em"; cloudList[7].style.bottom = "-25em";
        cloudList[8].style.right = "20em"; cloudList[8].style.bottom = "-40em";
        cloudList[9].style.right = "50em"; cloudList[9].style.bottom = "-35em";
        cloudList[10].style.right = "75em"; cloudList[10].style.bottom = "-60em";
        cloudList[11].style.right = "110em"; cloudList[11].style.bottom = "-50em";
      }
    });

    const getRandomDirection = () => ["2em", "-2em"][Math.floor(Math.random() * 2)];
    const moveElementRandomly = (element) => {
      element.style.transform = `translate(${getRandomDirection()}, ${getRandomDirection()})`;
    };
    const cloudSons = root.querySelectorAll(".cloud-son");
    setInterval(() => { cloudSons.forEach(moveElementRandomly); }, 1000);

    if (initTheme === "dark") {
      components.onclick();
    }
  };

  class ThemeButton extends HTMLElement {
    constructor() { super(); }
    connectedCallback() {
      const initTheme = this.getAttribute("value") || "light";
      const size = +this.getAttribute("size") || 3;
      const shadow = this.attachShadow({ mode: "closed" });
      const container = document.createElement("div");
      container.setAttribute("class", "container");
      container.setAttribute("style", `font-size: ${(size / 3).toFixed(2)}px`);
      container.innerHTML = '<div class="components"><div class="main-button"><div class="moon"></div><div class="moon"></div><div class="moon"></div></div><div class="daytime-background"></div><div class="daytime-background"></div><div class="daytime-background"></div><div class="cloud"><div class="cloud-son"></div><div class="cloud-son"></div><div class="cloud-son"></div><div class="cloud-son"></div><div class="cloud-son"></div><div class="cloud-son"></div></div><div class="cloud-light"><div class="cloud-son"></div><div class="cloud-son"></div><div class="cloud-son"></div><div class="cloud-son"></div><div class="cloud-son"></div><div class="cloud-son"></div></div><div class="stars"><div class="star big"><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div></div><div class="star big"><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div></div><div class="star medium"><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div></div><div class="star medium"><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div></div><div class="star small"><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div></div><div class="star small"><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div><div class="star-son"></div></div></div></div>';
      const style = document.createElement("style");
      /**
       * 日夜切换按钮组件的完整 CSS 样式
       * 
       * 组件结构:
       * - .container: 最外层容器,控制整体尺寸和定位
       * - .components: 按钮主体(胶囊形状),包含所有内部元素
       * - .main-button: 可移动的圆形按钮(太阳/月亮)
       * - .moon: 月亮上的环形山(3个灰色圆形)
       * - .daytime-background: 太阳光晕效果(3层渐变圆形)
       * - .cloud / .cloud-light: 白天的云朵容器
       * - .cloud-son: 单个云朵(白色圆形)
       * - .stars: 夜晚的星星容器
       * - .star: 单颗星星(由4个 .star-son 组成四角星形状)
       */
      style.textContent = [
        // ========== 全局重置 ==========
        // 清除默认边距,设置统一过渡动画,禁用移动端点击高亮
        "* { margin: 0; padding: 0; transition: 0.7s; -webkit-tap-highlight-color: rgba(0,0,0,0); }",

        // ========== 最外层容器 ==========
        // position: relative - 在文档流中正常显示,作为内部 absolute 元素的定位参考
        // width/height: 180em x 70em - 按钮整体尺寸(em 单位可通过 font-size 缩放)
        // display: inline-block - 行内块元素,便于在 header 中排列
        // vertical-align: bottom - 底部对齐
        // transform: translate3d(0,0,0) - 开启 GPU 加速,提升动画性能
        ".container { position: relative; width: 180em; height: 70em; display: inline-block; vertical-align: bottom; transform: translate3d(0, 0, 0); }",

        // ========== 按钮主体(胶囊形状) ==========
        // position: absolute - 相对于 .container 绝对定位
        // background-color: rgba(70,133,192,1) - 白天的蓝色天空背景
        // border-radius: 100em - 超大圆角形成胶囊形状
        // box-shadow: inset ... - 内阴影增加立体感
        // overflow: hidden - 隐藏超出边界的元素(云朵、光晕等)
        // transition-timing-function: cubic-bezier(0,0.5,1,1) - 自定义缓动曲线
        // cursor: pointer - 鼠标悬停显示手型
        ".components { position: absolute; top: 0; left: 0; width: 180em; height: 70em; background-color: rgba(70, 133, 192, 1); border-radius: 100em; box-shadow: inset 0 0 5em 3em rgba(0, 0, 0, 0.5); overflow: hidden; transition: 0.7s; transition-timing-function: cubic-bezier(0, 0.5, 1, 1); cursor: pointer; }",

        // ========== 可移动的圆形按钮(太阳/月亮) ==========
        // margin: 7.5em 0 0 7.5em - 初始位置在左侧(白天/太阳状态)
        // width/height: 55em - 圆形按钮直径
        // background-color: rgba(255,195,35,1) - 太阳的金黄色
        // border-radius: 50% - 完美圆形
        // box-shadow - 三层阴影:外阴影(立体感) + 内阴影(暗部) + 内高光(亮部)
        // transition: 1.0s - 切换动画时长
        // cubic-bezier(0.56,1.35,0.52,1.00) - 弹性缓动效果(超过终点后回弹)
        ".main-button { margin: 7.5em 0 0 7.5em; width: 55em; height: 55em; background-color: rgba(255, 195, 35, 1); border-radius: 50%; box-shadow: 3em 3em 5em rgba(0, 0, 0, 0.5), inset -3em -5em 3em -3em rgba(0, 0, 0, 0.5), inset 4em 5em 2em -2em rgba(255, 230, 80, 1); transition: 1.0s; transition-timing-function: cubic-bezier(0.56, 1.35, 0.52, 1.00); }",

        // ========== 月亮环形山 ==========
        // 三个灰色圆形模拟月球表面的环形山
        // opacity: 0 - 白天时隐藏,切换到夜晚时显示
        // box-shadow: inset ... - 内阴影增加凹陷效果
        ".moon { position: absolute; background-color: rgba(150, 160, 180, 1); box-shadow: inset 0em 0em 1em 1em rgba(0, 0, 0, 0.3); border-radius: 50%; transition: 0.5s; opacity: 0; }",
        // 三个环形山的不同位置和大小
        ".moon:nth-child(1) { top: 7.5em; left: 25em; width: 12.5em; height: 12.5em; }",   // 右上角小环形山
        ".moon:nth-child(2) { top: 20em; left: 7.5em; width: 20em; height: 20em; }",       // 左侧大环形山
        ".moon:nth-child(3) { top: 32.5em; left: 32.5em; width: 12.5em; height: 12.5em; }", // 右下角小环形山

        // ========== 太阳光晕效果 ==========
        // 三层半透明白色圆形,模拟太阳的光晕扩散效果
        // 随太阳移动,z-index 为负值确保在太阳后面
        ".daytime-background { position: absolute; border-radius: 50%; transition: 1.0s; transition-timing-function: cubic-bezier(0.56, 1.35, 0.52, 1.00); }",
        // 第一层光晕:最亮,20%不透明度
        ".daytime-background:nth-child(2) { top: -20em; left: -20em; width: 110em; height: 110em; background-color: rgba(255, 255, 255, 0.2); z-index: -2; }",
        // 第二层光晕:中等亮度,10%不透明度
        ".daytime-background:nth-child(3) { top: -32.5em; left: -17.5em; width: 135em; height: 135em; background-color: rgba(255, 255, 255, 0.1); z-index: -3; }",
        // 第三层光晕:最淡,5%不透明度
        ".daytime-background:nth-child(4) { top: -45em; left: -15em; width: 160em; height: 160em; background-color: rgba(255, 255, 255, 0.05); z-index: -4; }",

        // ========== 云朵容器 ==========
        // transform: translateY(10em) - 白天时云朵可见位置
        // 切换到夜晚时 translateY(80em) 将云朵移出视野
        ".cloud, .cloud-light { transform: translateY(10em); transition: 1.0s; transition-timing-function: cubic-bezier(0.56, 1.35, 0.52, 1.00); }",

        // ========== 单个云朵 ==========
        // 白色圆形,通过不同位置组合形成云朵形状
        // transition: transform 6s - 云朵随机飘动动画较慢(6秒)
        // right/bottom 1s - 位置变化动画较快(1秒)
        ".cloud-son { position: absolute; background-color: #fff; border-radius: 50%; z-index: -1; transition: transform 6s, right 1s, bottom 1s; }",
        // 6个云朵的不同位置和大小(使用 6n+x 选择器循环应用)
        ".cloud-son:nth-child(6n+1) { right: -20em; bottom: 10em; width: 50em; height: 50em; }",
        ".cloud-son:nth-child(6n+2) { right: -10em; bottom: -25em; width: 60em; height: 60em; }",
        ".cloud-son:nth-child(6n+3) { right: 20em; bottom: -40em; width: 60em; height: 60em; }",
        ".cloud-son:nth-child(6n+4) { right: 50em; bottom: -35em; width: 60em; height: 60em; }",
        ".cloud-son:nth-child(6n+5) { right: 75em; bottom: -60em; width: 75em; height: 75em; }",
        ".cloud-son:nth-child(6n+6) { right: 110em; bottom: -50em; width: 60em; height: 60em; }",
        // 主云朵层
        ".cloud { z-index: -2; }",
        // 浅色云朵层(半透明,增加层次感)
        ".cloud-light { position: absolute; right: 0em; bottom: 25em; opacity: 0.5; z-index: -3; }",

        // ========== 星星容器 ==========
        // transform: translateY(-125em) - 白天时星星在视野外上方
        // 切换到夜晚时 translateY(-62.5em) 将星星移入视野
        ".stars { transform: translateY(-125em); z-index: -2; transition: 1.0s; transition-timing-function: cubic-bezier(0.56, 1.35, 0.52, 1.00); }",

        // ========== 星星尺寸变量 ==========
        // 使用 CSS 变量定义三种星星大小
        ".big { --size: 7.5em; }",     // 大星星
        ".medium { --size: 5em; }",    // 中星星
        ".small { --size: 3em; }",     // 小星星

        // ========== 单颗星星 ==========
        // 星星尺寸为 2 * --size(因为由4个角组成)
        ".star { position: absolute; width: calc(2*var(--size)); height: calc(2*var(--size)); }",
        // 6颗星星的不同位置和闪烁动画时长(错开闪烁节奏)
        ".star:nth-child(1) { top: 11em; left: 39em; animation-name: star; animation-duration: 3.5s; }",
        ".star:nth-child(2) { top: 39em; left: 91em; animation-name: star; animation-duration: 4.1s; }",
        ".star:nth-child(3) { top: 26em; left: 19em; animation-name: star; animation-duration: 4.9s; }",
        ".star:nth-child(4) { top: 37em; left: 66em; animation-name: star; animation-duration: 5.3s; }",
        ".star:nth-child(5) { top: 21em; left: 75em; animation-name: star; animation-duration: 3s; }",
        ".star:nth-child(6) { top: 51em; left: 38em; animation-name: star; animation-duration: 2.2s; }",

        // ========== 星星闪烁动画 ==========
        // 0-20%: 缩小到0(消失)
        // 20-100%: 恢复原大小(显示)
        // 配合 animation-direction: alternate 实现来回闪烁
        "@keyframes star { 0%, 20% { transform: scale(0); } 20%, 100% { transform: scale(1); } }",

        // ========== 星星角(组成四角星形状) ==========
        // 每颗星星由4个 .star-son 组成,分别是四个角
        ".star-son { float: left; }",
        // 四个角的位置变量(用于 radial-gradient 定位)
        ".star-son:nth-child(1) { --pos: left 0; }",       // 左上角
        ".star-son:nth-child(2) { --pos: right 0; }",      // 右上角
        ".star-son:nth-child(3) { --pos: 0 bottom; }",     // 左下角
        ".star-son:nth-child(4) { --pos: right bottom; }", // 右下角
        // 使用 radial-gradient 创建四分之一圆形,组合成四角星
        // 原理:在角落位置创建透明圆形,圆形外是白色,形成尖角效果
        ".star-son { width: var(--size); height: var(--size); background-image: radial-gradient(circle var(--size) at var(--pos), transparent var(--size), #fff); }",

        // ========== 星星动画属性 ==========
        // animation-iteration-count: infinite - 无限循环
        // animation-direction: alternate - 正反交替播放
        // animation-timing-function: linear - 线性匀速
        ".star { transform: scale(1); transition-timing-function: cubic-bezier(0.56, 1.35, 0.52, 1.00); transition: 1s; animation-iteration-count: infinite; animation-direction: alternate; animation-timing-function: linear; }",

        // ========== 星星闪烁状态 ==========
        // 用于 JS 控制的闪烁状态类
        ".twinkle { transform: scale(0); }"
      ].join(" ");
      const changeTheme = (detail) => {
        this.dispatchEvent(new CustomEvent("change", { detail }));
      };
      themeButtonFunc(container, initTheme, changeTheme);
      shadow.appendChild(style);
      shadow.appendChild(container);
    }
  }
  customElements.define("theme-button", ThemeButton);
})();
/* ========== End Theme Button Web Component ========== */

const chartRegistry = [];
const wordCloudRegistry = new Map();
const STABLE_CHART_TYPES = ['line', 'bar'];
const CHART_TYPE_LABELS = {
  line: '折线图',
  bar: '柱状图',
  doughnut: '圆环图',
  pie: '饼图',
  radar: '雷达图',
  polarArea: '极地区域图'
};

// 与PDF矢量渲染保持一致的颜色替换/提亮规则
const DEFAULT_CHART_COLORS = [
  '#4A90E2', '#E85D75', '#50C878', '#FFB347',
  '#9B59B6', '#3498DB', '#E67E22', '#16A085',
  '#F39C12', '#D35400', '#27AE60', '#8E44AD'
];
const CSS_VAR_COLOR_MAP = {
  'var(--chart-color-green)': '#4BC0C0',
  'var(--chart-color-red)': '#FF6384',
  'var(--chart-color-blue)': '#36A2EB',
  'var(--color-accent)': '#4A90E2',
  'var(--re-accent-color)': '#4A90E2',
  'var(--re-accent-color-translucent)': 'rgba(74, 144, 226, 0.08)',
  'var(--color-kpi-down)': '#E85D75',
  'var(--re-danger-color)': '#E85D75',
  'var(--re-danger-color-translucent)': 'rgba(232, 93, 117, 0.08)',
  'var(--color-warning)': '#FFB347',
  'var(--re-warning-color)': '#FFB347',
  'var(--re-warning-color-translucent)': 'rgba(255, 179, 71, 0.08)',
  'var(--color-success)': '#50C878',
  'var(--re-success-color)': '#50C878',
  'var(--re-success-color-translucent)': 'rgba(80, 200, 120, 0.08)',
  'var(--color-accent-positive)': '#50C878',
  'var(--color-accent-negative)': '#E85D75',
  'var(--color-text-secondary)': '#6B7280',
  'var(--accentPositive)': '#50C878',
  'var(--accentNegative)': '#E85D75',
  'var(--sentiment-positive, #28A745)': '#28A745',
  'var(--sentiment-negative, #E53E3E)': '#E53E3E',
  'var(--sentiment-neutral, #FFC107)': '#FFC107',
  'var(--sentiment-positive)': '#28A745',
  'var(--sentiment-negative)': '#E53E3E',
  'var(--sentiment-neutral)': '#FFC107',
  'var(--color-primary)': '#3498DB',
  'var(--color-secondary)': '#95A5A6'
};
const WORDCLOUD_CATEGORY_COLORS = {
  positive: '#10b981',
  negative: '#ef4444',
  neutral: '#6b7280',
  controversial: '#f59e0b'
};

function normalizeColorToken(color) {
  if (typeof color !== 'string') return color;
  const trimmed = color.trim();
  if (!trimmed) return null;
  // 支持 var(--token, fallback) 形式,优先解析fallback
  const varWithFallback = trimmed.match(/^var\(\s*--[^,)+]+,\s*([^)]+)\)/i);
  if (varWithFallback && varWithFallback[1]) {
    const fallback = varWithFallback[1].trim();
    const normalizedFallback = normalizeColorToken(fallback);
    if (normalizedFallback) return normalizedFallback;
  }
  if (CSS_VAR_COLOR_MAP[trimmed]) {
    return CSS_VAR_COLOR_MAP[trimmed];
  }
  if (trimmed.startsWith('var(')) {
    if (/accent|primary/i.test(trimmed)) return '#4A90E2';
    if (/danger|down|error/i.test(trimmed)) return '#E85D75';
    if (/warning/i.test(trimmed)) return '#FFB347';
    if (/success|up/i.test(trimmed)) return '#50C878';
    return '#3498DB';
  }
  return trimmed;
}

function hexToRgb(color) {
  if (typeof color !== 'string') return null;
  const normalized = color.replace('#', '');
  if (!(normalized.length === 3 || normalized.length === 6)) return null;
  const hex = normalized.length === 3 ? normalized.split('').map(c => c + c).join('') : normalized;
  const intVal = parseInt(hex, 16);
  if (Number.isNaN(intVal)) return null;
  return [(intVal >> 16) & 255, (intVal >> 8) & 255, intVal & 255];
}

function parseRgbString(color) {
  if (typeof color !== 'string') return null;
  const match = color.match(/rgba?\s*\(([^)]+)\)/i);
  if (!match) return null;
  const parts = match[1].split(',').map(p => parseFloat(p.trim())).filter(v => !Number.isNaN(v));
  if (parts.length < 3) return null;
  return [parts[0], parts[1], parts[2]].map(v => Math.max(0, Math.min(255, v)));
}

function alphaFromColor(color) {
  if (typeof color !== 'string') return null;
  const raw = color.trim();
  if (!raw) return null;
  if (raw.toLowerCase() === 'transparent') return 0;

  const extractAlpha = (source) => {
    const match = source.match(/rgba?\s*\(([^)]+)\)/i);
    if (!match) return null;
    const parts = match[1].split(',').map(p => p.trim());
    if (source.toLowerCase().startsWith('rgba') && parts.length >= 2) {
      const alphaToken = parts[parts.length - 1];
      const isPercent = /%$/.test(alphaToken);
      const alphaVal = parseFloat(alphaToken.replace('%', ''));
      if (!Number.isNaN(alphaVal)) {
        const normalizedAlpha = isPercent ? alphaVal / 100 : alphaVal;
        return Math.max(0, Math.min(1, normalizedAlpha));
      }
    }
    if (parts.length >= 3) return 1;
    return null;
  };

  const rawAlpha = extractAlpha(raw);
  if (rawAlpha !== null) return rawAlpha;

  const normalized = normalizeColorToken(raw);
  if (typeof normalized === 'string' && normalized !== raw) {
    const normalizedAlpha = extractAlpha(normalized);
    if (normalizedAlpha !== null) return normalizedAlpha;
  }

  return null;
}

function rgbFromColor(color) {
  const normalized = normalizeColorToken(color);
  return hexToRgb(normalized) || parseRgbString(normalized);
}

function colorLuminance(color) {
  const rgb = rgbFromColor(color);
  if (!rgb) return null;
  const [r, g, b] = rgb.map(v => {
    const c = v / 255;
    return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
  });
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

function lightenColor(color, ratio) {
  const rgb = rgbFromColor(color);
  if (!rgb) return color;
  const factor = Math.min(1, Math.max(0, ratio || 0.25));
  const mixed = rgb.map(v => Math.round(v + (255 - v) * factor));
  return `rgb(${mixed[0]}, ${mixed[1]}, ${mixed[2]})`;
}

function ensureAlpha(color, alpha) {
  const rgb = rgbFromColor(color);
  if (!rgb) return color;
  const clamped = Math.min(1, Math.max(0, alpha));
  return `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${clamped})`;
}

function liftDarkColor(color) {
  const normalized = normalizeColorToken(color);
  const lum = colorLuminance(normalized);
  if (lum !== null && lum < 0.12) {
    return lightenColor(normalized, 0.35);
  }
  return normalized;
}

function mixColors(colorA, colorB, amount) {
  const rgbA = rgbFromColor(colorA);
  const rgbB = rgbFromColor(colorB);
  if (!rgbA && !rgbB) return colorA || colorB;
  if (!rgbA) return colorB;
  if (!rgbB) return colorA;
  const t = Math.min(1, Math.max(0, amount || 0));
  const mixed = rgbA.map((v, idx) => Math.round(v * (1 - t) + rgbB[idx] * t));
  return `rgb(${mixed[0]}, ${mixed[1]}, ${mixed[2]})`;
}

function pickComputedColor(keys, fallback, styles) {
  const styleRef = styles || getComputedStyle(document.body);
  for (const key of keys) {
    const val = styleRef.getPropertyValue(key);
    if (val && val.trim()) {
      const normalized = normalizeColorToken(val.trim());
      if (normalized) return normalized;
    }
  }
  return fallback;
}

function resolveWordcloudTheme() {
  const styles = getComputedStyle(document.body);
  const isDark = document.body.classList.contains('dark-mode');
  const text = pickComputedColor(['--text-color'], isDark ? '#e5e7eb' : '#111827', styles);
  const secondary = pickComputedColor(['--secondary-color', '--color-text-secondary'], isDark ? '#cbd5e1' : '#475569', styles);
  const accent = liftDarkColor(
    pickComputedColor(['--primary-color', '--color-accent', '--re-accent-color'], '#4A90E2', styles)
  );
  const cardBg = pickComputedColor(
    ['--card-bg', '--paper-bg', '--bg', '--bg-color', '--background', '--page-bg'],
    isDark ? '#0f172a' : '#ffffff',
    styles
  );
  return { text, secondary, accent, cardBg, isDark };
}

function normalizeDatasetColors(payload, chartType) {
  const changes = [];
  const data = payload && payload.data;
  if (!data || !Array.isArray(data.datasets)) {
    return changes;
  }
  const type = chartType || 'bar';
  const needsArrayColors = type === 'pie' || type === 'doughnut' || type === 'polarArea';
  const MIN_PIE_ALPHA = 0.6;
  const pickColor = (value, fallback) => {
    if (Array.isArray(value) && value.length) return value[0];
    return value || fallback;
  };

  data.datasets.forEach((dataset, idx) => {
    if (!isPlainObject(dataset)) return;
    if (type === 'line') {
      dataset.fill = true;  // 对折线图强制开启填充,便于区域对比
    }
    const paletteColor = normalizeColorToken(DEFAULT_CHART_COLORS[idx % DEFAULT_CHART_COLORS.length]);
    const borderInput = dataset.borderColor;
    const backgroundInput = dataset.backgroundColor;
    const borderIsArray = Array.isArray(borderInput);
    const bgIsArray = Array.isArray(backgroundInput);
    const baseCandidate = pickColor(borderInput, pickColor(backgroundInput, dataset.color || paletteColor));
    const liftedBase = liftDarkColor(baseCandidate || paletteColor);

    if (needsArrayColors) {
      const labelCount = Array.isArray(data.labels) ? data.labels.length : 0;
      const rawColors = bgIsArray ? backgroundInput : [];
      const dataLength = Array.isArray(dataset.data) ? dataset.data.length : 0;
      const total = Math.max(labelCount, rawColors.length, dataLength, 1);
      const normalizedColors = [];
      let fixedTransparentCount = 0;
      for (let i = 0; i < total; i++) {
        const fallbackColor = DEFAULT_CHART_COLORS[(idx + i) % DEFAULT_CHART_COLORS.length];
        const normalizedRaw = normalizeColorToken(rawColors[i]);
        const alpha = alphaFromColor(normalizedRaw);
        const isInvisible = typeof normalizedRaw === 'string' && normalizedRaw.toLowerCase() === 'transparent';
        if (alpha === 0 || isInvisible) {
          fixedTransparentCount += 1;
        }
        const baseColor = (!normalizedRaw || isInvisible) ? fallbackColor : normalizedRaw;
        const targetAlpha = alpha === null ? 1 : alpha;
        const normalizedColor = ensureAlpha(
          liftDarkColor(baseColor),
          Math.max(MIN_PIE_ALPHA, targetAlpha)
        );
        normalizedColors.push(normalizedColor);
      }
      dataset.backgroundColor = normalizedColors;
      dataset.borderColor = normalizedColors.map(col => ensureAlpha(liftDarkColor(col), 1));
      const changeLabel = fixedTransparentCount
        ? `dataset${idx}: 修正${fixedTransparentCount}个透明扇区`
        : `dataset${idx}: 标准化扇区颜色(${normalizedColors.length})`;
      changes.push(changeLabel);
      return;
    }

    if (!borderInput) {
      dataset.borderColor = liftedBase;
      changes.push(`dataset${idx}: 补全边框色`);
    } else if (borderIsArray) {
      dataset.borderColor = borderInput.map(col => liftDarkColor(col));
    } else {
      dataset.borderColor = liftDarkColor(borderInput);
    }

    const typeAlpha = type === 'line'
      ? (dataset.fill ? 0.25 : 0.18)
      : type === 'radar'
        ? 0.25
        : type === 'scatter' || type === 'bubble'
          ? 0.6
          : type === 'bar'
            ? 0.85
            : null;

    if (typeAlpha !== null) {
      if (bgIsArray && dataset.backgroundColor.length) {
        dataset.backgroundColor = backgroundInput.map(col => ensureAlpha(liftDarkColor(col), typeAlpha));
      } else {
        const bgSeed = pickColor(backgroundInput, pickColor(dataset.borderColor, paletteColor));
        dataset.backgroundColor = ensureAlpha(liftDarkColor(bgSeed), typeAlpha);
      }
      if (dataset.fill || type !== 'line') {
        changes.push(`dataset${idx}: 应用淡化填充以避免遮挡`);
      }
    } else if (!dataset.backgroundColor) {
      dataset.backgroundColor = ensureAlpha(liftedBase, 0.85);
    } else if (bgIsArray) {
      dataset.backgroundColor = backgroundInput.map(col => liftDarkColor(col));
    } else if (!bgIsArray) {
      dataset.backgroundColor = liftDarkColor(dataset.backgroundColor);
    }

    if (type === 'line' && !dataset.pointBackgroundColor) {
      dataset.pointBackgroundColor = Array.isArray(dataset.borderColor)
        ? dataset.borderColor[0]
        : dataset.borderColor;
    }
  });

  if (changes.length) {
    payload._colorAudit = changes;
  }
  return changes;
}

function getThemePalette() {
  const styles = getComputedStyle(document.body);
  return {
    text: styles.getPropertyValue('--text-color').trim(),
    grid: styles.getPropertyValue('--border-color').trim()
  };
}

function applyChartTheme(chart) {
  if (!chart) return;
  try {
    chart.update('none');
  } catch (err) {
    console.error('Chart refresh failed', err);
  }
}

function isPlainObject(value) {
  return Object.prototype.toString.call(value) === '[object Object]';
}

function cloneDeep(value) {
  if (Array.isArray(value)) {
    return value.map(cloneDeep);
  }
  if (isPlainObject(value)) {
    const obj = {};
    Object.keys(value).forEach(key => {
      obj[key] = cloneDeep(value[key]);
    });
    return obj;
  }
  return value;
}

function mergeOptions(base, override) {
  const result = isPlainObject(base) ? cloneDeep(base) : {};
  if (!isPlainObject(override)) {
    return result;
  }
  Object.keys(override).forEach(key => {
    const overrideValue = override[key];
    if (Array.isArray(overrideValue)) {
      result[key] = cloneDeep(overrideValue);
    } else if (isPlainObject(overrideValue)) {
      result[key] = mergeOptions(result[key], overrideValue);
    } else {
      result[key] = overrideValue;
    }
  });
  return result;
}

function resolveChartTypes(payload) {
  const explicit = payload && payload.props && payload.props.type;
  const widgetType = payload && payload.widgetType ? payload.widgetType : 'chart.js/bar';
  const derived = widgetType && widgetType.includes('/') ? widgetType.split('/').pop() : widgetType;
  const extra = Array.isArray(payload && payload.preferredTypes) ? payload.preferredTypes : [];
  const pipeline = [explicit, derived, ...extra, ...STABLE_CHART_TYPES].filter(Boolean);
  const result = [];
  pipeline.forEach(type => {
    if (type && !result.includes(type)) {
      result.push(type);
    }
  });
  return result.length ? result : ['bar'];
}

function describeChartType(type) {
  return CHART_TYPE_LABELS[type] || type || '图表';
}

function setChartDegradeNote(card, fromType, toType) {
  if (!card) return;
  card.setAttribute('data-chart-state', 'degraded');
  let note = card.querySelector('.chart-note');
  if (!note) {
    note = document.createElement('p');
    note.className = 'chart-note';
    card.appendChild(note);
  }
  note.textContent = `${describeChartType(fromType)}渲染失败,已自动切换为${describeChartType(toType)}以确保兼容。`;
}

function clearChartDegradeNote(card) {
  if (!card) return;
  card.removeAttribute('data-chart-state');
  const note = card.querySelector('.chart-note');
  if (note) {
    note.remove();
  }
}

function isWordCloudWidget(payload) {
  const type = payload && payload.widgetType;
  return typeof type === 'string' && type.toLowerCase().includes('wordcloud');
}

function hashString(str) {
  let h = 0;
  if (!str) return h;
  for (let i = 0; i < str.length; i++) {
    h = (h << 5) - h + str.charCodeAt(i);
    h |= 0;
  }
  return h;
}

function normalizeWordcloudItems(payload) {
  const sources = [];
  const props = payload && payload.props;
  const dataField = payload && payload.data;
  if (props) {
    ['data', 'items', 'words', 'sourceData'].forEach(key => {
      if (props[key]) sources.push(props[key]);
    });
  }
  if (dataField) {
    sources.push(dataField);
  }

  const seen = new Map();
  const pushItem = (word, weight, category) => {
    if (!word) return;
    let numeric = 1;
    if (typeof weight === 'number' && Number.isFinite(weight)) {
      numeric = weight;
    } else if (typeof weight === 'string') {
      const parsed = parseFloat(weight);
      numeric = Number.isFinite(parsed) ? parsed : 1;
    }
    if (!(numeric > 0)) numeric = 1;
    const cat = (category || '').toString().toLowerCase();
    const key = `${word}__${cat}`;
    const existing = seen.get(key);
    const payloadItem = { word: String(word), weight: numeric, category: cat };
    if (!existing || numeric > existing.weight) {
      seen.set(key, payloadItem);
    }
  };

  const consume = (raw) => {
    if (!raw) return;
    if (Array.isArray(raw)) {
      raw.forEach(item => {
        if (!item) return;
        if (Array.isArray(item)) {
          pushItem(item[0], item[1], item[2]);
        } else if (typeof item === 'object') {
          pushItem(item.word || item.text || item.label, item.weight, item.category);
        } else if (typeof item === 'string') {
          pushItem(item, 1, '');
        }
      });
    } else if (typeof raw === 'object') {
      Object.entries(raw).forEach(([word, weight]) => pushItem(word, weight, ''));
    }
  };

  sources.forEach(consume);

  const items = Array.from(seen.values());
  items.sort((a, b) => (b.weight || 0) - (a.weight || 0));
  return items.slice(0, 150);
}

function wordcloudColor(category) {
  const key = typeof category === 'string' ? category.toLowerCase() : '';
  const palette = resolveWordcloudTheme();
  const base = WORDCLOUD_CATEGORY_COLORS[key] || palette.accent || palette.secondary || '#334155';
  return liftDarkColor(base);
}

function renderWordCloudFallback(canvas, items, reason) {
  const card = canvas.closest('.chart-card') || canvas.parentElement;
  if (!card) return;
  const wrapper = canvas.parentElement && canvas.parentElement.classList && canvas.parentElement.classList.contains('chart-container')
    ? canvas.parentElement
    : null;
  if (wrapper) {
    wrapper.style.display = 'none';
  } else {
    canvas.style.display = 'none';
  }
  let fallback = card.querySelector('.chart-fallback[data-dynamic="true"]');
  if (!fallback) {
    fallback = card.querySelector('.chart-fallback');
  }
  if (!fallback) {
    fallback = document.createElement('div');
    card.appendChild(fallback);
  }
  fallback.className = 'chart-fallback wordcloud-fallback';
  fallback.setAttribute('data-dynamic', 'true');
  fallback.style.display = 'block';
  fallback.innerHTML = '';
  card.setAttribute('data-chart-state', 'fallback');
  const buildBadge = (item, maxWeight) => {
    const badge = document.createElement('span');
    badge.className = 'wordcloud-badge';
    const clampedWeight = Math.max(0.5, (item.weight || 1));
    const normalized = Math.min(1, clampedWeight / (maxWeight || 1));
    const fontSize = 0.85 + normalized * 0.9;
    badge.style.fontSize = `${fontSize}rem`;
    badge.style.background = `linear-gradient(135deg, ${lightenColor(wordcloudColor(item.category), 0.05)} 0%, ${lightenColor(wordcloudColor(item.category), 0.15)} 100%)`;
    badge.style.borderColor = lightenColor(wordcloudColor(item.category), 0.25);
    badge.textContent = item.word;
    if (item.weight !== undefined && item.weight !== null) {
      const meta = document.createElement('small');
      meta.textContent = item.weight >= 0 && item.weight <= 1.5
        ? `${(item.weight * 100).toFixed(0)}%`
        : item.weight.toFixed(1).replace(/\.0+$/, '').replace(/0+$/, '').replace(/\.$/, '');
      badge.appendChild(meta);
    }
    return badge;
  };

  if (reason) {
    const notice = document.createElement('p');
    notice.className = 'chart-fallback__notice';
    notice.textContent = `词云未能渲染${reason ? `(${reason})` : ''},已展示关键词列表。`;
    fallback.appendChild(notice);
  }
  if (!items || !items.length) {
    const empty = document.createElement('p');
    empty.textContent = '暂无可用数据。';
    fallback.appendChild(empty);
    return;
  }
  const badges = document.createElement('div');
  badges.className = 'wordcloud-badges';
  const maxWeight = items.reduce((max, item) => Math.max(max, item.weight || 0), 1);
  items.forEach(item => {
    badges.appendChild(buildBadge(item, maxWeight));
  });
  fallback.appendChild(badges);
}

function renderWordCloud(canvas, payload, skipRegistry) {
  const items = normalizeWordcloudItems(payload);
  const card = canvas.closest('.chart-card') || canvas.parentElement;
  const container = canvas.parentElement && canvas.parentElement.classList && canvas.parentElement.classList.contains('chart-container')
    ? canvas.parentElement
    : null;
  if (!items.length) {
    renderWordCloudFallback(canvas, items, '无有效数据');
    return;
  }
  if (typeof WordCloud === 'undefined') {
    renderWordCloudFallback(canvas, items, '词云依赖未加载');
    return;
  }
  const theme = resolveWordcloudTheme();
  const dpr = Math.max(1, window.devicePixelRatio || 1);
  const width = Math.max(260, (container ? container.clientWidth : canvas.clientWidth || canvas.width || 320));
  const height = Math.max(120, Math.round(width / 5)); // 5:1 宽高比
  canvas.width = Math.round(width * dpr);
  canvas.height = Math.round(height * dpr);
  canvas.style.width = `${width}px`;
  canvas.style.height = `${height}px`;
  canvas.style.backgroundColor = 'transparent';

  const resolveBgColor = () => {
    const cardEl = card || container || document.body;
    const style = getComputedStyle(cardEl);
    const tokens = ['--card-bg', '--panel-bg', '--paper-bg', '--bg', '--background', '--page-bg'];
    for (const key of tokens) {
      const val = style.getPropertyValue(key);
      if (val && val.trim() && val.trim() !== 'transparent') return val.trim();
    }
    if (style.backgroundColor && style.backgroundColor !== 'rgba(0, 0, 0, 0)') return style.backgroundColor;
    const bodyStyle = getComputedStyle(document.body);
    for (const key of tokens) {
      const val = bodyStyle.getPropertyValue(key);
      if (val && val.trim() && val.trim() !== 'transparent') return val.trim();
    }
    if (bodyStyle.backgroundColor && bodyStyle.backgroundColor !== 'rgba(0, 0, 0, 0)') {
      return bodyStyle.backgroundColor;
    }
    return 'transparent';
  };
  const bgColor = resolveBgColor() || theme.cardBg || 'transparent';

  const maxWeight = items.reduce((max, item) => Math.max(max, item.weight || 0), 0) || 1;
  const weightLookup = new Map();
  const categoryLookup = new Map();
  items.forEach(it => {
    weightLookup.set(it.word, it.weight || 1);
    categoryLookup.set(it.word, it.category || '');
  });
  const list = items.map(item => [item.word, item.weight && item.weight > 0 ? item.weight : 1]);
  try {
    WordCloud(canvas, {
      list,
      gridSize: Math.max(3, Math.floor(Math.sqrt(canvas.width * canvas.height) / 170)),
      weightFactor: (val) => {
        const normalized = Math.max(0, val) / maxWeight;
        const cap = Math.min(width, height);
        const base = Math.max(9, cap / 5.5);
        const size = base * (0.8 + normalized * 1.3);
        return size * dpr;
      },
      color: (word) => {
        const w = weightLookup.get(word) || 1;
        const ratio = Math.max(0, Math.min(1, w / (maxWeight || 1)));
        const category = categoryLookup.get(word) || '';
        const base = wordcloudColor(category);
        const target = theme.isDark ? '#ffffff' : (theme.text || '#111827');
        const mixAmount = theme.isDark
          ? 0.28 + (1 - ratio) * 0.22
          : 0.12 + (1 - ratio) * 0.35;
        const mixed = mixColors(base, target, mixAmount);
        return ensureAlpha(mixed || base, theme.isDark ? 0.95 : 1);
      },
      rotateRatio: 0,
      rotationSteps: 0,
      shuffle: false,
      shrinkToFit: true,
      drawOutOfBound: false,
      shape: 'square',
      ellipticity: 0.45,
      clearCanvas: true,
      backgroundColor: bgColor
    });
    if (container) {
      container.style.display = '';
      container.style.minHeight = `${height}px`;
      container.style.background = 'transparent';
    }
    const fallback = card && card.querySelector('.chart-fallback');
    if (fallback) {
      fallback.style.display = 'none';
    }
    card && card.removeAttribute('data-chart-state');
    if (!skipRegistry) {
      wordCloudRegistry.set(canvas, () => renderWordCloud(canvas, payload, true));
    }
  } catch (err) {
    console.error('WordCloud 渲染失败', err);
    renderWordCloudFallback(canvas, items, err && err.message ? err.message : '');
  }
}

function createFallbackTable(labels, datasets) {
  if (!Array.isArray(datasets) || !datasets.length) {
    return null;
  }
  const primaryDataset = datasets.find(ds => Array.isArray(ds && ds.data));
  const resolvedLabels = Array.isArray(labels) && labels.length
    ? labels
    : (primaryDataset && primaryDataset.data ? primaryDataset.data.map((_, idx) => `数据点 ${idx + 1}`) : []);
  if (!resolvedLabels.length) {
    return null;
  }
  const table = document.createElement('table');
  const thead = document.createElement('thead');
  const headRow = document.createElement('tr');
  const categoryHeader = document.createElement('th');
  categoryHeader.textContent = '类别';
  headRow.appendChild(categoryHeader);
  datasets.forEach((dataset, index) => {
    const th = document.createElement('th');
    th.textContent = dataset && dataset.label ? dataset.label : `系列${index + 1}`;
    headRow.appendChild(th);
  });
  thead.appendChild(headRow);
  table.appendChild(thead);
  const tbody = document.createElement('tbody');
  resolvedLabels.forEach((label, rowIdx) => {
    const row = document.createElement('tr');
    const labelCell = document.createElement('td');
    labelCell.textContent = label;
    row.appendChild(labelCell);
    datasets.forEach(dataset => {
      const cell = document.createElement('td');
      const series = dataset && Array.isArray(dataset.data) ? dataset.data[rowIdx] : undefined;
      if (typeof series === 'number') {
        cell.textContent = series.toLocaleString();
      } else if (series !== undefined && series !== null && series !== '') {
        cell.textContent = series;
      } else {
        cell.textContent = '—';
      }
      row.appendChild(cell);
    });
    tbody.appendChild(row);
  });
  table.appendChild(tbody);
  return table;
}

function renderChartFallback(canvas, payload, reason) {
  const card = canvas.closest('.chart-card') || canvas.parentElement;
  if (!card) return;
  clearChartDegradeNote(card);
  const wrapper = canvas.parentElement && canvas.parentElement.classList && canvas.parentElement.classList.contains('chart-container')
    ? canvas.parentElement
    : null;
  if (wrapper) {
    wrapper.style.display = 'none';
  } else {
    canvas.style.display = 'none';
  }
  let fallback = card.querySelector('.chart-fallback[data-dynamic="true"]');
  let prebuilt = false;
  if (!fallback) {
    fallback = card.querySelector('.chart-fallback');
    if (fallback) {
      prebuilt = fallback.hasAttribute('data-prebuilt');
    }
  }
  if (!fallback) {
    fallback = document.createElement('div');
    fallback.className = 'chart-fallback';
    fallback.setAttribute('data-dynamic', 'true');
    card.appendChild(fallback);
  } else if (!prebuilt) {
    fallback.innerHTML = '';
  }
  const titleFromOptions = payload && payload.props && payload.props.options &&
    payload.props.options.plugins && payload.props.options.plugins.title &&
    payload.props.options.plugins.title.text;
  const fallbackTitle = titleFromOptions ||
    (payload && payload.props && payload.props.title) ||
    (payload && payload.widgetId) ||
    canvas.getAttribute('id') ||
    '图表';
  const existingNotice = fallback.querySelector('.chart-fallback__notice');
  if (existingNotice) {
    existingNotice.remove();
  }
  const notice = document.createElement('p');
  notice.className = 'chart-fallback__notice';
  notice.textContent = `${fallbackTitle}:图表未能渲染,已展示表格数据${reason ? `(${reason})` : ''}`;
  fallback.insertBefore(notice, fallback.firstChild || null);
  if (!prebuilt) {
    const table = createFallbackTable(
      payload && payload.data && payload.data.labels,
      payload && payload.data && payload.data.datasets
    );
    if (table) {
      fallback.appendChild(table);
    }
  }
  fallback.style.display = 'block';
  card.setAttribute('data-chart-state', 'fallback');
}

function buildChartOptions(payload) {
  const rawLegend = payload && payload.props ? payload.props.legend : undefined;
  let legendConfig;
  if (isPlainObject(rawLegend)) {
    legendConfig = mergeOptions({
      display: rawLegend.display !== false,
      position: rawLegend.position || 'top'
    }, rawLegend);
  } else {
    legendConfig = {
      display: rawLegend === 'hidden' ? false : true,
      position: typeof rawLegend === 'string' ? rawLegend : 'top'
    };
  }
  const baseOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: legendConfig
    }
  };
  if (payload && payload.props && payload.props.title) {
    baseOptions.plugins.title = {
      display: true,
      text: payload.props.title
    };
  }
  const overrideOptions = payload && payload.props && payload.props.options;
  return mergeOptions(baseOptions, overrideOptions);
}

function validateChartData(payload, type) {
  /**
   * 前端验证图表数据
   * 返回: { valid: boolean, errors: string[] }
   */
  const errors = [];

  if (!payload || typeof payload !== 'object') {
    errors.push('无效的payload');
    return { valid: false, errors };
  }

  const data = payload.data;
  if (!data || typeof data !== 'object') {
    errors.push('缺少data字段');
    return { valid: false, errors };
  }

  // 特殊图表类型(scatter, bubble)
  const specialTypes = { 'scatter': true, 'bubble': true };
  if (specialTypes[type]) {
    // 这些类型需要特殊的数据格式 {x, y} 或 {x, y, r}
    // 跳过标准验证
    return { valid: true, errors };
  }

  // 标准图表类型验证
  const datasets = data.datasets;
  if (!Array.isArray(datasets)) {
    errors.push('datasets必须是数组');
    return { valid: false, errors };
  }

  if (datasets.length === 0) {
    errors.push('datasets数组为空');
    return { valid: false, errors };
  }

  // 验证每个dataset
  for (let i = 0; i < datasets.length; i++) {
    const dataset = datasets[i];
    if (!dataset || typeof dataset !== 'object') {
      errors.push(`datasets[${i}]不是对象`);
      continue;
    }

    if (!Array.isArray(dataset.data)) {
      errors.push(`datasets[${i}].data不是数组`);
    } else if (dataset.data.length === 0) {
      errors.push(`datasets[${i}].data为空`);
    }
  }

  // 需要labels的图表类型
  const labelRequiredTypes = {
    'line': true, 'bar': true, 'radar': true,
    'polarArea': true, 'pie': true, 'doughnut': true
  };

  if (labelRequiredTypes[type]) {
    const labels = data.labels;
    if (!Array.isArray(labels)) {
      errors.push('缺少labels数组');
    } else if (labels.length === 0) {
      errors.push('labels数组为空');
    }
  }

  return {
    valid: errors.length === 0,
    errors
  };
}

function instantiateChart(ctx, payload, optionsTemplate, type) {
  if (!ctx) {
    return null;
  }
  if (ctx.canvas && typeof Chart !== 'undefined' && typeof Chart.getChart === 'function') {
    const existing = Chart.getChart(ctx.canvas);
    if (existing) {
      existing.destroy();
    }
  }
  const data = cloneDeep(payload && payload.data ? payload.data : {});
  const config = {
    type,
    data,
    options: cloneDeep(optionsTemplate)
  };
  return new Chart(ctx, config);
}

function debounce(fn, wait) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(null, args), wait || 200);
  };
}

function hydrateCharts() {
  document.querySelectorAll('canvas[data-config-id]').forEach(canvas => {
    const configScript = document.getElementById(canvas.dataset.configId);
    if (!configScript) return;
    let payload;
    try {
      payload = JSON.parse(configScript.textContent);
    } catch (err) {
      console.error('Widget JSON 解析失败', err);
      renderChartFallback(canvas, { widgetId: canvas.dataset.configId }, '配置解析失败');
      return;
    }
    if (isWordCloudWidget(payload)) {
      renderWordCloud(canvas, payload);
      return;
    }
    if (typeof Chart === 'undefined') {
      renderChartFallback(canvas, payload, 'Chart.js 未加载');
      return;
    }
    const chartTypes = resolveChartTypes(payload);
    const ctx = canvas.getContext('2d');
    if (!ctx) {
      renderChartFallback(canvas, payload, 'Canvas 初始化失败');
      return;
    }

    // 前端数据验证
    const desiredType = chartTypes[0];
    const card = canvas.closest('.chart-card') || canvas.parentElement;
    const colorAdjustments = normalizeDatasetColors(payload, desiredType);
    if (colorAdjustments.length && card) {
      card.setAttribute('data-chart-color-fixes', colorAdjustments.join(' | '));
    }
    const validation = validateChartData(payload, desiredType);
    if (!validation.valid) {
      console.warn('图表数据验证失败:', validation.errors);
      // 验证失败但仍然尝试渲染,因为可能会降级成功
    }

    const optionsTemplate = buildChartOptions(payload);
    let chartInstance = null;
    let selectedType = null;
    let lastError;
    for (const type of chartTypes) {
      try {
        chartInstance = instantiateChart(ctx, payload, optionsTemplate, type);
        selectedType = type;
        break;
      } catch (err) {
        lastError = err;
        console.error('图表渲染失败', type, err);
      }
    }
    if (chartInstance) {
      chartRegistry.push(chartInstance);
      try {
        applyChartTheme(chartInstance);
      } catch (err) {
        console.error('主题同步失败', selectedType || desiredType || payload && payload.widgetType || 'chart', err);
      }
      if (selectedType && selectedType !== desiredType) {
        setChartDegradeNote(card, desiredType, selectedType);
      } else {
        clearChartDegradeNote(card);
      }
    } else {
      const reason = lastError && lastError.message ? lastError.message : '';
      renderChartFallback(canvas, payload, reason);
    }
  });
}

function getExportOverlayParts() {
  const overlay = document.getElementById('export-overlay');
  if (!overlay) {
    return null;
  }
  return {
    overlay,
    status: overlay.querySelector('.export-status')
  };
}

function showExportOverlay(message) {
  const parts = getExportOverlayParts();
  if (!parts) return;
  if (message && parts.status) {
    parts.status.textContent = message;
  }
  parts.overlay.classList.add('active');
  document.body.classList.add('exporting');
}

function updateExportOverlay(message) {
  if (!message) return;
  const parts = getExportOverlayParts();
  if (parts && parts.status) {
    parts.status.textContent = message;
  }
}

function hideExportOverlay(delay) {
  const parts = getExportOverlayParts();
  if (!parts) return;
  const close = () => {
    parts.overlay.classList.remove('active');
    document.body.classList.remove('exporting');
  };
  if (delay && delay > 0) {
    setTimeout(close, delay);
  } else {
    close();
  }
}

// exportPdf已移除
function exportPdf() {
  const target = document.querySelector('main');
  if (!target || typeof jspdf === 'undefined' || typeof jspdf.jsPDF !== 'function') {
    alert('PDF导出依赖未就绪');
    return;
  }
  const exportBtn = document.getElementById('export-btn');
  if (exportBtn) {
    exportBtn.disabled = true;
  }
  showExportOverlay('正在导出PDF,请稍候...');
  document.body.classList.add('exporting');
  const pdf = new jspdf.jsPDF('p', 'mm', 'a4');
  try {
    if (window.pdfFontData) {
      pdf.addFileToVFS('SourceHanSerifSC-Medium.ttf', window.pdfFontData);
      pdf.addFont('SourceHanSerifSC-Medium.ttf', 'SourceHanSerif', 'normal');
      pdf.setFont('SourceHanSerif');
      console.log('PDF字体已成功加载');
    } else {
      console.warn('PDF字体数据未找到,将使用默认字体');
    }
  } catch (err) {
    console.warn('Custom PDF font setup failed, fallback to default', err);
  }
  const pageWidth = pdf.internal.pageSize.getWidth();
  const pxWidth = Math.max(
    target.scrollWidth,
    document.documentElement.scrollWidth,
    Math.round(pageWidth * 3.78)
  );
  const restoreButton = () => {
    if (exportBtn) {
      exportBtn.disabled = false;
    }
    document.body.classList.remove('exporting');
  };
  let renderTask;
  try {
    // force charts to rerender at full width before capture
    chartRegistry.forEach(chart => {
      if (chart && typeof chart.resize === 'function') {
        chart.resize();
      }
    });
    wordCloudRegistry.forEach(fn => {
      if (typeof fn === 'function') {
        try {
          fn();
        } catch (err) {
          console.error('词云重新渲染失败', err);
        }
      }
    });
    renderTask = pdf.html(target, {
      x: 8,
      y: 12,
      width: pageWidth - 16,
      margin: [12, 12, 20, 12],
      autoPaging: 'text',
      windowWidth: pxWidth,
      html2canvas: {
        scale: Math.min(1.5, Math.max(1.0, pageWidth / (target.clientWidth || pageWidth))),
        useCORS: true,
        scrollX: 0,
        scrollY: -window.scrollY,
        logging: false,
        allowTaint: true,
        backgroundColor: '#ffffff'
      },
      pagebreak: {
        mode: ['css', 'legacy'],
        avoid: [
          '.chapter > *',
          '.callout',
          '.chart-card',
          '.table-wrap',
          '.kpi-grid',
          '.hero-section'
        ],
        before: '.chapter-divider'
      },
      callback: (doc) => doc.save('report.pdf')
    });
  } catch (err) {
    console.error('PDF 导出失败', err);
    updateExportOverlay('导出失败,请稍后重试');
    hideExportOverlay(1200);
    restoreButton();
    alert('PDF导出失败,请稍后重试');
    return;
  }
  if (renderTask && typeof renderTask.then === 'function') {
    renderTask.then(() => {
      updateExportOverlay('导出完成,正在保存...');
      hideExportOverlay(800);
      restoreButton();
    }).catch(err => {
      console.error('PDF 导出失败', err);
      updateExportOverlay('导出失败,请稍后重试');
      hideExportOverlay(1200);
      restoreButton();
      alert('PDF导出失败,请稍后重试');
    });
  } else {
    hideExportOverlay();
    restoreButton();
  }
}

document.addEventListener('DOMContentLoaded', () => {
  const rerenderWordclouds = debounce(() => {
    wordCloudRegistry.forEach(fn => {
      if (typeof fn === 'function') {
        fn();
      }
    });
  }, 260);
  const themeBtn = document.getElementById('theme-toggle');
  if (themeBtn) {
    themeBtn.addEventListener('change', (e) => {
      if (e.detail === 'dark') {
        document.body.classList.add('dark-mode');
      } else {
        document.body.classList.remove('dark-mode');
      }
      chartRegistry.forEach(applyChartTheme);
      rerenderWordclouds();
    });
  }
  const printBtn = document.getElementById('print-btn');
  if (printBtn) {
    printBtn.addEventListener('click', () => window.print());
  }
  const exportBtn = document.getElementById('export-btn');
  if (exportBtn) {
    exportBtn.addEventListener('click', exportPdf);
  }
  window.addEventListener('resize', rerenderWordclouds);
  hydrateCharts();
});
</script>
""".strip()


__all__ = ["HTMLRenderer"]