File size: 32,171 Bytes
79f5e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935a74e
 
 
 
79f5e3d
 
 
 
 
 
935a74e
 
 
 
 
79f5e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d962083
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f5e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935a74e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f5e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da05051
79f5e3d
da05051
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f5e3d
da05051
 
 
 
 
79f5e3d
 
 
 
 
 
da05051
79f5e3d
 
 
 
 
 
 
 
 
 
da05051
79f5e3d
 
 
da05051
79f5e3d
 
 
 
da05051
79f5e3d
 
 
 
da05051
79f5e3d
 
 
 
 
da05051
935a74e
d962083
935a74e
 
 
da05051
 
 
 
 
 
 
79f5e3d
da05051
 
 
 
79f5e3d
da05051
79f5e3d
da05051
 
 
 
79f5e3d
 
 
 
da05051
79f5e3d
 
 
da05051
79f5e3d
 
 
 
da05051
79f5e3d
 
 
 
da05051
79f5e3d
 
 
 
da05051
 
 
 
79f5e3d
d962083
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935a74e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f5e3d
 
da05051
 
 
79f5e3d
 
da05051
 
79f5e3d
da05051
79f5e3d
da05051
79f5e3d
 
 
 
da05051
79f5e3d
da05051
 
79f5e3d
 
 
da05051
eef8af8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f5e3d
 
 
da05051
 
79f5e3d
 
da05051
79f5e3d
 
 
 
da05051
935a74e
 
 
79f5e3d
da05051
 
 
 
 
 
 
 
 
79f5e3d
da05051
79f5e3d
da05051
 
 
 
79f5e3d
 
935a74e
eef8af8
 
 
935a74e
 
 
eef8af8
 
935a74e
eef8af8
 
935a74e
 
 
 
 
eef8af8
 
 
 
 
 
 
 
 
 
 
 
 
79f5e3d
 
 
 
 
 
 
935a74e
 
 
 
eef8af8
 
935a74e
 
 
 
79f5e3d
 
 
 
da05051
79f5e3d
 
 
 
 
 
da05051
 
79f5e3d
 
da05051
79f5e3d
 
 
 
da05051
79f5e3d
 
 
 
 
 
da05051
79f5e3d
 
 
 
 
 
 
da05051
79f5e3d
 
da05051
79f5e3d
 
 
 
 
 
da05051
79f5e3d
da05051
79f5e3d
 
da05051
79f5e3d
 
 
 
da05051
 
 
 
 
 
 
 
 
 
 
 
 
 
79f5e3d
 
da05051
79f5e3d
 
da05051
79f5e3d
 
 
 
 
 
 
 
 
da05051
79f5e3d
da05051
 
79f5e3d
 
 
da05051
79f5e3d
 
 
da05051
79f5e3d
 
 
da05051
79f5e3d
da05051
 
 
 
 
79f5e3d
 
 
 
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
/**

 * server.js

 * Banana Pro AI 生图平台 - 后端服务

 * 支持多图上传的 ES6 模块化版本

 */

import express from 'express';
import cookieParser from 'cookie-parser';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
import crypto from 'crypto';

// ============================================
// 配置初始化模块
// ============================================
dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const parsePositiveInt = (value, fallback) => {
    const parsed = parseInt(value, 10);
    return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
};

const parseSitePasswords = (value, fallback) => {
    if (typeof value !== 'string' || value.trim() === '') {
        return fallback ? [fallback] : [];
    }
    return value
        .split(',')
        .map((item) => item.trim())
        .filter(Boolean);
};


const CONFIG = {
    port: process.env.PORT || 3000,
    apiKey: process.env.GEMINI_API_KEY || process.env.OPENAI_API_KEY || '1362204768',
    apiUrl: process.env.GEMINI_API_URL || process.env.OPENAI_API_URL || 'http://35.208.190.208:8317/v1beta/models/{model}:generateContent',
    sitePassword: process.env.SITE_PASSWORD || '123456',
    sitePasswords: parseSitePasswords(process.env.SITE_PASSWORD, '123456'),
    modelName: process.env.GEMINI_MODEL || process.env.MODEL_NAME || 'gemini-3-pro-image-preview',
    maxImages: 16,
    maxPublicGalleryItems: parsePositiveInt(process.env.PUBLIC_GALLERY_LIMIT, 80)
};

