image_generator.py 101 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
#!/usr/bin/env python3
"""
Gemini Image Generator App - PySide6 Version
Modern GUI application for generating images using Google's Gemini API
"""

from PySide6.QtWidgets import (
    QApplication, QMainWindow, QDialog, QWidget,
    QVBoxLayout, QHBoxLayout, QFormLayout, QGridLayout,
    QLabel, QLineEdit, QPushButton, QCheckBox, QTextEdit,
    QComboBox, QScrollArea, QGroupBox, QFileDialog, QMessageBox,
    QListWidget, QListWidgetItem, QTabWidget, QSplitter,
    QMenu, QProgressBar
)
from PySide6.QtCore import Qt, QThread, Signal, QSize, QTimer, QMimeData
from PySide6.QtGui import QPixmap, QFont, QIcon, QDesktopServices, QAction, QImage, QDragEnterEvent, QDropEvent
from PySide6.QtCore import QUrl

import base64
import io
import json
import os
import sys
import shutil
import tempfile
import platform
import logging
from pathlib import Path
from google import genai
from google.genai import types
import hashlib
import pymysql
import socket
import requests
from datetime import datetime
from dataclasses import dataclass, asdict
from typing import List, Optional, Dict, Any


def init_logging(log_level=logging.INFO):
    """
    初始化简单的日志系统
    创建logs目录并配置基本的文件日志记录
    """
    try:
        # 获取脚本所在目录
        script_dir = Path(__file__).parent

        # 尝试加载日志配置
        config_path = script_dir / "config.json"
        logging_config = {
            "enabled": True,
            "level": "INFO",
            "log_to_console": True
        }

        if config_path.exists():
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    logging_config = config.get("logging_config", logging_config)
            except Exception as e:
                print(f"加载日志配置失败: {e}")

        # 如果日志被禁用,直接返回成功
        if not logging_config.get("enabled", True):
            print("日志系统已禁用")
            return True

        # 解析日志级别
        level_str = logging_config.get("level", "INFO").upper()
        log_level = getattr(logging, level_str, logging.INFO)

        # 创建logs目录
        logs_dir = script_dir / "logs"
        logs_dir.mkdir(exist_ok=True)

        # 配置日志文件路径
        log_file = logs_dir / "app.log"

        # 配置日志格式
        log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

        # 配置处理器
        handlers = [logging.FileHandler(log_file, encoding='utf-8')]
        if logging_config.get("log_to_console", True):
            handlers.append(logging.StreamHandler())

        # 配置日志系统
        logging.basicConfig(
            level=log_level,
            format=log_format,
            handlers=handlers,
            force=True  # 强制重新配置
        )

        logging.info(f"日志系统初始化完成 - 级别: {level_str}, 文件: {log_file}")
        return True

    except Exception as e:
        print(f"日志系统初始化失败: {e}")
        return False


def hash_password(password: str) -> str:
    """使用 SHA256 哈希密码"""
    return hashlib.sha256(password.encode('utf-8')).hexdigest()


class DatabaseManager:
    """数据库连接管理类"""

    def __init__(self, db_config):
        self.config = db_config
        self.logger = logging.getLogger(__name__)

    def authenticate(self, username, password):
        """
        验证用户凭证
        返回: (success: bool, message: str)
        """
        try:
            self.logger.info(f"开始用户认证: {username}")

            # 计算密码哈希
            password_hash = hash_password(password)

            # 连接数据库
            self.logger.debug(f"连接数据库: {self.config['host']}:{self.config.get('port', 3306)}")
            conn = pymysql.connect(
                host=self.config['host'],
                port=self.config.get('port', 3306),
                user=self.config['user'],
                password=self.config['password'],
                database=self.config['database'],
                connect_timeout=5
            )

            try:
                with conn.cursor() as cursor:
                    # 使用参数化查询防止 SQL 注入
                    sql = f"SELECT * FROM {self.config['table']} WHERE user_name=%s AND passwd=%s AND status='active'"
                    cursor.execute(sql, (username, password_hash))
                    result = cursor.fetchone()

                    if result:
                        self.logger.info(f"用户认证成功: {username}")
                        return True, "认证成功"
                    else:
                        self.logger.warning(f"用户认证失败: {username} - 用户名或密码错误")
                        return False, "用户名或密码错误"
            finally:
                conn.close()

        except pymysql.OperationalError as e:
            error_msg = "无法连接到服务器,请检查网络连接"
            self.logger.error(f"数据库连接失败: {e}")
            return False, error_msg
        except Exception as e:
            error_msg = f"认证失败: {str(e)}"
            self.logger.error(f"认证过程异常: {e}")
            return False, error_msg


@dataclass
class HistoryItem:
    """历史记录项数据结构"""
    timestamp: str
    prompt: str
    generated_image_path: Path
    reference_image_paths: List[Path]
    aspect_ratio: str
    image_size: str
    model: str
    created_at: datetime

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'timestamp': self.timestamp,
            'prompt': self.prompt,
            'generated_image_path': str(self.generated_image_path),
            'reference_image_paths': [str(p) for p in self.reference_image_paths],
            'aspect_ratio': self.aspect_ratio,
            'image_size': self.image_size,
            'model': self.model,
            'created_at': self.created_at.isoformat()
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'HistoryItem':
        """从字典创建实例"""
        return cls(
            timestamp=data['timestamp'],
            prompt=data['prompt'],
            generated_image_path=Path(data['generated_image_path']),
            reference_image_paths=[Path(p) for p in data['reference_image_paths']],
            aspect_ratio=data['aspect_ratio'],
            image_size=data['image_size'],
            model=data['model'],
            created_at=datetime.fromisoformat(data['created_at'])
        )


def get_app_data_path() -> Path:
    """获取应用数据存储路径 - 智能选择,优先使用当前目录"""

    # 定义多个备选路径,按优先级排序
    def get_candidate_paths():
        """获取候选路径列表"""
        system = platform.system()
        candidates = []

        # 1. 优先尝试:当前目录的images文件夹
        if getattr(sys, 'frozen', False):
            # 打包环境:使用可执行文件所在目录
            candidates.append(Path(sys.executable).parent / "images")
        else:
            # 开发环境:使用脚本所在目录
            candidates.append(Path(__file__).parent / "images")

        # 2. 备选方案:用户目录
        if system == "Darwin":  # macOS
            candidates.append(Path.home() / "Library/Application Support/ZB100ImageGenerator/images")
            candidates.append(Path.home() / "Documents/ZB100ImageGenerator/images")
        elif system == "Windows":
            candidates.append(Path(os.environ.get("APPDATA", "")) / "ZB100ImageGenerator/images")
            candidates.append(Path.home() / "Documents/ZB100ImageGenerator/images")
        else:  # Linux
            candidates.append(Path.home() / ".config/zb100imagegenerator/images")
            candidates.append(Path.home() / "Documents/ZB100ImageGenerator/images")

        return candidates

    # 测试路径可用性
    def test_path_write_access(path: Path) -> bool:
        """测试路径是否有写入权限"""
        try:
            # 尝试创建目录
            path.mkdir(parents=True, exist_ok=True)

            # 测试写入权限
            test_file = path / ".write_test"
            test_file.write_text("test")
            test_file.unlink()  # 删除测试文件

            return True
        except (PermissionError, OSError) as e:
            print(f"路径 {path} 无写入权限: {e}")
            return False
        except Exception as e:
            print(f"路径 {path} 测试失败: {e}")
            return False

    # 按优先级测试每个候选路径
    candidates = get_candidate_paths()

    for path in candidates:
        if test_path_write_access(path):
            print(f"使用图片存储路径: {path}")
            return path

    # 如果所有路径都失败,使用最后的备选方案
    fallback_path = get_candidate_paths()[0]  # 使用第一个候选路径
    try:
        fallback_path.mkdir(parents=True, exist_ok=True)
        print(f"使用备选路径: {fallback_path}")
        return fallback_path
    except Exception as e:
        print(f"警告: 无法创建存储路径,将在当前目录操作: {e}")
        return Path.cwd() / "images"


def save_png_with_validation(file_path: str, image_bytes: bytes) -> bool:
    """使用Pillow验证并重写PNG文件,确保格式正确性

    Args:
        file_path: 保存文件路径
        image_bytes: 图像字节数据

    Returns:
        bool: True表示使用Pillow成功处理,False表示回退到原始方法
    """
    try:
        from PIL import Image
        import io

        # 使用Pillow打开图像数据
        with Image.open(io.BytesIO(image_bytes)) as img:
            # 检查是否实际是JPEG但伪装成PNG的情况
            file_format = img.format
            if file_format == 'JPEG':
                logger = logging.getLogger(__name__)
                logger.info(f"检测到伪装PNG的JPEG文件,实际格式: {file_format}")

            # 根据文件路径的扩展名决定保存格式
            save_format = 'PNG' if file_path.lower().endswith('.png') else 'JPEG'

            # 如果检测到的格式与目标格式不符,进行真正的转换
            if file_format and file_format != save_format:
                logger = logging.getLogger(__name__)
                logger.info(f"执行格式转换: {file_format} -> {save_format}")

                # 如果目标格式是PNG,确保使用RGBA模式以支持透明度
                if save_format == 'PNG':
                    if img.mode not in ['RGBA', 'RGB', 'L']:
                        if img.mode == 'P':
                            img = img.convert('RGBA')
                        elif img.mode == 'LA':
                            img = img.convert('RGBA')
                        else:
                            img = img.convert('RGBA')
                elif save_format == 'JPEG':
                    if img.mode in ['RGBA', 'P']:
                        img = img.convert('RGB')
                    elif img.mode == 'L':
                        img = img.convert('RGB')

            # 保存图片为指定格式
            img.save(file_path, save_format, optimize=True)

        logger = logging.getLogger(__name__)
        logger.info(f"图片格式验证成功: {file_path}, 保存格式: {save_format}")
        return True

    except ImportError:
        # Pillow不可用
        logger = logging.getLogger(__name__)
        logger.warning("Pillow库不可用,使用原始保存方法")
        return False

    except Exception as e:
        # Pillow处理失败,回退到原始方法
        logger = logging.getLogger(__name__)
        logger.warning(f"Pillow处理失败,使用原始保存方法: {e}")
        return False