// 调试输出环境变量
console.log('[DEBUG] GEMINI_API_URL:', process.env.GEMINI_API_URL || process.env.OPENAI_API_URL);
console.log(`[DEBUG] 最终 CONFIG.apiUrl:`, CONFIG.apiUrl);
console.log('[DEBUG] Model:', CONFIG.modelName);

const DATA_DIR = path.join(__dirname, 'data');
const PUBLIC_GALLERY_FILE = path.join(DATA_DIR, 'public-gallery.json');
const STATS_FILE = path.join(DATA_DIR, 'usage-stats.json');
const GENERATED_DIR = path.join(DATA_DIR, 'generated');

// ============================================
// Express 应用初始化
// ============================================
const app = express();

app.use(express.json({ limit: '200mb' }));
app.use(express.urlencoded({ extended: true, limit: '200mb' }));
app.use(cookieParser());
app.use(express.static(__dirname));
app.use('/generated', express.static(GENERATED_DIR));

// ============================================
// 认证中间件
// ============================================
const authMiddleware = (req, res, next) => {
    const token = req.cookies.auth_token;
    if (CONFIG.sitePasswords.includes(token)) {
        next();
    } else {
        res.status(401).json({
            success: false,
            error: 'Unauthorized',
            message: '请先登录'
        });
    }
};

// ============================================
// 图片数据解析模块
// ============================================
const ImageParser = {
    /**

     * 从 assistant content 中提取 base64 图片数据

     * 格式: ![Generated Image](data:image/png;base64,xxxxx)

     */
    extractBase64FromMarkdown(content) {
        if (!content || typeof content !== 'string') {
            return null;
        }

        // 匹配 Markdown 图片格式
        const markdownPattern = /!\[.*?\]\((data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/=]+)\)/g;
        const matches = content.match(markdownPattern);

        if (matches && matches.length > 0) {
            const dataUrlMatch = matches[0].match(/\((data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/=]+)\)/);
            if (dataUrlMatch && dataUrlMatch[1]) {
                return dataUrlMatch[1];
            }
        }

        // 备用:直接匹配 data:image 格式
        const directPattern = /(data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/=]+)/;
        const directMatch = content.match(directPattern);
        if (directMatch && directMatch[1]) {
            return directMatch[1];
        }

        return null;
    },

    isValidBase64Image(base64Data) {
        if (!base64Data) return false;
        return base64Data.startsWith('data:image/');
    }
};

// ============================================
// 消息构建模块
// ============================================
const MessageBuilder = {
    /**

     * Build Gemini parts with prompt and base64 images.

     * @param {string} prompt - User prompt

     * @param {Array<string>} images - base64 data URLs

     * @returns {Array} - Gemini parts array

     */
    buildParts(prompt, images = []) {
        const parts = [];

        if (Array.isArray(images)) {
            images.forEach((imageData) => {
                const matches = imageData.match(/^data:(image\/[a-zA-Z]+);base64,(.+)$/);
                if (matches) {
                    parts.push({
                        inline_data: {
                            mime_type: matches[1],
                            data: matches[2]
                        }
                    });
                }
            });
        }

        if (prompt) {
            parts.push({ text: prompt });
        }

        return parts;
    }
};

// ============================================
// API 请求模块
// ============================================
const APIService = {
    /**

     * Call Gemini generateContent API

     * @param {string} prompt - User prompt

     * @param {Array<string>} images - Uploaded images

     */
    async generateImage(prompt, images = [], options = {}) {
        const parts = MessageBuilder.buildParts(prompt, images);

        const payload = {
            contents: [{ parts }]
        };

        const imageConfig = {};
        if (options.imageSize) {
            imageConfig.imageSize = options.imageSize;
        }
        if (options.aspectRatio) {
            imageConfig.aspectRatio = options.aspectRatio;
        }
        if (Object.keys(imageConfig).length > 0) {
            payload.generationConfig = { imageConfig };
        }

        const apiUrl = CONFIG.apiUrl.includes('{model}')
            ? CONFIG.apiUrl.replace('{model}', CONFIG.modelName)
            : CONFIG.apiUrl;

        console.log(`[${new Date().toISOString()}] Request model: ${CONFIG.modelName}`);
        console.log(`[${new Date().toISOString()}] Prompt: ${prompt.substring(0, 100)}...`);
        console.log(`[${new Date().toISOString()}] Images attached: ${images.length}`);

        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'x-goog-api-key': CONFIG.apiKey
            },
            body: JSON.stringify(payload)
        });

        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`API request failed: ${response.status} - ${errorText}`);
        }

        return await response.json();
    },

    /**

     * Extract image from Gemini response

     */
    extractImageFromResponse(data) {
        console.log(`[${new Date().toISOString()}] API response type:`, typeof data);
        console.log(`[${new Date().toISOString()}] API response keys:`, Object.keys(data || {}));

        if (data.error) {
            const message = typeof data.error === 'string'
                ? data.error
                : (data.error.message || JSON.stringify(data.error));
            throw new Error(`API returned error: ${message}`);
        }

        const candidates = Array.isArray(data.candidates) ? data.candidates : [];
        for (const candidate of candidates) {
            const parts = candidate?.content?.parts || [];
            for (const part of parts) {
                const inlineData = part.inlineData || part.inline_data;
                if (inlineData && inlineData.data) {
                    const mimeType = inlineData.mimeType || inlineData.mime_type || 'image/png';
                    return `data:${mimeType};base64,${inlineData.data}`;
                }
                if (part.text) {
                    const imageData = ImageParser.extractBase64FromMarkdown(part.text);
                    if (imageData && ImageParser.isValidBase64Image(imageData)) {
                        return imageData;
                    }
                }
            }
        }

        if (data.data && data.data[0]) {
            if (data.data[0].b64_json) {
                console.log(`[${new Date().toISOString()}] Using DALL-E b64_json format`);
                return `data:image/png;base64,${data.data[0].b64_json}`;
            }
            if (data.data[0].url) {
                console.log(`[${new Date().toISOString()}] Using DALL-E URL format`);
                return data.data[0].url;
            }
        }

        console.log(`[${new Date().toISOString()}] Full API response:`, JSON.stringify(data, null, 2));
        throw new Error('Unable to extract image data from API response.');
    }
};

// ============================================
// Public gallery store
// ============================================
const generateId = () => {
    if (typeof crypto.randomUUID === 'function') {
        return crypto.randomUUID();
    }
    return crypto.randomBytes(16).toString('hex');
};

const generateDeleteToken = () => crypto.randomBytes(24).toString('hex');

const mimeToExt = (mimeType) => {
    const normalized = String(mimeType || '').toLowerCase();
    if (normalized === 'image/jpeg' || normalized === 'image/jpg') return 'jpg';
    if (normalized === 'image/webp') return 'webp';
    if (normalized === 'image/gif') return 'gif';
    return 'png';
};

const GeneratedImageStore = {
    async ensureDir() {
        await fs.mkdir(GENERATED_DIR, { recursive: true });
    },

    async saveDataUrl(dataUrl) {
        if (!dataUrl || typeof dataUrl !== 'string') return null;
        const match = dataUrl.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/);
        if (!match) return null;

        const mimeType = match[1];
        const base64Data = match[2];
        const ext = mimeToExt(mimeType);
        const id = generateId();
        const filename = `${id}.${ext}`;
        const filePath = path.join(GENERATED_DIR, filename);

        await this.ensureDir();
        await fs.writeFile(filePath, Buffer.from(base64Data, 'base64'));

        return {
            id: filename,
            url: `/generated/${filename}`,
            mimeType
        };
    },

    async resolveUrl(id) {
        if (!id || typeof id !== 'string') return null;
        const safeName = path.basename(id);
        const filePath = path.join(GENERATED_DIR, safeName);
        try {
            await fs.access(filePath);
            return `/generated/${safeName}`;
        } catch {
            return null;
        }
    }
};