class HistoryManager:
    """历史记录管理器"""

    def __init__(self, base_path: Optional[Path] = None):
        """初始化历史记录管理器

        Args:
            base_path: 历史记录存储基础路径,默认使用get_app_data_path()的结果
        """
        self.logger = logging.getLogger(__name__)
        self.base_path = base_path or get_app_data_path()
        self.base_path.mkdir(parents=True, exist_ok=True)
        self.history_index_file = self.base_path / "history_index.json"
        self.max_history_count = 100  # 默认最大历史记录数量

        self.logger.debug(f"历史记录管理器初始化完成,存储路径: {self.base_path}")

    def save_generation(self, image_bytes: bytes, prompt: str, reference_images: List[bytes],
                        aspect_ratio: str, image_size: str, model: str) -> str:
        """保存生成的图片到历史记录

        Args:
            image_bytes: 生成的图片字节数据
            prompt: 使用的提示词
            reference_images: 参考图片字节数据列表
            aspect_ratio: 宽高比
            image_size: 图片尺寸
            model: 使用的模型

        Returns:
            历史记录的时间戳
        """
        self.logger.info(f"开始保存历史记录 - 模型: {model}, 尺寸: {image_size}")

        # 生成时间戳目录
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        record_dir = self.base_path / timestamp
        record_dir.mkdir(exist_ok=True)

        # 保存生成的图片 - 使用PNG格式验证
        generated_image_path = record_dir / "generated.png"
        if not save_png_with_validation(str(generated_image_path), image_bytes):
            # Pillow处理失败,回退到原始方法
            with open(generated_image_path, 'wb') as f:
                f.write(image_bytes)
            self.logger.warning(f"使用原始保存方法: {generated_image_path}")

        # 保存参考图片 - 使用PNG格式验证
        reference_image_paths = []
        for i, ref_img_bytes in enumerate(reference_images):
            ref_path = record_dir / f"reference_{i + 1}.png"
            if not save_png_with_validation(str(ref_path), ref_img_bytes):
                # Pillow处理失败,回退到原始方法
                with open(ref_path, 'wb') as f:
                    f.write(ref_img_bytes)
                self.logger.warning(f"使用原始保存方法: {ref_path}")
            reference_image_paths.append(ref_path)

        # 保存元数据
        metadata = {
            'timestamp': timestamp,
            'prompt': prompt,
            'aspect_ratio': aspect_ratio,
            'image_size': image_size,
            'model': model,
            'created_at': datetime.now().isoformat()
        }

        metadata_path = record_dir / "metadata.json"
        with open(metadata_path, 'w', encoding='utf-8') as f:
            json.dump(metadata, f, ensure_ascii=False, indent=2)

        # 更新历史记录索引
        history_item = HistoryItem(
            timestamp=timestamp,
            prompt=prompt,
            generated_image_path=generated_image_path,
            reference_image_paths=reference_image_paths,
            aspect_ratio=aspect_ratio,
            image_size=image_size,
            model=model,
            created_at=datetime.now()
        )

        self._update_history_index(history_item)

        # 清理旧记录
        self._cleanup_old_records()

        return timestamp

    def load_history_index(self) -> List[HistoryItem]:
        """加载历史记录索引

        Returns:
            历史记录项列表,按时间戳倒序排列
        """
        if not self.history_index_file.exists():
            return []

        try:
            with open(self.history_index_file, 'r', encoding='utf-8') as f:
                data = json.load(f)

            history_items = [HistoryItem.from_dict(item) for item in data]
            # 按时间戳倒序排列
            history_items.sort(key=lambda x: x.timestamp, reverse=True)
            return history_items
        except Exception as e:
            print(f"加载历史记录索引失败: {e}")
            return []

    def get_history_item(self, timestamp: str) -> Optional[HistoryItem]:
        """获取指定时间戳的历史记录项

        Args:
            timestamp: 时间戳

        Returns:
            历史记录项,如果不存在则返回None
        """
        history_items = self.load_history_index()
        for item in history_items:
            if item.timestamp == timestamp:
                return item
        return None

    def delete_history_item(self, timestamp: str) -> bool:
        """删除指定的历史记录

        Args:
            timestamp: 要删除的时间戳

        Returns:
            删除是否成功
        """
        try:
            # 删除文件目录
            record_dir = self.base_path / timestamp
            if record_dir.exists():
                shutil.rmtree(record_dir)

            # 更新索引文件
            history_items = self.load_history_index()
            history_items = [item for item in history_items if item.timestamp != timestamp]
            self._save_history_index(history_items)

            return True
        except Exception as e:
            print(f"删除历史记录失败: {e}")
            return False

    def _update_history_index(self, history_item: HistoryItem):
        """更新历史记录索引

        Args:
            history_item: 要添加的历史记录项
        """
        history_items = self.load_history_index()

        # 检查是否已存在相同时间戳的记录,如果存在则替换
        history_items = [item for item in history_items if item.timestamp != history_item.timestamp]
        history_items.insert(0, history_item)  # 插入到开头

        self._save_history_index(history_items)

    def _save_history_index(self, history_items: List[HistoryItem]):
        """保存历史记录索引到文件

        Args:
            history_items: 历史记录项列表
        """
        try:
            data = [item.to_dict() for item in history_items]
            with open(self.history_index_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存历史记录索引失败: {e}")

    def _cleanup_old_records(self):
        """清理旧的历史记录,保持最大数量限制"""
        history_items = self.load_history_index()
        if len(history_items) > self.max_history_count:
            # 保留最新的记录
            items_to_keep = history_items[:self.max_history_count]
            items_to_remove = history_items[self.max_history_count:]

            # 删除多余记录的文件
            for item in items_to_remove:
                record_dir = self.base_path / item.timestamp
                if record_dir.exists():
                    try:
                        shutil.rmtree(record_dir)
                    except Exception as e:
                        print(f"删除旧历史记录失败 {item.timestamp}: {e}")

            # 更新索引文件
            self._save_history_index(items_to_keep)


class LoginDialog(QDialog):
    """Qt-based login dialog"""

    def __init__(self, db_config, last_user="", saved_password_hash=""):
        super().__init__()
        self.db_config = db_config
        self.last_user = last_user
        self.saved_password_hash = saved_password_hash

        self.success = False
        self.authenticated_user = ""
        self.password_changed = False
        self.current_password_hash = ""

        self.set_window_icon()
        self.setup_ui()
        self.apply_styles()

    def set_window_icon(self):
        """Set window icon based on platform"""
        try:
            icon_path = None

            if getattr(sys, 'frozen', False):
                # Running as compiled executable
                if platform.system() == 'Windows':
                    icon_path = os.path.join(sys._MEIPASS, 'zb100_windows.ico')
                elif platform.system() == 'Darwin':
                    icon_path = os.path.join(sys._MEIPASS, 'zb100_mac.icns')
            else:
                # Running as script
                if platform.system() == 'Windows':
                    icon_path = 'zb100_windows.ico'
                elif platform.system() == 'Darwin':
                    icon_path = 'zb100_mac.icns'

            if icon_path and os.path.exists(icon_path):
                app_icon = QIcon(icon_path)
                if not app_icon.isNull():
                    self.setWindowIcon(app_icon)
                else:
                    print(f"警告:图标文件无效: {icon_path}")
        except Exception as e:
            print(f"设置窗口图标失败: {e}")

    def setup_ui(self):
        """Build login dialog UI"""
        self.setWindowTitle("登录 - 珠宝壹佰图像生成器")
        self.setFixedSize(400, 400)

        # Main layout
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(40, 40, 40, 40)
        main_layout.setSpacing(20)

        # Title
        title_label = QLabel("登录")
        title_label.setObjectName("title")
        title_label.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(title_label)

        main_layout.addSpacing(10)

        # Username field
        username_label = QLabel("用户名")
        username_label.setObjectName("field_label")

        main_layout.addWidget(username_label)

        self.username_entry = QLineEdit()
        self.username_entry.setText(self.last_user)
        self.username_entry.setFixedHeight(40)
        main_layout.addWidget(self.username_entry)

        main_layout.addSpacing(10)

        # Password field
        password_label = QLabel("密码")
        password_label.setObjectName("field_label")
        main_layout.addWidget(password_label)

        self.password_entry = QLineEdit()
        self.password_entry.setEchoMode(QLineEdit.Password)
        self.password_entry.setFixedHeight(40)

        # Handle saved password placeholder
        if self.saved_password_hash:
            self.password_entry.setPlaceholderText("••••••••")
            self.password_entry.setStyleSheet("QLineEdit { color: #999999; }")

        self.password_entry.textChanged.connect(self.on_password_change)
        self.password_entry.returnPressed.connect(self.on_login)

        main_layout.addWidget(self.password_entry)

        # Checkboxes
        checkbox_layout = QHBoxLayout()
        self.remember_user_check = QCheckBox("记住用户名")
        self.remember_user_check.setChecked(bool(self.last_user))
        checkbox_layout.addWidget(self.remember_user_check)

        self.remember_password_check = QCheckBox("记住密码")
        self.remember_password_check.setChecked(bool(self.saved_password_hash))
        checkbox_layout.addWidget(self.remember_password_check)

        checkbox_layout.addStretch()
        main_layout.addLayout(checkbox_layout)

        # Login button
        self.login_button = QPushButton("登录")
        self.login_button.setObjectName("login_button")
        self.login_button.setFixedHeight(40)
        self.login_button.clicked.connect(self.on_login)
        main_layout.addWidget(self.login_button)

        # Error label
        self.error_label = QLabel("")
        self.error_label.setObjectName("error_label")
        self.error_label.setAlignment(Qt.AlignCenter)
        self.error_label.setWordWrap(True)
        main_layout.addWidget(self.error_label)

        main_layout.addStretch()

        self.setLayout(main_layout)

        # Set focus
        if self.last_user:
            self.password_entry.setFocus()
        else:
            self.username_entry.setFocus()

    def apply_styles(self):
        """Apply QSS stylesheet"""
        self.setStyleSheet("""
            QDialog {
                background-color: #ffffff;
            }
            QLabel#title {
                font-size: 20pt;
                font-weight: bold;
                color: #1d1d1f;
            }
            QLabel#field_label {
                font-size: 10pt;
                color: #666666;
            }
            QLineEdit {
                padding: 8px;
                border: 1px solid #e5e5e5;
                border-radius: 4px;
                background-color: #fafafa;
                font-size: 11pt;
                color: #000000;
            }
            QLineEdit:focus {
                border: 1px solid #007AFF;
            }
            QPushButton#login_button {
                background-color: #007AFF;
                color: white;
                font-size: 10pt;
                font-weight: bold;
                padding: 10px 20px;
                border: none;
                border-radius: 6px;
            }
            QPushButton#login_button:hover {
                background-color: #0051D5;
            }
            QPushButton#login_button:pressed {
                background-color: #003D99;
            }
            QPushButton#login_button:disabled {
                background-color: #cccccc;
            }
            QCheckBox {
                font-size: 9pt;
                color: #1d1d1f;
            }
            QLabel#error_label {
                color: #ff3b30;
                font-size: 9pt;
            }
        """)

    def on_password_change(self):
        """Handle password field changes"""
        if not self.password_changed and self.saved_password_hash:
            # First change - clear placeholder style
            self.password_entry.setStyleSheet("")
            self.password_changed = True

    def on_login(self):
        """Handle login button click"""
        username = self.username_entry.text().strip()
        password_input = self.password_entry.text()

        # Validate input
        if not username:
            self.show_error("请输入用户名")
            return

        # Check if password is provided or saved password exists
        if not password_input and not self.saved_password_hash:
            self.show_error("请输入密码")
            return

        # Disable button during authentication
        self.login_button.setEnabled(False)
        self.error_label.setText("正在验证...")
        self.error_label.setStyleSheet("QLabel { color: #666666; }")

        # Determine which password to use
        if not self.password_changed and self.saved_password_hash:
            password_hash = self.saved_password_hash
        else:
            password_hash = hash_password(password_input)

        # Authenticate
        try:
            conn = pymysql.connect(
                host=self.db_config['host'],
                port=self.db_config.get('port', 3306),
                user=self.db_config['user'],
                password=self.db_config['password'],
                database=self.db_config['database'],
                connect_timeout=5
            )

            try:
                with conn.cursor() as cursor:
                    sql = f"SELECT * FROM {self.db_config['table']} WHERE user_name=%s AND passwd=%s AND status='active'"
                    cursor.execute(sql, (username, password_hash))
                    result = cursor.fetchone()

                    if result:
                        self.success = True
                        self.authenticated_user = username
                        self.current_password_hash = password_hash

                        # 记录用户登录日志
                        self.log_user_login(username)

                        self.accept()  # Close dialog with success
                    else:
                        self.show_error("用户名或密码错误,联系[柴进]重置密码")
                        self.password_entry.clear()
                        self.password_changed = False
                        self.login_button.setEnabled(True)
            finally:
                conn.close()

        except pymysql.OperationalError:
            self.show_error("无法连接到服务器,请检查网络连接")
            self.login_button.setEnabled(True)
        except Exception as e:
            self.show_error(f"认证失败: {str(e)}")
            self.login_button.setEnabled(True)

    def get_local_ip(self):
        """获取局域网IP地址"""
        try:
            # 尝试获取真实的局域网IP,而不是127.0.0.1
            hostname = socket.gethostname()
            local_ip = socket.gethostbyname(hostname)

            # 如果获取到的是127.0.0.1,尝试连接外部地址获取本地IP
            if local_ip.startswith('127.'):
                # 创建一个UDP socket连接到公共DNS服务器
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                try:
                    s.connect(('8.8.8.8', 80))
                    local_ip = s.getsockname()[0]
                except:
                    pass
                finally:
                    s.close()

            return local_ip
        except:
            return "127.0.0.1"

    def get_public_ip(self):
        """获取公网IP地址,失败返回None"""
        try:
            # 使用多个API作为备选
            apis = [
                'https://api.ipify.org',
                'https://ifconfig.me',
                'https://ipinfo.io/ip'
            ]

            for api in apis:
                try:
                    response = requests.get(api, timeout=3)
                    if response.status_code == 200:
                        public_ip = response.text.strip()
                        # 简单验证IP格式
                        if len(public_ip.split('.')) == 4 or ':' in public_ip:
                            return public_ip
                except:
                    continue
            return None
        except:
            return None

    def get_device_name(self):
        """获取设备名称"""
        try:
            return socket.gethostname()
        except:
            return "Unknown"

    def log_user_login(self, username):
        """静默记录用户登录日志,支持双IP"""
        try:
            local_ip = self.get_local_ip()
            public_ip = self.get_public_ip()
            device_name = self.get_device_name()

            conn = pymysql.connect(
                host=self.db_config['host'],
                port=self.db_config.get('port', 3306),
                user=self.db_config['user'],
                password=self.db_config['password'],
                database=self.db_config['database'],
                connect_timeout=5
            )

            try:
                with conn.cursor() as cursor:
                    sql = """INSERT INTO nano_banana_user_log
                             (user_name, local_ip, public_ip, device_name, login_time)
                             VALUES (%s, %s, %s, %s, %s)"""
                    cursor.execute(sql, (username, local_ip, public_ip, device_name, datetime.now()))
                    conn.commit()
            finally:
                conn.close()

        except Exception:
            # 静默处理,不影响登录流程
            pass

    def show_error(self, message):
        """显示错误弹窗和标签"""
        # 显示弹窗错误提示
        QMessageBox.critical(self, "登录错误", message)

        # 同时保留标签显示
        self.error_label.setText(message)
        self.error_label.setStyleSheet("QLabel { color: #ff3b30; }")

    def get_remember_user(self):
        """Get remember username checkbox state"""
        return self.remember_user_check.isChecked()

    def get_remember_password(self):
        """Get remember password checkbox state"""
        return self.remember_password_check.isChecked()

    def get_password_hash(self):
        """Get current password hash"""
        return getattr(self, 'current_password_hash', '')


class DragDropScrollArea(QScrollArea):
    """自定义支持拖拽的图像滚动区域"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAcceptDrops(True)
        self.parent_window = parent
        self.setStyleSheet("""
            QScrollArea {
                border: 2px dashed #e5e5e5;
                border-radius: 8px;
                background-color: #fafafa;
            }
            QScrollArea:hover {
                border-color: #007AFF;
                background-color: #f0f8ff;
            }
        """)

    def dragEnterEvent(self, event: QDragEnterEvent):
        """拖拽进入事件处理"""
        mime_data = event.mimeData()

        # 检查是否包含文件URL
        if mime_data.hasUrls():
            urls = mime_data.urls()
            for url in urls:
                if url.isLocalFile():
                    file_path = url.toLocalFile()
                    if self.is_valid_image_file(file_path):
                        event.acceptProposedAction()
                        self.setStyleSheet("""
                            QScrollArea {
                                border: 2px dashed #007AFF;
                                border-radius: 8px;
                                background-color: #e6f3ff;
                            }
                        """)
                        return

        # 检查剪贴板图像
        if mime_data.hasImage():
            event.acceptProposedAction()
            self.setStyleSheet("""
                QScrollArea {
                    border: 2px dashed #007AFF;
                    border-radius: 8px;
                    background-color: #e6f3ff;
                }
            """)
            return

        event.ignore()

    def dragLeaveEvent(self, event):
        """拖拽离开事件处理"""
        self.setStyleSheet("""
            QScrollArea {
                border: 2px dashed #e5e5e5;
                border-radius: 8px;
                background-color: #fafafa;
            }
            QScrollArea:hover {
                border-color: #007AFF;
                background-color: #f0f8ff;
            }
        """)

    def dropEvent(self, event: QDropEvent):
        """拖拽放置事件处理"""
        mime_data = event.mimeData()

        # 重置样式
        self.setStyleSheet("""
            QScrollArea {
                border: 2px dashed #e5e5e5;
                border-radius: 8px;
                background-color: #fafafa;
            }
            QScrollArea:hover {
                border-color: #007AFF;
                background-color: #f0f8ff;
            }
        """)

        # 处理文件拖拽
        if mime_data.hasUrls():
            urls = mime_data.urls()
            image_files = []

            for url in urls:
                if url.isLocalFile():
                    file_path = url.toLocalFile()
                    if self.is_valid_image_file(file_path):
                        image_files.append(file_path)

            if image_files:
                self.parent_window.add_image_files(image_files)
                event.acceptProposedAction()
                return

        # 处理剪贴板图像拖拽
        if mime_data.hasImage():
            image = mime_data.imageData()
            if image and not image.isNull():
                self.parent_window.add_clipboard_image(image)
                event.acceptProposedAction()
                return

        event.ignore()

    def is_valid_image_file(self, file_path: str) -> bool:
        """检查文件是否为有效的图像文件"""
        valid_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'}
        return Path(file_path).suffix.lower() in valid_extensions


class ImageGeneratorWindow(QMainWindow):
    """Qt-based main application window"""

    def __init__(self):
        super().__init__()
        self.logger = logging.getLogger(__name__)
        self.logger.info("应用程序启动")

        self.api_key = ""
        self.uploaded_images = []  # List of file paths
        self.generated_image_data = None
        self.generated_image_bytes = None
        self.saved_prompts = []
        self.db_config = None
        self.last_user = ""
        self.saved_password_hash = ""

        self.load_config()
        self.set_window_icon()

        # Initialize history manager
        self.history_manager = HistoryManager()

        self.setup_ui()
        self.apply_styles()

        self.logger.info("应用程序初始化完成")

    def set_window_icon(self):
        """Set window icon based on platform"""
        try:
            icon_path = None

            if getattr(sys, 'frozen', False):
                # Running as compiled executable
                if platform.system() == 'Windows':
                    icon_path = os.path.join(sys._MEIPASS, 'zb100_windows.ico')
                elif platform.system() == 'Darwin':
                    icon_path = os.path.join(sys._MEIPASS, 'zb100_mac.icns')
            else:
                # Running as script
                if platform.system() == 'Windows':
                    icon_path = 'zb100_windows.ico'
                elif platform.system() == 'Darwin':
                    icon_path = 'zb100_mac.icns'

            if icon_path and os.path.exists(icon_path):
                app_icon = QIcon(icon_path)
                if not app_icon.isNull():
                    self.setWindowIcon(app_icon)
                    self.logger.debug(f"主窗口图标设置成功: {icon_path}")
                else:
                    self.logger.warning(f"图标文件无效: {icon_path}")
            else:
                self.logger.debug(f"图标文件不存在,跳过设置: {icon_path}")

        except Exception as e:
            self.logger.error(f"设置窗口图标失败: {e}")

    def get_config_dir(self):
        """Get the appropriate directory for config files based on platform and mode"""
        if getattr(sys, 'frozen', False):
            system = platform.system()
            if system == 'Darwin':
                config_dir = Path.home() / 'Library' / 'Application Support' / 'ZB100ImageGenerator'
            elif system == 'Windows':
                config_dir = Path(os.getenv('APPDATA', Path.home())) / 'ZB100ImageGenerator'
            else:
                config_dir = Path.home() / '.config' / 'zb100imagegenerator'
        else:
            config_dir = Path('.')

        config_dir.mkdir(parents=True, exist_ok=True)
        return config_dir

    def get_config_path(self):
        """Get the full path to config.json"""
        return self.get_config_dir() / 'config.json'

    def load_config(self):
        """Load API key, saved prompts, and db config from config file"""
        config_path = self.get_config_path()
        self.logger.debug(f"加载配置文件: {config_path}")

        # Try to load from user directory first
        config_loaded = False
        if config_path.exists():
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.api_key = config.get("api_key", "")
                    self.saved_prompts = config.get("saved_prompts", [])
                    self.db_config = config.get("db_config")
                    self.last_user = config.get("last_user", "")
                    self.saved_password_hash = config.get("saved_password_hash", "")

                    # Load history configuration
                    history_config = config.get("history_config", {})
                    if hasattr(self, 'history_manager'):
                        self.history_manager.max_history_count = history_config.get("max_history_count", 100)

                    self.logger.info("配置文件加载成功")
                    config_loaded = True
            except Exception as e:
                self.logger.error(f"配置文件加载失败: {e}")
                print(f"Failed to load config from {config_path}: {e}")

        # If user config doesn't exist or failed to load, try bundled config
        if not config_loaded and getattr(sys, 'frozen', False):
            bundled_config_paths = [
                Path(sys.executable).parent / 'config.json',  # Same directory as exe
                Path(sys._MEIPASS) / 'config.json',  # PyInstaller temp directory
            ]

            for bundled_path in bundled_config_paths:
                if bundled_path.exists():
                    try:
                        with open(bundled_path, 'r', encoding='utf-8') as f:
                            config = json.load(f)
                            self.api_key = config.get("api_key", "")
                            self.saved_prompts = config.get("saved_prompts", [])
                            self.db_config = config.get("db_config")
                            self.last_user = config.get("last_user", "")
                            self.saved_password_hash = config.get("saved_password_hash", "")

                            # Load history configuration
                            history_config = config.get("history_config", {})
                            if hasattr(self, 'history_manager'):
                                self.history_manager.max_history_count = history_config.get("max_history_count", 100)

                            self.logger.info(f"从打包配置文件加载成功: {bundled_path}")
                            config_loaded = True
                            break
                    except Exception as e:
                        self.logger.error(f"打包配置文件加载失败 {bundled_path}: {e}")
                        continue

        # If still no config loaded, try current directory
        if not config_loaded:
            current_config = Path('.') / 'config.json'
            if current_config.exists():
                try:
                    with open(current_config, 'r', encoding='utf-8') as f:
                        config = json.load(f)
                        self.api_key = config.get("api_key", "")
                        self.saved_prompts = config.get("saved_prompts", [])
                        self.db_config = config.get("db_config")
                        self.last_user = config.get("last_user", "")
                        self.saved_password_hash = config.get("saved_password_hash", "")

                        # Load history configuration
                        history_config = config.get("history_config", {})
                        if hasattr(self, 'history_manager'):
                            self.history_manager.max_history_count = history_config.get("max_history_count", 100)

                        self.logger.info(f"从当前目录配置文件加载成功: {current_config}")
                        config_loaded = True
                except Exception as e:
                    self.logger.error(f"当前目录配置文件加载失败: {e}")

        if not config_loaded:
            self.logger.warning("未找到任何有效的配置文件")
            print("警告:未找到配置文件,某些功能可能无法正常工作")

        # 即使没有db_config也继续运行,让用户在UI中配置
        if not self.db_config:
            self.logger.info("未找到数据库配置,将使用UI配置模式")
            self.db_config = None

        if not self.api_key and getattr(sys, 'frozen', False):
            try:
                bundle_dir = Path(sys._MEIPASS)
                bundled_config = bundle_dir / 'config.json'
                if bundled_config.exists():
                    with open(bundled_config, 'r', encoding='utf-8') as f:
                        config = json.load(f)
                        self.api_key = config.get("api_key", "")
                        self.db_config = config.get("db_config")
                    self.save_config()
            except Exception as e:
                print(f"Failed to load bundled config: {e}")

        if not self.api_key:
            QMessageBox.warning(self, "警告",
                                f"未找到API密钥\n配置文件位置: {config_path}\n\n请在应用中输入API密钥或手动编辑配置文件")

    def save_config(self, last_user=None):
        """Save configuration to file"""
        config_path = self.get_config_path()

        try:
            config = {
                "api_key": self.api_key,
                "saved_prompts": self.saved_prompts
            }

            if self.db_config:
                config["db_config"] = self.db_config

            if last_user is not None:
                config["last_user"] = last_user
            elif hasattr(self, 'last_user'):
                config["last_user"] = self.last_user
            else:
                config["last_user"] = ""

            if hasattr(self, 'saved_password_hash'):
                config["saved_password_hash"] = self.saved_password_hash
            else:
                config["saved_password_hash"] = ""

            # Save history configuration
            if hasattr(self, 'history_manager'):
                config["history_config"] = {
                    "max_history_count": self.history_manager.max_history_count
                }

            config_path.parent.mkdir(parents=True, exist_ok=True)

            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=2, ensure_ascii=False)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}\n路径: {config_path}")

    def setup_ui(self):
        """Setup the user interface"""
        self.setWindowTitle("珠宝壹佰图像生成器")
        self.setGeometry(100, 100, 1200, 850)
        self.setMinimumSize(1000, 700)

        # Central widget
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)

        # Create tab widget
        self.tab_widget = QTabWidget()

        # Create generation tab
        generation_tab = self.setup_generation_tab()
        self.tab_widget.addTab(generation_tab, "图片生成")

        # Create history tab
        history_tab = self.setup_history_tab()
        self.tab_widget.addTab(history_tab, "历史记录")

        main_layout.addWidget(self.tab_widget)
        central_widget.setLayout(main_layout)

        self.check_favorite_status()

    def setup_generation_tab(self):
        """Setup the image generation tab"""
        tab_widget = QWidget()
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(15)

        # Reference images section
        ref_group = QGroupBox("参考图片")
        ref_layout = QVBoxLayout()

        # Upload button and count
        upload_header = QHBoxLayout()
        upload_btn = QPushButton("+ 添加图片")
        upload_btn.clicked.connect(self.upload_images)
        upload_header.addWidget(upload_btn)

        # Paste button
        paste_btn = QPushButton("📋 粘贴图片")
        paste_btn.clicked.connect(self.paste_from_clipboard)
        paste_btn.setStyleSheet("""
            QPushButton {
                background-color: #f0f0f0;
                border: 1px solid #d0d0d0;
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 12px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #e8e8e8;
                border-color: #007AFF;
            }
            QPushButton:pressed {
                background-color: #d0d0d0;
            }
        """)
        upload_header.addWidget(paste_btn)

        self.image_count_label = QLabel("已选择 0 张")
        upload_header.addWidget(self.image_count_label)
        upload_header.addStretch()
        ref_layout.addLayout(upload_header)

        # Drag and drop hint
        hint_label = QLabel("💡 提示:可以直接拖拽图片到下方区域,或使用 Ctrl+V 粘贴截图")
        hint_label.setStyleSheet("QLabel { color: #666666; font-size: 11px; margin: 2px 0; }")
        hint_label.setWordWrap(True)
        ref_layout.addWidget(hint_label)

        # Image preview scroll area with drag-and-drop support
        self.img_scroll = DragDropScrollArea(self)
        self.img_scroll.setWidgetResizable(True)
        self.img_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.img_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.img_scroll.setFixedHeight(160)

        self.img_container = QWidget()
        self.img_layout = QHBoxLayout()
        self.img_layout.addStretch()
        self.img_container.setLayout(self.img_layout)
        self.img_scroll.setWidget(self.img_container)

        ref_layout.addWidget(self.img_scroll)
        ref_group.setLayout(ref_layout)
        main_layout.addWidget(ref_group)

        # Content row: Prompt (left) + Settings (right)
        content_row = QHBoxLayout()

        # Prompt section
        prompt_group = QGroupBox("提示词")
        prompt_layout = QVBoxLayout()

        # Prompt toolbar
        prompt_toolbar = QHBoxLayout()
        self.save_prompt_btn = QPushButton("⭐ 收藏")
        self.save_prompt_btn.clicked.connect(self.toggle_favorite)
        prompt_toolbar.addWidget(self.save_prompt_btn)

        prompt_toolbar.addWidget(QLabel("快速选择:"))
        self.saved_prompts_combo = QComboBox()
        prompt_toolbar.addWidget(self.saved_prompts_combo)

        delete_prompt_btn = QPushButton("🗑️ 删除")
        delete_prompt_btn.clicked.connect(self.delete_saved_prompt)
        prompt_toolbar.addWidget(delete_prompt_btn)
        prompt_toolbar.addStretch()

        prompt_layout.addLayout(prompt_toolbar)

        # Prompt text area
        self.prompt_text = QTextEdit()
        self.prompt_text.setStyleSheet("font-size: 16px;")
        self.prompt_text.setPlainText("一幅美丽的风景画,有山有湖,日落时分")
        self.prompt_text.textChanged.connect(self.check_favorite_status)
        prompt_layout.addWidget(self.prompt_text)

        # Update list first (before connecting signal to avoid triggering it during init)
        self.update_saved_prompts_list()

        prompt_group.setLayout(prompt_layout)
        content_row.addWidget(prompt_group, 2)

        # Settings section
        settings_group = QGroupBox("生成设置")
        settings_layout = QVBoxLayout()

        settings_layout.addWidget(QLabel("宽高比"))
        self.aspect_ratio = QComboBox()
        self.aspect_ratio.addItems(["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"])
        settings_layout.addWidget(self.aspect_ratio)

        settings_layout.addSpacing(10)

        settings_layout.addWidget(QLabel("图片尺寸"))
        self.image_size = QComboBox()
        self.image_size.addItems(["1K", "2K", "4K"])
        self.image_size.setCurrentIndex(1)  # Default to 2K
        settings_layout.addWidget(self.image_size)

        settings_layout.addSpacing(10)

        settings_layout.addStretch()
        settings_group.setLayout(settings_layout)
        content_row.addWidget(settings_group, 1)

        main_layout.addLayout(content_row)

        # Action buttons
        action_layout = QHBoxLayout()
        self.generate_btn = QPushButton("生成图片")
        self.generate_btn.clicked.connect(self.generate_image_async)
        action_layout.addWidget(self.generate_btn)

        self.download_btn = QPushButton("下载图片")
        self.download_btn.clicked.connect(self.download_image)
        self.download_btn.setEnabled(False)
        action_layout.addWidget(self.download_btn)

        self.status_label = QLabel("● 就绪")
        action_layout.addWidget(self.status_label)
        action_layout.addStretch()

        main_layout.addLayout(action_layout)

        # Preview section
        preview_group = QGroupBox("预览")
        preview_layout = QVBoxLayout()

        self.preview_label = QLabel("生成的图片将在这里显示\n双击用系统查看器打开")
        self.preview_label.setAlignment(Qt.AlignCenter)
        self.preview_label.setMinimumHeight(300)
        self.preview_label.setStyleSheet("QLabel { color: #999999; font-size: 10pt; }")
        self.preview_label.mouseDoubleClickEvent = self.open_fullsize_view

        preview_layout.addWidget(self.preview_label)
        preview_group.setLayout(preview_layout)
        main_layout.addWidget(preview_group, 1)

        tab_widget.setLayout(main_layout)
        return tab_widget

    def setup_history_tab(self):
        """Setup the history tab"""
        tab_widget = QWidget()
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)

        # History toolbar
        toolbar_layout = QHBoxLayout()

        refresh_btn = QPushButton("🔄 刷新")
        refresh_btn.clicked.connect(self.refresh_history)
        toolbar_layout.addWidget(refresh_btn)

        clear_btn = QPushButton("🗑️ 清空历史")
        clear_btn.clicked.connect(self.clear_history)
        toolbar_layout.addWidget(clear_btn)

        toolbar_layout.addStretch()

        self.history_count_label = QLabel("共 0 条历史记录")
        toolbar_layout.addWidget(self.history_count_label)

        main_layout.addLayout(toolbar_layout)

        # Create splitter for list and details
        from PySide6.QtWidgets import QSplitter
        splitter = QSplitter(Qt.Vertical)

        # History list (upper part)
        self.history_list = QListWidget()
        self.history_list.setIconSize(QSize(120, 120))
        self.history_list.setResizeMode(QListWidget.Adjust)
        self.history_list.setViewMode(QListWidget.IconMode)
        self.history_list.setSpacing(10)
        self.history_list.setMinimumHeight(200)  # Give more space for history list
        self.history_list.itemClicked.connect(self.load_history_item)
        self.history_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.history_list.customContextMenuRequested.connect(self.show_history_context_menu)

        splitter.addWidget(self.history_list)

        # Details panel (lower part)
        self.details_panel = self.create_details_panel()
        splitter.addWidget(self.details_panel)

        # Set splitter proportions (40% for list, 60% for details)
        splitter.setSizes([300, 450])
        splitter.setChildrenCollapsible(False)  # Prevent panels from being collapsed completely

        main_layout.addWidget(splitter)
        tab_widget.setLayout(main_layout)

        # Load initial history
        self.refresh_history()

        return tab_widget

    def create_details_panel(self):
        """Create the details panel for displaying selected history item"""
        panel = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)

        # Prompt section
        prompt_group = QGroupBox("提示词")
        prompt_layout = QVBoxLayout()

        # Prompt text area with copy button
        prompt_header = QHBoxLayout()
        prompt_header.addWidget(QLabel("完整提示词:"))
        self.copy_prompt_btn = QPushButton("📋 复制")
        self.copy_prompt_btn.clicked.connect(self.copy_prompt_text)
        self.copy_prompt_btn.setEnabled(False)
        prompt_header.addWidget(self.copy_prompt_btn)
        prompt_header.addStretch()

        prompt_layout.addLayout(prompt_header)

        self.prompt_display = QLabel("请选择一个历史记录查看详情")
        self.prompt_display.setWordWrap(True)
        self.prompt_display.setStyleSheet(
            "QLabel { padding: 8px; background-color: #f9f9f9; border: 1px solid #ddd; border-radius: 4px; }")
        prompt_layout.addWidget(self.prompt_display)

        prompt_group.setLayout(prompt_layout)
        layout.addWidget(prompt_group)

        # Parameters section - compressed to one line
        params_group = QGroupBox("生成参数")
        params_layout = QHBoxLayout()

        params_layout.addWidget(QLabel("生成时间:"))
        self.time_label = QLabel("-")
        params_layout.addWidget(self.time_label)

        params_layout.addWidget(QLabel("  |  宽高比:"))
        self.aspect_ratio_label = QLabel("-")
        params_layout.addWidget(self.aspect_ratio_label)

        params_layout.addWidget(QLabel("  |  图片尺寸:"))
        self.image_size_label = QLabel("-")
        params_layout.addWidget(self.image_size_label)

        params_layout.addStretch()
        params_group.setLayout(params_layout)
        layout.addWidget(params_group)

        # Images section - left (reference) and right (generated) layout
        images_group = QGroupBox("图片预览")
        images_layout = QHBoxLayout()

        # Left side - Reference images
        ref_group = QGroupBox("参考图片")
        ref_layout = QVBoxLayout()

        self.ref_images_scroll = QScrollArea()
        self.ref_images_scroll.setWidgetResizable(True)
        self.ref_images_scroll.setMinimumHeight(200)
        self.ref_images_widget = QWidget()
        self.ref_images_layout = QVBoxLayout()  # Changed to vertical for better layout
        self.ref_images_layout.setAlignment(Qt.AlignCenter)
        self.ref_images_widget.setLayout(self.ref_images_layout)
        self.ref_images_scroll.setWidget(self.ref_images_widget)

        ref_layout.addWidget(self.ref_images_scroll)
        ref_group.setLayout(ref_layout)
        images_layout.addWidget(ref_group, 1)  # 1:1 stretch

        # Right side - Generated image (larger)
        gen_group = QGroupBox("生成图片")
        gen_layout = QVBoxLayout()
        gen_layout.setAlignment(Qt.AlignCenter)

        self.generated_image_label = QLabel("请选择一个历史记录查看生成图片")
        self.generated_image_label.setAlignment(Qt.AlignCenter)
        self.generated_image_label.setMinimumSize(200, 200)  # Larger size for generated image
        self.generated_image_label.setMaximumSize(300, 300)
        self.generated_image_label.setStyleSheet(
            "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")
        self.generated_image_label.mouseDoubleClickEvent = self.open_generated_image_from_history

        gen_layout.addWidget(self.generated_image_label)
        gen_group.setLayout(gen_layout)
        images_layout.addWidget(gen_group, 1)  # 1:1 stretch

        images_group.setLayout(images_layout)
        layout.addWidget(images_group)

        layout.addStretch()
        panel.setLayout(layout)
        return panel

    def apply_styles(self):
        """Apply QSS stylesheet"""
        """Apply QSS stylesheet - 最小化自定义样式"""
        self.setStyleSheet("""
                QMainWindow {
                    background-color: #ffffff;
                }
                QGroupBox {
                    font-weight: bold;
                    font-size: 10pt;
                    border: 1px solid #e5e5e5;
                    border-radius: 6px;
                    margin-top: 10px;
                    padding-top: 10px;
                }
                QGroupBox::title {
                    subcontrol-origin: margin;
                    left: 10px;
                    padding: 0 5px;
                }
                QPushButton {
                    padding: 6px 12px;
                    font-size: 9pt;
                    border: 1px solid #cccccc;
                    border-radius: 4px;
                }
                QPushButton:disabled {
                    color: #999999;
                }
                QComboBox {
                    padding: 5px;
                    min-width: 100px;
                }
                QTextEdit {
                    border: 1px solid #e5e5e5;
                    border-radius: 4px;
                    font-size: 10pt;
                }
                QScrollArea {
                    border: none;
                    background-color: #f6f6f6;
                }
                /* 只保留必要的边框和背景,不设置颜色 */
                QLineEdit, QComboBox, QTextEdit {
                    border: 1px solid #cccccc;
                    border-radius: 4px;
                }
                QLineEdit:focus, QComboBox:focus, QTextEdit:focus {
                    border: 1px solid #007AFF;  /* 保持焦点状态 */
                }
            """)

        # Connect signals after all widgets are created
        self.saved_prompts_combo.currentIndexChanged.connect(self.load_saved_prompt)

    def upload_images(self):
        """Upload reference images"""
        files, _ = QFileDialog.getOpenFileNames(
            self,
            "选择参考图片",
            "",
            "图片文件 (*.png *.jpg *.jpeg *.gif *.bmp);;所有文件 (*.*)"
        )

        if files:
            for file_path in files:
                try:
                    self.uploaded_images.append(file_path)
                except Exception as e:
                    QMessageBox.critical(self, "错误", f"无法加载图片: {file_path}\n{str(e)}")

            self.update_image_preview()
            self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
            self.status_label.setText(f"● 已添加 {len(files)} 张参考图片")
            self.status_label.setStyleSheet("QLabel { color: #34C759; }")

    def add_image_files(self, file_paths):
        """添加图像文件到上传列表(用于拖拽功能)"""
        if not file_paths:
            return

        added_count = 0
        for file_path in file_paths:
            try:
                if self.validate_image_file(file_path):
                    self.uploaded_images.append(file_path)
                    added_count += 1
                else:
                    self.logger.warning(f"无效的图像文件: {file_path}")
            except Exception as e:
                self.logger.error(f"添加图片失败: {file_path}, 错误: {str(e)}")

        if added_count > 0:
            self.update_image_preview()
            self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
            self.status_label.setText(f"● 已通过拖拽添加 {added_count} 张参考图片")
            self.status_label.setStyleSheet("QLabel { color: #34C759; }")
        else:
            QMessageBox.warning(self, "警告", "没有找到有效的图片文件")

    def add_clipboard_image(self, image):
        """添加剪贴板图像(用于拖拽和粘贴功能)"""
        try:
            # 生成临时文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            temp_dir = Path(tempfile.gettempdir()) / "nano_banana_app"
            temp_dir.mkdir(exist_ok=True)

            # 根据图像格式选择文件扩展名
            file_extension = ".png"  # 默认使用PNG格式
            if image.format() == QImage.Format_RGB32:
                file_extension = ".bmp"
            elif image.format() == QImage.Format_RGB888:
                file_extension = ".jpg"

            temp_file_path = temp_dir / f"clipboard_{timestamp}{file_extension}"

            # 保存图像到临时文件
            if image.save(str(temp_file_path)):
                self.uploaded_images.append(str(temp_file_path))
                self.update_image_preview()
                self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
                self.status_label.setText("● 已添加剪贴板图片")
                self.status_label.setStyleSheet("QLabel { color: #34C759; }")
                self.logger.info(f"剪贴板图片已保存到: {temp_file_path}")
            else:
                QMessageBox.critical(self, "错误", "无法保存剪贴板图片")

        except Exception as e:
            self.logger.error(f"添加剪贴板图片失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"添加剪贴板图片失败: {str(e)}")

    def paste_from_clipboard(self):
        """从剪贴板粘贴图像"""
        clipboard = QApplication.clipboard()

        # 检查剪贴板中是否有图像
        if clipboard.mimeData().hasImage():
            image = clipboard.image()
            if not image.isNull():
                self.add_clipboard_image(image)
            else:
                QMessageBox.information(self, "信息", "剪贴板中没有有效的图片")
        else:
            QMessageBox.information(self, "信息", "剪贴板中没有图片,请先复制一张图片")

    def validate_image_file(self, file_path: str) -> bool:
        """验证图像文件"""
        try:
            # 检查文件是否存在
            if not Path(file_path).exists():
                return False

            # 检查文件扩展名
            valid_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'}
            if Path(file_path).suffix.lower() not in valid_extensions:
                return False

            # 尝试加载图像以验证文件完整性
            pixmap = QPixmap(file_path)
            if pixmap.isNull():
                return False

            # 检查文件大小(限制为10MB)
            file_size = Path(file_path).stat().st_size
            if file_size > 10 * 1024 * 1024:  # 10MB
                QMessageBox.warning(self, "警告", f"图片文件过大: {file_path}\n请选择小于10MB的图片")
                return False

            return True

        except Exception as e:
            self.logger.error(f"图像文件验证失败: {file_path}, 错误: {str(e)}")
            return False

    def keyPressEvent(self, event):
        """处理键盘事件"""
        # Ctrl+V 粘贴
        if event.key() == Qt.Key_V and event.modifiers() == Qt.ControlModifier:
            self.paste_from_clipboard()
            event.accept()
            return

        # Cmd+V 粘贴 (macOS)
        elif event.key() == Qt.Key_V and event.modifiers() == Qt.MetaModifier:
            self.paste_from_clipboard()
            event.accept()
            return

        super().keyPressEvent(event)

    def update_image_preview(self):
        """Update image preview thumbnails"""
        # Clear existing previews
        while self.img_layout.count() > 1:  # Keep the stretch
            item = self.img_layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()

        # Add thumbnails
        for idx, file_path in enumerate(self.uploaded_images):
            try:
                # Load and create thumbnail
                pixmap = QPixmap(file_path)
                pixmap = pixmap.scaled(100, 100, Qt.KeepAspectRatio, Qt.SmoothTransformation)

                # Container
                container = QWidget()
                container_layout = QVBoxLayout()
                container_layout.setContentsMargins(5, 5, 5, 5)

                # Image label
                img_label = QLabel()
                img_label.setPixmap(pixmap)
                img_label.setFixedSize(100, 100)
                img_label.setStyleSheet("QLabel { border: 1px solid #e5e5e5; }")
                container_layout.addWidget(img_label)

                # Info row
                info_layout = QHBoxLayout()
                index_label = QLabel(f"图 {idx + 1}")
                index_label.setStyleSheet("QLabel { font-size: 8pt; color: #666666; }")
                info_layout.addWidget(index_label)

                del_btn = QPushButton("✕")
                del_btn.setFixedSize(20, 20)
                del_btn.setStyleSheet("""
                    QPushButton {
                        background-color: #ff4444;
                        color: white;
                        font-weight: bold;
                        border: none;
                        border-radius: 3px;
                        padding: 0px;
                    }
                    QPushButton:hover {
                        background-color: #FF3B30;
                    }
                """)
                del_btn.clicked.connect(lambda checked, i=idx: self.delete_image(i))
                info_layout.addWidget(del_btn)

                container_layout.addLayout(info_layout)
                container.setLayout(container_layout)

                self.img_layout.insertWidget(self.img_layout.count() - 1, container)
            except Exception as e:
                print(f"Failed to create thumbnail for {file_path}: {e}")

    def delete_image(self, index):
        """Delete an image by index"""
        if 0 <= index < len(self.uploaded_images):
            self.uploaded_images.pop(index)
            self.update_image_preview()
            self.image_count_label.setText(f"已选择 {len(self.uploaded_images)} 张")
            self.status_label.setText("● 已删除图片")
            self.status_label.setStyleSheet("QLabel { color: #FF9500; }")

    def update_saved_prompts_list(self):
        """Update the saved prompts dropdown"""
        # Block signals to avoid triggering load_saved_prompt during update
        self.saved_prompts_combo.blockSignals(True)
        self.saved_prompts_combo.clear()
        if self.saved_prompts:
            display_prompts = [p[:50] + "..." if len(p) > 50 else p for p in self.saved_prompts]
            self.saved_prompts_combo.addItems(display_prompts)
        self.saved_prompts_combo.blockSignals(False)

    def check_favorite_status(self):
        """Check if current prompt is favorited"""
        prompt = self.prompt_text.toPlainText().strip()
        if prompt in self.saved_prompts:
            self.save_prompt_btn.setText("✓ 已收藏")
        else:
            self.save_prompt_btn.setText("⭐ 收藏")

    def toggle_favorite(self):
        """Toggle favorite status of current prompt"""
        prompt = self.prompt_text.toPlainText().strip()
        if not prompt:
            self.status_label.setText("● 提示词不能为空")
            self.status_label.setStyleSheet("QLabel { color: #FF3B30; }")
            return

        if prompt in self.saved_prompts:
            self.saved_prompts.remove(prompt)
            self.save_config()
            self.update_saved_prompts_list()
            self.status_label.setText("● 该提示词已取消收藏")
        else:
            self.saved_prompts.append(prompt)
            self.save_config()
            self.update_saved_prompts_list()
            self.status_label.setText("● 该提示词已收藏")

        self.status_label.setStyleSheet("QLabel { color: #34C759; }")
        self.check_favorite_status()

    def load_saved_prompt(self):
        """Load a saved prompt"""
        index = self.saved_prompts_combo.currentIndex()
        if 0 <= index < len(self.saved_prompts):
            self.prompt_text.setPlainText(self.saved_prompts[index])
            self.status_label.setText("● 已加载提示词")
            self.status_label.setStyleSheet("QLabel { color: #007AFF; }")

    def delete_saved_prompt(self):
        """Delete the currently selected saved prompt"""
        index = self.saved_prompts_combo.currentIndex()

        if index < 0 or index >= len(self.saved_prompts):
            self.status_label.setText("● 请先选择要删除的提示词")
            self.status_label.setStyleSheet("QLabel { color: #FF9500; }")
            return

        self.saved_prompts.pop(index)
        self.save_config()
        self.update_saved_prompts_list()
        self.status_label.setText("● 已删除提示词")
        self.status_label.setStyleSheet("QLabel { color: #34C759; }")

    def generate_image_async(self):
        """Start image generation in a separate thread"""
        # Create and start worker thread
        self.worker = ImageGenerationWorker(
            self.api_key,
            self.prompt_text.toPlainText().strip(),
            self.uploaded_images,
            self.aspect_ratio.currentText(),
            self.image_size.currentText(),
            "gemini-3-pro-image-preview"  # 锁死模型
        )
        self.worker.finished.connect(self.on_image_generated)
        self.worker.error.connect(self.on_generation_error)
        self.worker.progress.connect(self.update_status)

        self.generate_btn.setEnabled(False)
        self.download_btn.setEnabled(False)
        self.status_label.setText("● 正在生成图片...")
        self.status_label.setStyleSheet("QLabel { color: #FF9500; }")

        self.worker.start()

    def on_image_generated(self, image_bytes, prompt, reference_images, aspect_ratio, image_size, model):
        """Handle successful image generation"""
        self.generated_image_bytes = image_bytes
        self.display_image()
        self.download_btn.setEnabled(True)
        self.generate_btn.setEnabled(True)
        self.status_label.setText("● 图片生成成功")
        self.status_label.setStyleSheet("QLabel { color: #34C759; }")

        # 自动保存到历史记录
        try:
            self.history_manager.save_generation(
                image_bytes=image_bytes,
                prompt=prompt,
                reference_images=reference_images,
                aspect_ratio=aspect_ratio,
                image_size=image_size,
                model=model
            )
            self.status_label.setText("● 图片生成成功,已保存到历史记录")
            # 刷新历史记录列表
            self.refresh_history()
        except Exception as e:
            print(f"保存到历史记录失败: {e}")
            # 不影响主要功能,静默处理错误

    def on_generation_error(self, error_msg):
        """Handle image generation error"""
        QMessageBox.critical(self, "错误", f"生成失败: {error_msg}")
        self.generate_btn.setEnabled(True)
        self.status_label.setText("● 生成失败")
        self.status_label.setStyleSheet("QLabel { color: #FF3B30; }")

    def update_status(self, message):
        """Update status label"""
        self.status_label.setText(f"● {message}")

    def display_image(self):
        """Display generated image in preview"""
        if not self.generated_image_bytes:
            return

        try:
            # Load image from bytes
            pixmap = QPixmap()
            pixmap.loadFromData(self.generated_image_bytes)

            # Scale to fit preview area
            available_width = self.preview_label.width() - 40
            available_height = self.preview_label.height() - 40

            scaled_pixmap = pixmap.scaled(
                available_width, available_height,
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation
            )

            self.preview_label.setPixmap(scaled_pixmap)
            self.preview_label.setStyleSheet("")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"图片显示失败: {str(e)}")

    def open_fullsize_view(self, event):
        """Open generated image with system default viewer"""
        if not self.generated_image_bytes:
            return

        try:
            # 获取处理后的PNG图片数据
            processed_bytes = self.get_processed_image_bytes('.png')

            # Create temporary file with processed data
            with tempfile.NamedTemporaryFile(delete=False, suffix='.png', mode='wb') as tmp_file:
                tmp_file.write(processed_bytes)
                tmp_path = tmp_file.name

            # Open with system default viewer
            url = QUrl.fromLocalFile(tmp_path)
            QDesktopServices.openUrl(url)

            processing_method = "格式转换后" if processed_bytes != self.generated_image_bytes else "原始数据"
            self.status_label.setText(f"● 已用系统查看器打开 ({processing_method})")
            self.status_label.setStyleSheet("QLabel { color: #007AFF; }")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"无法打开系统图片查看器: {str(e)}")

    def get_processed_image_bytes(self, file_extension='.png') -> bytes:
        """获取处理后的图片字节数据"""
        try:
            from PIL import Image
            import io

            # 使用Pillow处理图像
            with Image.open(io.BytesIO(self.generated_image_bytes)) as img:
                file_format = img.format
                save_format = 'PNG' if file_extension.lower().endswith('.png') else 'JPEG'

                # 检测并执行格式转换
                if file_format and file_format != save_format:
                    self.logger.info(f"下载时格式转换: {file_format} -> {save_format}")

                    # 模式转换
                    if save_format == 'PNG':
                        if img.mode not in ['RGBA', 'RGB', 'L']:
                            if img.mode == 'P':
                                img = img.convert('RGBA')
                            elif img.mode == 'LA':
                                img = img.convert('RGBA')
                            else:
                                img = img.convert('RGBA')
                    elif save_format == 'JPEG':
                        if img.mode in ['RGBA', 'P']:
                            img = img.convert('RGB')
                        elif img.mode == 'L':
                            img = img.convert('RGB')

                # 转换为字节数据
                processed_bytes = io.BytesIO()
                img.save(processed_bytes, save_format, optimize=True)
                return processed_bytes.getvalue()

        except Exception as e:
            self.logger.warning(f"图片处理失败,使用原始数据: {e}")
            return self.generated_image_bytes

    def download_image(self):
        """Download generated image"""
        if not self.generated_image_bytes:
            QMessageBox.critical(self, "错误", "没有可下载的图片!")
            return

        # Generate default filename
        default_filename = datetime.now().strftime("%Y%m%d%H%M%S.png")

        file_path, _ = QFileDialog.getSaveFileName(
            self,
            "保存图片",
            default_filename,
            "PNG 文件 (*.png);;JPEG 文件 (*.jpg);;所有文件 (*.*)"
        )

        if file_path:
            try:
                # 获取处理后的图片数据
                file_extension = Path(file_path).suffix
                processed_bytes = self.get_processed_image_bytes(file_extension)

                # 保存处理后的图片
                with open(file_path, 'wb') as f:
                    f.write(processed_bytes)

                # 获取实际文件大小
                import os
                file_size = os.path.getsize(file_path)

                processing_method = "格式转换" if processed_bytes != self.generated_image_bytes else "原始数据"
                self.logger.info(f"图片下载完成 - 方法: {processing_method}, 文件: {file_path}, 大小: {file_size} 字节")

                QMessageBox.information(self, "成功", f"图片已保存到:\n{file_path}\n\n文件大小: {file_size:,} 字节")
                self.status_label.setText("● 图片已保存")
                self.status_label.setStyleSheet("QLabel { color: #34C759; }")
            except Exception as e:
                self.logger.error(f"图片保存失败: {str(e)}")
                QMessageBox.critical(self, "错误", f"保存失败: {str(e)}")

    def refresh_history(self):
        """Refresh the history list"""
        self.history_list.clear()
        history_items = self.history_manager.load_history_index()

        for item in history_items:
            # Create list item with icon
            list_item = QListWidgetItem()

            # Set item data
            list_item.setData(Qt.UserRole, item.timestamp)

            # Create enhanced tooltip with details
            tooltip = f"时间: {item.created_at.strftime('%Y-%m-%d %H:%M:%S')}\n"
            tooltip += f"提示词: {item.prompt}\n"
            tooltip += f"宽高比: {item.aspect_ratio}\n"
            tooltip += f"尺寸: {item.image_size}"
            list_item.setToolTip(tooltip)

            # Try to load thumbnail
            if item.generated_image_path.exists():
                try:
                    pixmap = QPixmap(str(item.generated_image_path))
                    if not pixmap.isNull():
                        # Scale to thumbnail size
                        scaled_pixmap = pixmap.scaled(120, 120, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                        list_item.setIcon(QIcon(scaled_pixmap))
                    else:
                        # Create placeholder icon
                        list_item.setIcon(self.create_placeholder_icon("图片\n加载失败"))
                except Exception as e:
                    print(f"Failed to load thumbnail for {item.timestamp}: {e}")
                    list_item.setIcon(self.create_placeholder_icon("图片\n错误"))
            else:
                list_item.setIcon(self.create_placeholder_icon("图片\n不存在"))

            # Add text info below the icon
            # Get prompt preview (first 20 characters)
            prompt_preview = item.prompt[:20] + "..." if len(item.prompt) > 20 else item.prompt
            list_item.setText(f"{item.timestamp}\n{prompt_preview}")

            # Add to list
            self.history_list.addItem(list_item)

        # Update count label
        self.history_count_label.setText(f"共 {len(history_items)} 条历史记录")

        # Clear details panel if no items
        if not history_items:
            self.clear_details_panel()

    def create_placeholder_icon(self, text):
        """Create a placeholder icon with text"""
        # Create a 120x120 pixmap
        pixmap = QPixmap(120, 120)
        pixmap.fill(Qt.lightGray)

        # Create a painter to draw text
        from PySide6.QtGui import QPainter, QFont
        painter = QPainter(pixmap)
        painter.setPen(Qt.black)
        painter.setFont(QFont("Arial", 10))

        # Draw text in center
        rect = pixmap.rect()
        painter.drawText(rect, Qt.AlignCenter, text)

        painter.end()
        return QIcon(pixmap)

    def load_history_item(self, item):
        """Display history item details when selected"""
        timestamp = item.data(Qt.UserRole)
        if not timestamp:
            return

        history_item = self.history_manager.get_history_item(timestamp)
        if not history_item:
            return

        # Display details in the details panel
        self.display_history_details(history_item)

    def show_history_context_menu(self, position):
        """Show context menu for history items"""
        item = self.history_list.itemAt(position)
        if not item:
            return

        timestamp = item.data(Qt.UserRole)
        if not timestamp:
            return

        # Create context menu
        menu = QMenu(self)

        # Delete action
        delete_action = QAction("删除此项", self)
        delete_action.triggered.connect(lambda: self.delete_history_item(timestamp))
        menu.addAction(delete_action)

        # Open in file manager action
        open_action = QAction("在文件管理器中显示", self)
        open_action.triggered.connect(lambda: self.open_in_file_manager(timestamp))
        menu.addAction(open_action)

        # Show menu
        menu.exec_(self.history_list.mapToGlobal(position))

    def delete_history_item(self, timestamp):
        """Delete a history item"""
        reply = QMessageBox.question(
            self, "确认删除", "确定要删除这条历史记录吗?\n这将删除相关的所有文件。",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            success = self.history_manager.delete_history_item(timestamp)
            if success:
                self.refresh_history()
                self.status_label.setText("● 历史记录已删除")
                self.status_label.setStyleSheet("QLabel { color: #34C759; }")
            else:
                QMessageBox.critical(self, "错误", "删除历史记录失败")

    def open_in_file_manager(self, timestamp):
        """Open the history item directory in file manager"""
        history_item = self.history_manager.get_history_item(timestamp)
        if not history_item:
            return

        record_dir = history_item.generated_image_path.parent
        if record_dir.exists():
            import subprocess
            import platform

            try:
                if platform.system() == "Windows":
                    subprocess.run(["explorer", str(record_dir)])
                elif platform.system() == "Darwin":  # macOS
                    subprocess.run(["open", str(record_dir)])
                else:  # Linux
                    subprocess.run(["xdg-open", str(record_dir)])
            except Exception as e:
                QMessageBox.critical(self, "错误", f"无法打开文件管理器: {str(e)}")

    def clear_history(self):
        """Clear all history"""
        reply = QMessageBox.question(
            self, "确认清空", "确定要清空所有历史记录吗?\n这将删除所有历史图片文件,且无法恢复。",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                # Remove entire history directory
                import shutil
                if self.history_manager.base_path.exists():
                    shutil.rmtree(self.history_manager.base_path)
                    # Recreate empty directory
                    self.history_manager.base_path.mkdir(parents=True, exist_ok=True)

                self.refresh_history()
                self.status_label.setText("● 历史记录已清空")
                self.status_label.setStyleSheet("QLabel { color: #34C759; }")

            except Exception as e:
                QMessageBox.critical(self, "错误", f"清空历史记录失败: {str(e)}")

    def display_history_details(self, history_item):
        """Display history item details in the details panel"""
        try:
            # Update prompt display
            self.prompt_display.setText(history_item.prompt)
            self.copy_prompt_btn.setEnabled(True)
            self.current_history_prompt = history_item.prompt  # Store for copying

            # Update parameters
            self.time_label.setText(history_item.created_at.strftime('%Y-%m-%d %H:%M:%S'))
            self.aspect_ratio_label.setText(history_item.aspect_ratio)
            self.image_size_label.setText(history_item.image_size)

            # Display reference images
            self.display_reference_images(history_item.reference_image_paths)

            # Display generated image
            self.display_generated_image(history_item.generated_image_path)

        except Exception as e:
            print(f"Error displaying history details: {e}")

    def display_reference_images(self, reference_paths):
        """Display reference images in the details panel with adaptive sizing"""
        # Clear existing images
        for i in reversed(range(self.ref_images_layout.count())):
            child = self.ref_images_layout.itemAt(i).widget()
            if child:
                child.setParent(None)

        if not reference_paths:
            no_images_label = QLabel("无参考图片")
            no_images_label.setStyleSheet("color: #999;")
            self.ref_images_layout.addWidget(no_images_label)
            return

        # Calculate adaptive size based on number of images
        num_images = len(reference_paths)
        if num_images == 1:
            size = 180  # Single image gets more space
        elif num_images == 2:
            size = 140  # Two images get medium space
        else:
            size = 100  # Multiple images get smaller space

        for ref_path in reference_paths:
            if ref_path.exists():
                try:
                    pixmap = QPixmap(str(ref_path))
                    if not pixmap.isNull():
                        # Create adaptive thumbnail
                        thumbnail = pixmap.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                        image_label = QLabel()
                        image_label.setPixmap(thumbnail)
                        image_label.setFixedSize(size, size)
                        image_label.setAlignment(Qt.AlignCenter)
                        image_label.setStyleSheet("border: 1px solid #ddd; margin: 5px;")
                        image_label.mouseDoubleClickEvent = lambda e, path=ref_path: self.open_reference_image(path)
                        self.ref_images_layout.addWidget(image_label)
                except Exception as e:
                    print(f"Failed to load reference image {ref_path}: {e}")

    def display_generated_image(self, image_path):
        """Display the generated image in the details panel"""
        if image_path.exists():
            try:
                pixmap = QPixmap(str(image_path))
                if not pixmap.isNull():
                    # Scale to larger size while maintaining aspect ratio
                    available_size = self.generated_image_label.size()
                    scaled_pixmap = pixmap.scaled(
                        available_size.width(),
                        available_size.height(),
                        Qt.KeepAspectRatio,
                        Qt.SmoothTransformation
                    )
                    self.generated_image_label.setPixmap(scaled_pixmap)
                    self.generated_image_label.setStyleSheet(
                        "QLabel { border: 1px solid #ddd; background-color: white; }")
                    self.current_generated_image_path = image_path
                else:
                    self.generated_image_label.setText("图片加载失败")
                    self.generated_image_label.setStyleSheet(
                        "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")
            except Exception as e:
                print(f"Failed to load generated image {image_path}: {e}")
                self.generated_image_label.setText("图片加载失败")
                self.generated_image_label.setStyleSheet(
                    "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")
        else:
            self.generated_image_label.setText("图片文件不存在")
            self.generated_image_label.setStyleSheet(
                "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")

    def clear_details_panel(self):
        """Clear the details panel"""
        self.prompt_display.setText("请选择一个历史记录查看详情")
        self.copy_prompt_btn.setEnabled(False)
        self.time_label.setText("-")
        self.aspect_ratio_label.setText("-")
        self.image_size_label.setText("-")

        # Clear reference images
        for i in reversed(range(self.ref_images_layout.count())):
            child = self.ref_images_layout.itemAt(i).widget()
            if child:
                child.setParent(None)
        no_images_label = QLabel("无参考图片")
        no_images_label.setStyleSheet("color: #999;")
        self.ref_images_layout.addWidget(no_images_label)

        self.generated_image_label.setText("请选择一个历史记录查看生成图片")
        self.generated_image_label.setPixmap(QPixmap())
        self.generated_image_label.setStyleSheet(
            "QLabel { background-color: #f5f5f5; border: 1px solid #ddd; color: #999; }")

    def copy_prompt_text(self):
        """Copy the prompt text to clipboard"""
        if hasattr(self, 'current_history_prompt'):
            from PySide6.QtWidgets import QApplication
            clipboard = QApplication.clipboard()
            clipboard.setText(self.current_history_prompt)

            # Show success message briefly
            original_text = self.copy_prompt_btn.text()
            self.copy_prompt_btn.setText("✅ 已复制")
            self.copy_prompt_btn.setStyleSheet("QPushButton { background-color: #34C759; color: white; }")

            # Reset after 2 seconds
            QTimer.singleShot(2000, lambda: self.reset_copy_button())

    def reset_copy_button(self):
        """Reset the copy button appearance"""
        self.copy_prompt_btn.setText("📋 复制")
        self.copy_prompt_btn.setStyleSheet("")

    def open_generated_image_from_history(self, event):
        """Open the generated image from history in system viewer"""
        if hasattr(self, 'current_generated_image_path') and self.current_generated_image_path:
            self.open_image_in_system_viewer(self.current_generated_image_path)

    def open_reference_image(self, image_path):
        """Open a reference image in system viewer"""
        self.open_image_in_system_viewer(image_path)

    def open_image_in_system_viewer(self, image_path):
        """Open an image in the system default viewer"""
        try:
            QDesktopServices.openUrl(QUrl.fromLocalFile(str(image_path)))
        except Exception as e:
            QMessageBox.critical(self, "错误", f"无法打开图片: {str(e)}")


class ImageGenerationWorker(QThread):
    """Worker thread for image generation"""
    finished = Signal(bytes, str, list, str, str,
                      str)  # image_bytes, prompt, reference_images, aspect_ratio, image_size, model
    error = Signal(str)
    progress = Signal(str)

    def __init__(self, api_key, prompt, images, aspect_ratio, image_size, model="gemini-3-pro-image-preview"):
        super().__init__()
        self.logger = logging.getLogger(__name__)
        self.api_key = api_key
        self.prompt = prompt
        self.images = images
        self.aspect_ratio = aspect_ratio
        self.image_size = image_size
        self.model = model

        self.logger.info(f"图片生成任务初始化 - 模型: {model}, 尺寸: {image_size}, 宽高比: {aspect_ratio}")

    def run(self):
        """Execute image generation in background thread"""
        try:
            self.logger.info("开始图片生成任务")

            if not self.prompt:
                self.logger.error("图片描述为空")
                self.error.emit("请输入图片描述!")
                return

            if not self.api_key:
                self.logger.error("API密钥为空")
                self.error.emit("未找到API密钥,请在config.json中配置!")
                return

            self.progress.emit("正在连接 Gemini API...")
            self.logger.debug("正在连接 Gemini API")

            client = genai.Client(api_key=self.api_key)

            # Build content parts
            content_parts = [self.prompt]

            # Add reference images
            for img_path in self.images:
                with open(img_path, 'rb') as f:
                    img_data = f.read()

                mime_type = "image/png"
                if img_path.lower().endswith(('.jpg', '.jpeg')):
                    mime_type = "image/jpeg"

                content_parts.append(
                    types.Part.from_bytes(
                        data=img_data,
                        mime_type=mime_type
                    )
                )

            self.progress.emit("正在生成图片...")

            # Generation config
            config = types.GenerateContentConfig(
                response_modalities=["IMAGE"],
                image_config=types.ImageConfig(
                    aspect_ratio=self.aspect_ratio,
                    image_size=self.image_size
                )
            )

            # Generate
            response = client.models.generate_content(
                model="gemini-3-pro-image-preview",
                contents=content_parts,
                config=config
            )

            # Extract image
            for part in response.parts:
                if hasattr(part, 'inline_data') and part.inline_data:
                    if isinstance(part.inline_data.data, bytes):
                        image_bytes = part.inline_data.data
                    else:
                        image_bytes = base64.b64decode(part.inline_data.data)

                    # Convert reference images to bytes for history saving
                    reference_images_bytes = []
                    for img_path in self.images:
                        if img_path and os.path.exists(img_path):
                            with open(img_path, 'rb') as f:
                                reference_images_bytes.append(f.read())
                        else:
                            reference_images_bytes.append(b'')

                    self.logger.info(f"图片生成成功 - 模型: {self.model}, 尺寸: {self.image_size}")
                    self.finished.emit(image_bytes, self.prompt, reference_images_bytes,
                                       self.aspect_ratio, self.image_size, self.model)
                    return

            error_msg = "响应中没有图片数据"
            self.logger.error(error_msg)
            self.error.emit(error_msg)

        except Exception as e:
            error_msg = f"图片生成异常: {e}"
            self.logger.error(error_msg)
            self.error.emit(error_msg)


def main():
    """Main application entry point"""
    # 初始化日志系统
    if not init_logging():
        print("警告:日志系统初始化失败,将继续运行但不记录日志")

    # Load config for database info
    config_dir = Path('.')
    if getattr(sys, 'frozen', False):
        system = platform.system()
        if system == 'Darwin':
            config_dir = Path.home() / 'Library' / 'Application Support' / 'ZB100ImageGenerator'
        elif system == 'Windows':
            config_dir = Path(os.getenv('APPDATA', Path.home())) / 'ZB100ImageGenerator'
        else:
            config_dir = Path.home() / '.config' / 'zb100imagegenerator'

    config_dir.mkdir(parents=True, exist_ok=True)
    config_path = config_dir / 'config.json'

    # Always try to ensure user config exists - copy from bundled if needed
    if not config_path.exists():
        if getattr(sys, 'frozen', False):
            # Running as bundled app - look for bundled config
            bundled_config = None

            if platform.system() == 'Darwin':
                # macOS: Contents/Resources/config.json
                bundled_config = Path(sys.executable).parent.parent / 'Resources' / 'config.json'
            else:
                # Windows/Linux: same directory as executable
                bundled_config = Path(sys.executable).parent / 'config.json'

            # Also try _MEIPASS directory (PyInstaller temp directory)
            if not bundled_config.exists():
                meipass_bundled = Path(sys._MEIPASS) / 'config.json'
                if meipass_bundled.exists():
                    bundled_config = meipass_bundled

            if bundled_config and bundled_config.exists():
                try:
                    # Create config directory if it doesn't exist
                    config_path.parent.mkdir(parents=True, exist_ok=True)
                    shutil.copy2(bundled_config, config_path)
                    print(f"✓ Copied config from {bundled_config} to {config_path}")
                except Exception as e:
                    print(f"✗ Failed to copy bundled config: {e}")
                    # If copy fails, try to use bundled config directly
                    config_path = bundled_config
            else:
                print(f"✗ Bundled config not found at {bundled_config}")
                # Try to use current directory config as fallback
                current_dir_config = Path('.') / 'config.json'
                if current_dir_config.exists():
                    config_path = current_dir_config
                    print(f"✓ Using current directory config: {config_path}")
                else:
                    print(f"✗ No config file found at all")

    db_config = None
    last_user = ""
    saved_password_hash = ""

    if config_path.exists():
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
                db_config = config.get("db_config")
                last_user = config.get("last_user", "")
                saved_password_hash = config.get("saved_password_hash", "")
        except Exception as e:
            print(f"Failed to load config: {e}")

    # Create QApplication
    app = QApplication(sys.argv)

    # Set application icon
    if getattr(sys, 'frozen', False):
        # Running as compiled executable
        if platform.system() == 'Windows':
            icon_path = os.path.join(sys._MEIPASS, 'zb100_windows.ico')
        elif platform.system() == 'Darwin':
            icon_path = os.path.join(sys._MEIPASS, 'zb100_mac.icns')
        else:
            icon_path = None
    else:
        # Running as script
        if platform.system() == 'Windows':
            icon_path = 'zb100_windows.ico'
        elif platform.system() == 'Darwin':
            icon_path = 'zb100_mac.icns'
        else:
            icon_path = None

    if icon_path and os.path.exists(icon_path):
        app_icon = QIcon(icon_path)
        app.setWindowIcon(app_icon)

    # Check database config - if missing, start app without database authentication
    if not db_config:
        print("警告:未找到数据库配置,将跳过数据库认证")
        # Create main window directly without login
        main_window = ImageGeneratorWindow()
        main_window.show()
        sys.exit(app.exec())

    # Show login dialog
    login_dialog = LoginDialog(db_config, last_user, saved_password_hash)

    if login_dialog.exec() == QDialog.Accepted:
        # Login successful
        authenticated_user = login_dialog.authenticated_user
        remember_user = login_dialog.get_remember_user()
        remember_password = login_dialog.get_remember_password()
        password_hash = login_dialog.get_password_hash()

        # Save/clear credentials
        if config_path.exists():
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)

                if remember_user:
                    config["last_user"] = authenticated_user
                else:
                    config["last_user"] = ""

                if remember_password:
                    config["saved_password_hash"] = password_hash
                else:
                    config["saved_password_hash"] = ""

                with open(config_path, 'w', encoding='utf-8') as f:
                    json.dump(config, f, indent=2, ensure_ascii=False)
            except Exception as e:
                print(f"Failed to save config: {e}")

        # Show main window
        main_window = ImageGeneratorWindow()
        main_window.show()

        sys.exit(app.exec())
    else:
        # Login cancelled or failed
        sys.exit(0)


if __name__ == "__main__":
    main()