const PublicGalleryStore = {
    async ensureFile() {
        await fs.mkdir(DATA_DIR, { recursive: true });
        try {
            await fs.access(PUBLIC_GALLERY_FILE);
        } catch {
            await fs.writeFile(PUBLIC_GALLERY_FILE, '[]', 'utf-8');
        }
    },

    async readData() {
        await this.ensureFile();
        try {
            const raw = await fs.readFile(PUBLIC_GALLERY_FILE, 'utf-8');
            const parsed = JSON.parse(raw);
            return Array.isArray(parsed) ? parsed : [];
        } catch (error) {
            console.error(`[${new Date().toISOString()}] 读取公共画廊数据失败:`, error);
            return [];
        }
    },

    async writeData(items) {
        await this.ensureFile();
        await fs.writeFile(PUBLIC_GALLERY_FILE, JSON.stringify(items, null, 2), 'utf-8');
    },

    async getAll() {
        return await this.readData();
    },

    async add(entry) {
        const items = await this.readData();
        items.unshift(entry);
        if (items.length > CONFIG.maxPublicGalleryItems) {
            items.splice(CONFIG.maxPublicGalleryItems);
        }
        await this.writeData(items);
        return entry;
    },

    async remove(id, token) {
        const items = await this.readData();
        const targetIndex = items.findIndex(item => item.id === id);

        if (targetIndex === -1) {
            return { found: false };
        }

        if (items[targetIndex].deleteToken !== token) {
            return { found: true, authorized: false };
        }

        items.splice(targetIndex, 1);
        await this.writeData(items);
        return { found: true, authorized: true };
    }
};

// ============================================
// Usage stats store
// ============================================
const DEFAULT_STATS = {
    totalRequests: 0,
    successCount: 0,
    failureCount: 0,
    lastRequestAt: null,
    lastSuccessAt: null,
    lastFailureAt: null,
    lastError: null,
    latencyTotalMs: 0,
    latencyCount: 0,
    avgLatencyMs: 0,
    shareRequests: 0,
    shareSuccess: 0,
    shareFailure: 0,
    lastShareAt: null,
    lastShareSuccessAt: null,
    lastShareFailureAt: null,
    lastShareError: null,
    byDay: {}
};

const StatsStore = {
    data: { ...DEFAULT_STATS },
    activeRequests: 0,
    flushTimer: null,

    async init() {
        await fs.mkdir(DATA_DIR, { recursive: true });
        try {
            const raw = await fs.readFile(STATS_FILE, 'utf-8');
            const parsed = JSON.parse(raw);
            this.data = {
                ...DEFAULT_STATS,
                ...(parsed && typeof parsed === 'object' ? parsed : {}),
                byDay: parsed && typeof parsed.byDay === 'object' ? parsed.byDay : {}
            };
        } catch (error) {
            if (error && error.code !== 'ENOENT') {
                console.error(`[${new Date().toISOString()}] Failed to load stats:`, error);
            }
            this.data = { ...DEFAULT_STATS };
        }
    },

    scheduleFlush() {
        if (this.flushTimer) return;
        this.flushTimer = setTimeout(() => this.flush(), 2000);
    },

    async flush() {
        clearTimeout(this.flushTimer);
        this.flushTimer = null;
        try {
            await fs.writeFile(STATS_FILE, JSON.stringify(this.data, null, 2), 'utf-8');
        } catch (error) {
            console.error(`[${new Date().toISOString()}] Failed to write stats:`, error);
        }
    },

    pruneOldDays(maxDays = 90) {
        const keys = Object.keys(this.data.byDay || {}).sort();
        if (keys.length <= maxDays) return;
        const toRemove = keys.slice(0, keys.length - maxDays);
        toRemove.forEach((key) => delete this.data.byDay[key]);
    },

    record({ ok, durationMs, errorMessage }) {
        const now = new Date();
        const dayKey = now.toISOString().slice(0, 10);
        const dayStats = this.data.byDay[dayKey] || {
            total: 0,
            success: 0,
            failure: 0,
            shareTotal: 0,
            shareSuccess: 0,
            shareFailure: 0
        };

        this.data.totalRequests += 1;
        dayStats.total += 1;
        this.data.lastRequestAt = now.toISOString();

        if (ok) {
            this.data.successCount += 1;
            dayStats.success += 1;
            this.data.lastSuccessAt = now.toISOString();
        } else {
            this.data.failureCount += 1;
            dayStats.failure += 1;
            this.data.lastFailureAt = now.toISOString();
            if (errorMessage) {
                this.data.lastError = String(errorMessage).slice(0, 240);
            }
        }

        if (Number.isFinite(durationMs)) {
            this.data.latencyTotalMs += durationMs;
            this.data.latencyCount += 1;
            this.data.avgLatencyMs = Math.round(
                this.data.latencyTotalMs / Math.max(1, this.data.latencyCount)
            );
        }

        this.data.byDay[dayKey] = dayStats;
        this.pruneOldDays();
        this.scheduleFlush();
    },

    recordShare({ ok, errorMessage }) {
        const now = new Date();
        const dayKey = now.toISOString().slice(0, 10);
        const dayStats = this.data.byDay[dayKey] || {
            total: 0,
            success: 0,
            failure: 0,
            shareTotal: 0,
            shareSuccess: 0,
            shareFailure: 0
        };

        this.data.shareRequests += 1;
        this.data.lastShareAt = now.toISOString();
        dayStats.shareTotal = (dayStats.shareTotal || 0) + 1;

        if (ok) {
            this.data.shareSuccess += 1;
            this.data.lastShareSuccessAt = now.toISOString();
            dayStats.shareSuccess = (dayStats.shareSuccess || 0) + 1;
        } else {
            this.data.shareFailure += 1;
            this.data.lastShareFailureAt = now.toISOString();
            dayStats.shareFailure = (dayStats.shareFailure || 0) + 1;
            if (errorMessage) {
                this.data.lastShareError = String(errorMessage).slice(0, 240);
            }
        }

        this.data.byDay[dayKey] = dayStats;
        this.pruneOldDays();
        this.scheduleFlush();
    },

    snapshot() {
        return { ...this.data };
    }
};

StatsStore.init().catch((error) => {
    console.error(`[${new Date().toISOString()}] Stats init failed:`, error);
});

// ============================================
// Routes
// ============================================

// Login
app.post('/api/login', (req, res) => {
    const { password } = req.body;

    if (!password) {
        return res.status(400).json({
            success: false,
            message: '\u8bf7\u8f93\u5165\u5bc6\u7801'
        });
    }

    if (CONFIG.sitePasswords.includes(password)) {
        res.cookie('auth_token', password, {
            maxAge: 30 * 24 * 60 * 60 * 1000,
            httpOnly: true,
            sameSite: 'strict'
        });

        console.log(`[${new Date().toISOString()}] User login success`);

        res.json({
            success: true,
            message: '\u767b\u5f55\u6210\u529f'
        });
    } else {
        res.status(403).json({
            success: false,
            message: '\u5bc6\u7801\u9519\u8bef'
        });
    }
});

// Auth status
app.get('/api/check-auth', (req, res) => {
    const token = req.cookies.auth_token;
    res.json({ authenticated: CONFIG.sitePasswords.includes(token) });
});

// Generate image (multi-image)
app.post('/api/generate', authMiddleware, async (req, res) => {
    const { prompt, images, preferUrl, imageSize, aspectRatio } = req.body;
    const requestStart = Date.now();
    StatsStore.activeRequests += 1;
    let recorded = false;

    const recordOnce = (ok, errorMessage) => {
        if (recorded) return;
        recorded = true;
        const durationMs = Date.now() - requestStart;
        StatsStore.record({ ok, durationMs, errorMessage });
    };

    const fail = (status, message) => {
        recordOnce(false, message);
        StatsStore.activeRequests = Math.max(0, StatsStore.activeRequests - 1);
        return res.status(status).json({
            success: false,
            message
        });
    };

    if (!prompt || typeof prompt !== 'string') {
        return fail(400, '\u8bf7\u63d0\u4f9b\u6709\u6548\u7684\u63d0\u793a\u8bcd');
    }

    const trimmedPrompt = prompt.trim();
    if (trimmedPrompt.length === 0) {
        return fail(400, '\u63d0\u793a\u8bcd\u4e0d\u80fd\u4e3a\u7a7a');
    }

    if (trimmedPrompt.length > 32000) {
        return fail(400, '\u63d0\u793a\u8bcd\u8fc7\u957f\uff0c\u8bf7\u9650\u5236\u5728 32000 \u5b57\u7b26\u4ee5\u5185');
    }

    const uploadedImages = images || [];
    if (uploadedImages.length > CONFIG.maxImages) {
        return fail(400, `\u6700\u591a\u53ea\u80fd\u4e0a\u4f20 ${CONFIG.maxImages} \u5f20\u56fe\u7247`);
    }

    for (let i = 0; i < uploadedImages.length; i++) {
        if (!ImageParser.isValidBase64Image(uploadedImages[i])) {
            return fail(400, `\u7b2c ${i + 1} \u5f20\u56fe\u7247\u683c\u5f0f\u65e0\u6548`);
        }
    }

    try {
        console.log(`[${new Date().toISOString()}] Generate image start`);
        console.log(`[${new Date().toISOString()}] API URL: ${CONFIG.apiUrl}`);
        console.log('[DEBUG] Model:', CONFIG.modelName);
        console.log(`[${new Date().toISOString()}] API key: ${CONFIG.apiKey.substring(0, 10)}...`);

        const allowImageConfig = /gemini-3/i.test(CONFIG.modelName);
        const resolvedImageSize = typeof imageSize === 'string'
            ? imageSize
            : (preferUrl ? '1K' : null);
        const resolvedAspectRatio = typeof aspectRatio === 'string' ? aspectRatio : null;
        const apiOptions = {};
        if (allowImageConfig) {
            if (resolvedImageSize) {
                apiOptions.imageSize = resolvedImageSize;
            }
            if (resolvedAspectRatio) {
                apiOptions.aspectRatio = resolvedAspectRatio;
            }
        }

        const apiResponse = await APIService.generateImage(trimmedPrompt, uploadedImages, apiOptions);
        const imageData = APIService.extractImageFromResponse(apiResponse);
        const wantsUrl = Boolean(preferUrl);
        let imageUrl = null;
        let imageId = null;

        if (typeof imageData === 'string' && imageData.startsWith('data:image/')) {
            if (wantsUrl) {
                try {
                    const saved = await GeneratedImageStore.saveDataUrl(imageData);
                    if (saved) {
                        imageUrl = saved.url;
                        imageId = saved.id;
                    }
                } catch (saveError) {
                    console.error(`[${new Date().toISOString()}] Save generated image failed:`, saveError);
                }
            }
        } else if (typeof imageData === 'string') {
            imageUrl = imageData;
        }

        console.log(`[${new Date().toISOString()}] Image generated`);

        recordOnce(true);
        const responsePayload = {
            success: true,
            imageUrl,
            imageId,
            prompt: trimmedPrompt,
            inputImages: uploadedImages,
            timestamp: new Date().toISOString()
        };

        if (!wantsUrl || !imageUrl) {
            responsePayload.image = imageData;
        }

        res.json(responsePayload);

    } catch (error) {
        recordOnce(false, error.message);
        console.error(`[${new Date().toISOString()}] Generate failed:`, error.message);
        console.error(`[${new Date().toISOString()}] Stack:`, error.stack);

        let errorMessage = error.message;
        if (error.message.includes('API\u8fd4\u56de\u9519\u8bef: \u672a\u6388\u6743') || error.message.includes('401') || error.message.includes('Unauthorized')) {
            errorMessage = '\u0041\u0050\u0049\u8ba4\u8bc1\u5931\u8d25\uff0c\u8bf7\u68c0\u67e5\u0041\u0050\u0049\u5bc6\u94a5\u914d\u7f6e';
        } else if (error.message.includes('ECONNREFUSED') || error.message.includes('ENOTFOUND')) {
            errorMessage = '\u65e0\u6cd5\u8fde\u63a5\u5230\u0041\u0050\u0049\u670d\u52a1\u5668\uff0c\u8bf7\u68c0\u67e5\u7f51\u7edc\u8fde\u63a5\u548c\u0041\u0050\u0049\u5730\u5740\u914d\u7f6e';
        } else if (error.message.includes('timeout')) {
            errorMessage = '\u0041\u0050\u0049\u8bf7\u6c42\u8d85\u65f6\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5';
        }

        res.status(500).json({
            success: false,
            message: errorMessage || '\u56fe\u7247\u751f\u6210\u5931\u8d25\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5'
        });
    } finally {
        StatsStore.activeRequests = Math.max(0, StatsStore.activeRequests - 1);
    }
});

// Public gallery - list
app.get('/api/public-gallery', async (req, res) => {
    try {
        console.log(`[${new Date().toISOString()}] Public gallery loading`);
        const lite = req.query.lite === '1';
        const items = await PublicGalleryStore.getAll();
        let updated = false;
        const sanitized = [];

        for (const item of items) {
            const { deleteToken, ...rest } = item;

            if (rest.image && typeof rest.image === 'string' && ImageParser.isValidBase64Image(rest.image)) {
                try {
                    const saved = await GeneratedImageStore.saveDataUrl(rest.image);
                    if (saved) {
                        item.imageUrl = saved.url;
                        item.imageId = saved.id;
                        delete item.image;
                        rest.imageUrl = saved.url;
                        rest.imageId = saved.id;
                        delete rest.image;
                        updated = true;
                    }
                } catch (error) {
                    console.error(`[${new Date().toISOString()}] Public gallery image migrate failed:`, error);
                }
            }

            if (lite) {
                if (Array.isArray(rest.inputImages)) {
                    rest.inputCount = rest.inputImages.length;
                }
                delete rest.inputImages;
            }

            sanitized.push(rest);
        }

        if (updated) {
            await PublicGalleryStore.writeData(items);
        }

        console.log(`[${new Date().toISOString()}] Public gallery items: ${sanitized.length}`);

        res.json({
            success: true,
            items: sanitized
        });
    } catch (error) {
        console.error(`[${new Date().toISOString()}] Public gallery load failed:`, error);
        console.error(`[${new Date().toISOString()}] Stack:`, error.stack);
        res.status(500).json({
            success: false,
            message: '\u65e0\u6cd5\u52a0\u8f7d\u516c\u5171\u753b\u5eca\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5'
        });
    }
});

// Public gallery - publish
app.post('/api/public-gallery', authMiddleware, async (req, res) => {
    const { prompt, image, imageUrl, imageId, inputImages } = req.body;
    let shareRecorded = false;

    const recordShareOnce = (ok, errorMessage) => {
        if (shareRecorded) return;
        shareRecorded = true;
        StatsStore.recordShare({ ok, errorMessage });
    };

    const failShare = (status, message) => {
        recordShareOnce(false, message);
        return res.status(status).json({
            success: false,
            message
        });
    };

    if (!prompt || typeof prompt !== 'string' || !prompt.trim()) {
        return failShare(400, '\u8bf7\u8f93\u5165\u6709\u6548\u7684\u63d0\u793a\u8bcd');
    }

    let finalImage = null;
    let finalImageUrl = null;
    let finalImageId = null;

    if (image && typeof image === 'string' && ImageParser.isValidBase64Image(image)) {
        finalImage = image;
    } else if (imageUrl && typeof imageUrl === 'string') {
        finalImageUrl = imageUrl.trim();
        finalImage = finalImageUrl;
    } else if (imageId && typeof imageId === 'string') {
        finalImageUrl = await GeneratedImageStore.resolveUrl(imageId);
        finalImage = finalImageUrl;
    }

    if (!finalImage) {
        return failShare(400, '\u8bf7\u63d0\u4f9b\u6709\u6548\u7684\u56fe\u7247\u6570\u636e');
    }

    if (finalImage && typeof finalImage === 'string' && ImageParser.isValidBase64Image(finalImage)) {
        try {
            const saved = await GeneratedImageStore.saveDataUrl(finalImage);
            if (saved) {
                finalImageUrl = saved.url;
                finalImageId = saved.id;
                finalImage = null;
            }
        } catch (error) {
            console.error(`[${new Date().toISOString()}] Public gallery save image failed:`, error);
        }
    }

    const sanitizedRefs = Array.isArray(inputImages)
        ? inputImages
            .filter(img => typeof img === 'string' && ImageParser.isValidBase64Image(img))
            .slice(0, CONFIG.maxImages)
        : [];

    const entry = {
        id: generateId(),
        prompt: prompt.trim(),
        image: finalImage,
        imageUrl: finalImageUrl,
        imageId: finalImageId,
        inputImages: sanitizedRefs,
        timestamp: new Date().toISOString(),
        deleteToken: generateDeleteToken()
    };

    try {
        await PublicGalleryStore.add(entry);
        const { deleteToken, ...publicItem } = entry;
        recordShareOnce(true);
        res.json({
            success: true,
            item: publicItem,
            deleteToken
        });
    } catch (error) {
        recordShareOnce(false, error.message);
        console.error(`[${new Date().toISOString()}] Public gallery publish failed:`, error);
        res.status(500).json({
            success: false,
            message: '\u53d1\u5e03\u5931\u8d25\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5'
        });
    }
});

// Public gallery - delete
app.delete('/api/public-gallery/:id', async (req, res) => {
    const id = req.params.id;

    if (!id || typeof id !== 'string') {
        return res.status(400).json({
            success: false,
            message: '\u65e0\u6548\u7684\u4f5c\u54c1 ID'
        });
    }

    try {
        const items = await PublicGalleryStore.readData();
        const targetIndex = items.findIndex(item => item.id === id);

        if (targetIndex == -1) {
            return res.status(404).json({
                success: false,
                message: '\u4f5c\u54c1\u4e0d\u5b58\u5728\u6216\u5df2\u88ab\u5220\u9664'
            });
        }

        items.splice(targetIndex, 1);
        await PublicGalleryStore.writeData(items);

        res.json({ success: true, message: '\u5220\u9664\u6210\u529f' });
    } catch (error) {
        console.error(`[${new Date().toISOString()}] Public gallery delete failed:`, error);
        res.status(500).json({
            success: false,
            message: '\u5220\u9664\u5931\u8d25\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5'
        });
    }
});

// Usage stats
app.get('/api/stats', authMiddleware, (req, res) => {
    const stats = StatsStore.snapshot();
    res.json({
        success: true,
        stats: {
            ...stats,
            activeRequests: StatsStore.activeRequests,
            uptimeSec: Math.floor(process.uptime())
        }
    });
});

// Logout
app.post('/api/logout', (req, res) => {
    res.clearCookie('auth_token');
    res.json({ success: true, message: '\u5df2\u9000\u51fa\u767b\u5f55' });
});

// Health
app.get('/api/health', (req, res) => {
    res.json({
        status: 'ok',
        timestamp: new Date().toISOString(),
        model: CONFIG.modelName,
        maxImages: CONFIG.maxImages
    });
});

// Error handling
app.use((err, req, res, next) => {
    console.error(`[${new Date().toISOString()}] Server error:`, err);
    res.status(500).json({ success: false, message: '\u670d\u52a1\u5668\u5185\u90e8\u9519\u8bef' });
});

app.use((req, res) => {
    res.status(404).json({ success: false, message: '\u63a5\u53e3\u4e0d\u5b58\u5728' });
});

// ============================================
// Start server
// ============================================
app.listen(CONFIG.port, () => {
    console.log('==========================================');
    console.log('Banana Pro AI Studio started');
    console.log('==========================================');
    console.log(`Server: http://localhost:${CONFIG.port}`);
    console.log(`Model: ${CONFIG.modelName}`);
    console.log(`Max images: ${CONFIG.maxImages}`);
    console.log(`API URL: ${CONFIG.apiUrl}`);
    console.log('[DEBUG] Model:', CONFIG.modelName);
    console.log('==========================================');
});

export default app;