File size: 49,406 Bytes
b7560a4
 
790de78
0afb612
7363663
b7560a4
 
 
b63441d
 
fce556e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0afb612
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bff263
0afb612
 
 
 
 
 
 
 
1bff263
0afb612
 
 
 
 
 
 
 
 
 
 
 
 
1bff263
0afb612
 
 
 
 
 
 
 
 
 
 
 
 
 
b7560a4
0afb612
 
 
b7560a4
0afb612
b7560a4
0afb612
b7560a4
 
 
 
 
 
 
 
0afb612
 
 
 
 
 
 
b7560a4
0afb612
 
b7560a4
 
 
 
0afb612
b7560a4
 
 
 
0afb612
b7560a4
 
0afb612
 
b7560a4
 
 
 
 
 
 
0afb612
9d621ef
b7560a4
 
 
 
 
 
0afb612
 
 
 
 
 
 
b7560a4
0afb612
 
b7560a4
 
 
 
 
 
 
 
da2c691
773dbcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da2c691
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7560a4
 
 
 
0afb612
b7560a4
 
 
 
 
 
 
 
 
 
 
 
 
 
0afb612
b7560a4
 
 
 
 
 
 
0afb612
 
 
 
 
 
 
b7560a4
0afb612
 
b7560a4
 
 
 
 
 
 
0afb612
b7560a4
 
 
 
 
 
 
 
 
 
0afb612
b7560a4
 
 
 
 
 
 
 
08a9a1b
 
0afb612
b7560a4
 
08a9a1b
 
0afb612
b7560a4
0afb612
08a9a1b
0afb612
 
08a9a1b
 
 
0afb612
 
08a9a1b
 
0afb612
 
08a9a1b
 
 
 
 
 
 
0afb612
08a9a1b
b7560a4
 
 
418f3d8
 
b7560a4
 
0afb612
b7560a4
0afb612
b7560a4
0afb612
08a9a1b
dcfc8f8
 
18c248a
 
0afb612
08a9a1b
 
 
 
 
b7560a4
 
08a9a1b
b7560a4
 
 
 
 
 
0afb612
790de78
 
 
0afb612
 
 
 
 
790de78
 
 
0afb612
 
d5c2fad
0afb612
d5c2fad
 
0afb612
d5c2fad
 
0afb612
790de78
 
 
0afb612
 
 
 
02edaa7
 
 
 
 
0afb612
da2c691
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0afb612
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418f3d8
0afb612
 
 
418f3d8
0afb612
418f3d8
0afb612
 
 
 
 
 
790de78
0afb612
 
 
227619b
0afb612
790de78
0afb612
 
790de78
 
 
 
227619b
 
418f3d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790de78
 
0afb612
da2c691
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790de78
227619b
 
418f3d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790de78
 
418f3d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b63441d
 
418f3d8
 
 
 
 
 
 
 
 
 
 
 
 
 
b63441d
418f3d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790de78
0afb612
227619b
 
418f3d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0afb612
 
 
 
 
 
 
 
 
 
d5c2fad
0afb612
 
 
 
 
 
 
 
 
 
53be694
 
0afb612
 
 
 
 
 
 
 
02edaa7
 
 
 
 
0afb612
da2c691
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0afb612
 
d5c2fad
0afb612
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1a892e
0afb612
 
d5c2fad
790de78
0afb612
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1a892e
0afb612
 
 
 
 
 
e1a892e
0afb612
 
 
 
 
 
 
 
790de78
 
 
227619b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da2c691
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227619b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7363663
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227619b
18c248a
 
 
8c596c7
18c248a
227619b
18c248a
 
 
 
 
 
 
 
 
 
227619b
18c248a
 
 
 
 
 
 
 
227619b
8c596c7
 
 
 
 
 
 
 
18c248a
227619b
8c596c7
18c248a
 
 
da2c691
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18c248a
227619b
8c596c7
 
 
 
 
 
 
 
18c248a
8c596c7
 
18c248a
 
227619b
 
8c596c7
 
 
 
 
 
 
18c248a
8c596c7
 
 
 
 
227619b
 
8c596c7
 
 
 
18c248a
8c596c7
227619b
8c596c7
 
 
18c248a
 
227619b
18c248a
8c596c7
 
 
 
 
 
 
 
 
 
18c248a
 
 
 
4becc1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7560a4
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
import express from 'express';
import githubService from '../services/githubService.js';
import screenshotService from '../services/screenshotService.js';
// 修正导入路径:从 backend/src 向上两级到 app,再进入 shared
import { generateSlideHTML, generateExportPage, exportPPTToJSON, generateHTMLPresentation } from '../../../shared/export-utils.js';

const router = express.Router();

// 前端导出图片功能已移除,直接使用screenshotService

// 辅助函数:生成SVG - 改进版,支持更精确的PPT渲染
function generateSlideSVG(slide, pptData, options = {}) {
  const { width = 1000, height = 562 } = options;
  
  // 处理背景
  let backgroundStyle = '#ffffff';
  if (slide.background) {
    if (slide.background.type === 'solid') {
      backgroundStyle = slide.background.color || '#ffffff';
    } else if (slide.background.type === 'gradient' && slide.background.gradient) {
      // SVG渐变处理
      const colors = slide.background.gradient.colors || [];
      if (colors.length > 0) {
        backgroundStyle = colors[0].color || '#ffffff';
      }
    }
  }
  
  // 生成渐变定义(如果需要)
  let gradientDefs = '';
  if (slide.background?.type === 'gradient' && slide.background.gradient?.colors) {
    const colors = slide.background.gradient.colors;
    const gradientId = 'bg-gradient';
    if (slide.background.gradient.type === 'linear') {
      gradientDefs = `

        <defs>

          <linearGradient id="${gradientId}" x1="0%" y1="0%" x2="100%" y2="0%"> 

            ${colors.map((color, index) => 

              `<stop offset="${(index / (colors.length - 1)) * 100}%" style="stop-color:${color.color};stop-opacity:1" />`

            ).join('')}

          </linearGradient>

        </defs>

      `;
      backgroundStyle = `url(#${gradientId})`;
    }
  }
  
  // 渲染元素
  const elementsHTML = slide.elements.map(element => {
    const x = element.left || 0;
    const y = element.top || 0;
    const w = element.width || 100;
    const h = element.height || 100;
    const rotation = element.rotate || 0;
    
    // 变换属性
    const transform = rotation !== 0 ? `transform="rotate(${rotation} ${x + w/2} ${y + h/2})"` : '';
    
    if (element.type === 'text') {
      const fontSize = element.fontSize || 16;
      const fontFamily = element.fontName || 'Arial, sans-serif';
      const color = element.defaultColor || element.color || '#000000';
      const fontWeight = element.bold ? 'bold' : 'normal';
      const fontStyle = element.italic ? 'italic' : 'normal';
      const textDecoration = element.underline ? 'underline' : 'none';
      const textAnchor = element.align === 'center' ? 'middle' : element.align === 'right' ? 'end' : 'start';
      
      // 计算文本位置
      let textX = x + 10;
      if (element.align === 'center') textX = x + w/2;
      else if (element.align === 'right') textX = x + w - 10;
      
      // 处理多行文本
      const content = (element.content || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
      const lines = content.split('\n');
      
      return `

        <g ${transform}>

          ${lines.map((line, index) => `

            <text x="${textX}" y="${y + fontSize + (index * fontSize * 1.2)}" 

                  font-family="${fontFamily}" 

                  font-size="${fontSize}" 

                  fill="${color}" 

                  font-weight="${fontWeight}"

                  font-style="${fontStyle}" 

                  text-decoration="${textDecoration}"

                  text-anchor="${textAnchor}">${line}</text>

          `).join('')}

        </g>

      `;
    }
    
    if (element.type === 'shape') {
      const fill = element.fill || '#cccccc';
      const stroke = element.outline?.color || 'none';
      const strokeWidth = element.outline?.width || 0;
      
      if (element.shape === 'ellipse') {
        const cx = x + w/2;
        const cy = y + h/2;
        const rx = w/2;
        const ry = h/2;
        return `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${transform}/>`;
      }
      
      // 默认矩形
      const borderRadius = element.borderRadius || 0;
      if (borderRadius > 0) {
        return `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${borderRadius}" ry="${borderRadius}" fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${transform}/>`;
      }
      return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${fill}" stroke="${stroke}" stroke-width="${strokeWidth}" ${transform}/>`;
    }
    
    if (element.type === 'image' && element.src) {
      // 检查是否是base64图片
      if (element.src.startsWith('data:image/')) {
        return `<image x="${x}" y="${y}" width="${w}" height="${h}" href="${element.src}" ${transform}/>`;
      }
      // 外部图片 - 在SVG中可能有跨域问题,显示占位符
      return `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="#f0f0f0" stroke="#ccc" stroke-width="1" ${transform}/>

              <text x="${x + w/2}" y="${y + h/2}" text-anchor="middle" font-size="12" fill="#666">图片</text>`;
    }
    
    return '';
  }).filter(Boolean).join('');
  
  return `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

    ${gradientDefs}

    <rect width="100%" height="100%" fill="${backgroundStyle}"/>

    <g>${elementsHTML}</g>

  </svg>`;
}

// Generate error page for frontend display
function generateErrorPage(title, message) {
  return `

<!DOCTYPE html>

<html lang="zh-CN">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>${title} - PPT导出</title>

    <style>

        body {

            font-family: 'Microsoft YaHei', sans-serif;

            margin: 0;

            padding: 0;

            background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);

            min-height: 100vh;

            display: flex;

            align-items: center;

            justify-content: center;

        }

        .error-container {

            background: white;

            padding: 40px;

            border-radius: 15px;

            box-shadow: 0 20px 40px rgba(0,0,0,0.1);

            text-align: center;

            max-width: 500px;

            margin: 20px;

        }

        .error-icon { font-size: 64px; margin-bottom: 20px; }

        .error-title { font-size: 24px; font-weight: bold; color: #333; margin-bottom: 15px; }

        .error-message { font-size: 16px; color: #666; line-height: 1.6; margin-bottom: 30px; }

        .error-actions { display: flex; gap: 15px; justify-content: center; }

        .btn {

            padding: 12px 24px;

            border: none;

            border-radius: 5px;

            font-size: 16px;

            cursor: pointer;

            text-decoration: none;

            display: inline-block;

            transition: all 0.3s;

        }

        .btn-primary { background: #4CAF50; color: white; }

        .btn-primary:hover { background: #45a049; }

        .btn-secondary { background: #f8f9fa; color: #333; border: 1px solid #ddd; }

        .btn-secondary:hover { background: #e9ecef; }

    </style>

</head>

<body>

    <div class="error-container">

        <div class="error-icon">❌</div>

        <div class="error-title">${title}</div>

        <div class="error-message">${message}</div>

        <div class="error-actions">

            <button class="btn btn-secondary" onclick="history.back()">返回上页</button>

            <a href="/" class="btn btn-primary">回到首页</a>

        </div>

    </div>

</body>

</html>

  `;
}

// Publicly access PPT page - return HTML page
router.get('/view/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.params;
    const querySlideIndex = req.query.slide ? parseInt(req.query.slide) : parseInt(slideIndex);
    const fileName = `${pptId}.json`;

    let pptData = null;
    
    // Try all GitHub repositories
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      return res.status(404).send(generateErrorPage('PPT Not Found', 'Please check if the link is correct'));
    }

    const slideIdx = querySlideIndex;
    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      return res.status(404).send(generateErrorPage('Slide Not Found', 'Please check if the slide index is correct'));
    }

    // 使用共享模块生成HTML
    const htmlContent = generateSlideHTML(pptData, slideIdx, { format: 'view' });
    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.send(htmlContent);
  } catch (error) {
    next(error);
  }
});

// API endpoint: Get PPT data and specified slide (JSON format)
router.get('/api-view/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.params;
    const fileName = `${pptId}.json`;

    let pptData = null;
    
    // Try all GitHub repositories
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      return res.status(404).json({ error: 'PPT not found' });
    }

    const slideIdx = parseInt(slideIndex);
    
    // 验证 slideIndex 是否为有效数字
    if (isNaN(slideIdx)) {
      console.log(`❌ Invalid slide index format: ${slideIndex}`);
      
      if (format === 'svg') {
        const invalidIndexSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

          <rect width="100%" height="100%" fill="#f8f9fa"/>

          <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">Invalid Slide Index</text>

          <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">Slide index "${slideIndex}" is not a valid number</text>

          <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

        </svg>`;
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        return res.send(invalidIndexSvg);
      } else {
        const errorPage = generateErrorPage('Invalid Slide Index', `Slide index "${slideIndex}" is not a valid number.`);
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        return res.status(400).send(errorPage);
      }
    }
    
    // 安全检查:确保 slides 数组存在
    if (!pptData.slides || !Array.isArray(pptData.slides)) {
      console.log(`❌ Invalid PPT data: slides array not found`);
      
      if (format === 'svg') {
        const invalidDataSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

          <rect width="100%" height="100%" fill="#f8f9fa"/>

          <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">Invalid PPT Data</text>

          <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">Slides data not found</text>

          <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

        </svg>`;
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        return res.send(invalidDataSvg);
      } else {
        const errorPage = generateErrorPage('Invalid PPT Data', 'PPT slides data not found or corrupted.');
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        return res.status(400).send(errorPage);
      }
    }
    
    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      return res.status(404).json({ error: 'Slide not found' });
    }

    // Return PPT data and specified slide
    res.json({
      id: pptData.id,
      title: pptData.title,
      theme: pptData.theme,
      currentSlide: pptData.slides[slideIdx],
      slideIndex: slideIdx,
      totalSlides: pptData.slides.length,
      isPublicView: true
    });
  } catch (error) {
    next(error);
  }
});

// Get complete PPT data (read-only mode)
router.get('/ppt/:userId/:pptId', async (req, res, next) => {
  try {
    const { userId, pptId } = req.params;
    const fileName = `${pptId}.json`;

    let pptData = null;
    
    // Try all GitHub repositories
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      return res.status(404).json({ error: 'PPT not found' });
    }

    // Return read-only version of PPT data
    res.json({
      ...pptData,
      isPublicView: true,
      readOnly: true
    });
  } catch (error) {
    next(error);
  }
});

// Generate PPT share link
router.post('/generate-share-link', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.body;

    if (!userId || !pptId) {
      return res.status(400).json({ error: 'User ID and PPT ID are required' });
    }

    console.log(`Generating share link for PPT: ${pptId}, User: ${userId}`);

    // Verify if PPT exists
    const fileName = `${pptId}.json`;
    let pptExists = false;
    let pptData = null;
    
    console.log(`Checking ${githubService.repositories.length} GitHub repositories...`);
    
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        console.log(`Checking repository ${i}: ${githubService.repositories[i]}`);
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptExists = true;
          pptData = result.content;
          console.log(`PPT found in repository ${i}`);
          break;
        }
      } catch (error) {
        console.log(`PPT not found in repository ${i}: ${error.message}`);
        continue;
      }
    }

    if (!pptExists) {
      return res.status(404).json({ 
        error: 'PPT not found',
        details: `PPT ${pptId} not found for user ${userId}`,
        searchedLocations: 'GitHub repositories'
      });
    }

    const baseUrl = process.env.PUBLIC_URL || req.get('host');
    // 修复协议判断:localhost 始终使用 http,生产环境使用 https
    const protocol = baseUrl.includes('localhost') ? 'http' : 'https';
    
    const shareLinks = {
      // Single page share link
      slideUrl: `${protocol}://${baseUrl}/api/public/view/${userId}/${pptId}/${slideIndex}`,
      // Complete PPT share link
      pptUrl: `${protocol}://${baseUrl}/api/public/ppt/${userId}/${pptId}`,
      // Frontend view link
      viewUrl: `${protocol}://${baseUrl}/public/${userId}/${pptId}/${slideIndex}`,
      // Screenshot link (直接返回图片)
      screenshotUrl: `${protocol}://${baseUrl}/api/public/image/${userId}/${pptId}/${slideIndex}?format=jpg&quality=90`,
      // 新增:直接图片URL (无需用户交互)
      directImageUrl: `${protocol}://${baseUrl}/api/public/direct-image/${userId}/${pptId}/${slideIndex}`,
      // Add PPT information
      pptInfo: {
        id: pptId,
        title: pptData?.title || 'Unknown Title',
        slideCount: pptData?.slides?.length || 0
      }
    };

    console.log('Share links generated successfully:', shareLinks);
    res.json(shareLinks);
  } catch (error) {
    next(error);
  }
});

// Screenshot endpoint - Frontend Export Strategy
router.get('/screenshot/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.params;
    const { format = 'jpeg', quality = 90, strategy = 'frontend-first', returnHtml = 'true' } = req.query;
    
    console.log(`Screenshot request: userId=${userId}, pptId=${pptId}, slideIndex=${slideIndex}, strategy=${strategy}, returnHtml=${returnHtml}`);
    
    // Get PPT data
    const fileName = `${pptId}.json`;
    let pptData = null;
    
    // Try all GitHub repositories
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      return res.status(404).json({ error: 'PPT not found' });
    }

    // Check if slides array exists
    if (!pptData.slides || !Array.isArray(pptData.slides)) {
      return res.status(400).json({ error: 'Invalid PPT data: slides not found' });
    }

    const slideIdx = parseInt(slideIndex);
    
    // 安全检查:确保 slides 数组存在
    if (!pptData.slides || !Array.isArray(pptData.slides)) {
      console.log(`❌ Invalid PPT data: slides array not found`);
      
      if (format === 'svg') {
        const invalidDataSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

          <rect width="100%" height="100%" fill="#f8f9fa"/>

          <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">Invalid PPT Data</text>

          <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">Slides data not found</text>

          <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

        </svg>`;
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        return res.send(invalidDataSvg);
      } else {
        const errorPage = generateErrorPage('Invalid PPT Data', 'PPT slides data not found or corrupted.');
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        return res.status(400).send(errorPage);
      }
    }
    
    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      return res.status(404).json({ error: 'Invalid slide index' });
    }

    // Frontend Export Strategy - Return HTML page for client-side screenshot generation
    if (strategy === 'frontend-first' && returnHtml !== 'false') {
      console.log('Using frontend export strategy - returning HTML page');
      
      // 使用共享模块生成导出页面
      const htmlPage = generateExportPage(pptData, slideIdx, {
        format,
        quality: parseInt(quality),
        autoDownload: req.query.autoDownload === 'true'
      });
      
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      res.setHeader('X-Screenshot-Strategy', 'frontend-export');
      res.setHeader('X-Generation-Time', '< 100ms');
      return res.send(htmlPage);
    }

    // Fallback: Backend screenshot (if specifically requested)
    console.log('Using backend screenshot for direct image return...');
    
    // 使用共享模块生成HTML用于后端截图
    const htmlContent = generateSlideHTML(pptData, slideIdx, { format: 'screenshot' });
    
    try {
      const screenshot = await screenshotService.generateScreenshot(htmlContent, {
        format,
        quality: parseInt(quality),
        width: pptData.viewportSize || 1000,
        height: Math.ceil((pptData.viewportSize || 1000) * (pptData.viewportRatio || 0.5625))
      });
      
      res.setHeader('Content-Type', `image/${format}`);
      res.setHeader('X-Screenshot-Type', 'backend-generated');
      res.setHeader('X-Generation-Time', '2-5s');
      res.send(screenshot);
      
    } catch (error) {
      console.error('Backend screenshot failed:', error);
      
      // Generate fallback image
      const fallbackImage = screenshotService.generateFallbackImage(
        pptData.viewportSize || 1000, 
        Math.ceil((pptData.viewportSize || 1000) * (pptData.viewportRatio || 0.5625))
      );
      
      res.setHeader('Content-Type', `image/${format}`);
      res.setHeader('X-Screenshot-Type', 'fallback-generated');
      res.setHeader('X-Generation-Time', '< 50ms');
      res.send(fallbackImage);
    }
    
  } catch (error) {
    next(error);
  }
});

// 🔥 关键修改:image端点现在支持多种格式,包括SVG和JPG
router.get('/image/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.params;
    const { format = 'svg', quality = 90, width: requestWidth, height: requestHeight } = req.query;
    
    console.log(`🔥 Image request: userId=${userId}, pptId=${pptId}, slideIndex=${slideIndex}, format=${format}`);
    
    // Get PPT data
    const fileName = `${pptId}.json`;
    let pptData = null;
    
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          console.log(`✅ PPT data found in repository ${i}`);
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      console.log(`❌ PPT not found: ${pptId}`);
      
      if (format === 'svg') {
        const notFoundSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

          <rect width="100%" height="100%" fill="#f8f9fa"/>

          <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">PPT Not Found</text>

          <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">PPT ${pptId} does not exist</text>

          <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

        </svg>`;
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        return res.send(notFoundSvg);
      } else {
        // 对于JPG/PNG格式,返回截图工具页面
        const errorPage = generateErrorPage('PPT Not Found', `PPT ${pptId} not found. Please check the PPT ID.`);
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        return res.status(404).send(errorPage);
      }
    }

    const slideIdx = parseInt(slideIndex);
    
    // 安全检查:确保 slides 数组存在
    if (!pptData.slides || !Array.isArray(pptData.slides)) {
      console.log(`❌ Invalid PPT data: slides array not found`);
      
      if (format === 'svg') {
        const invalidDataSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

          <rect width="100%" height="100%" fill="#f8f9fa"/>

          <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">Invalid PPT Data</text>

          <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">Slides data not found</text>

          <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

        </svg>`;
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        return res.send(invalidDataSvg);
      } else {
        const errorPage = generateErrorPage('Invalid PPT Data', 'PPT slides data not found or corrupted.');
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        return res.status(400).send(errorPage);
      }
    }
    
    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      console.log(`❌ Invalid slide index: ${slideIndex}`);
      
      if (format === 'svg') {
        const invalidSlideSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

          <rect width="100%" height="100%" fill="#f8f9fa"/>

          <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">Invalid Slide</text>

          <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">Slide ${slideIndex} not found</text>

          <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

        </svg>`;
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        return res.send(invalidSlideSvg);
      } else {
        const errorPage = generateErrorPage('Invalid Slide', `Slide ${slideIndex} not found in this PPT.`);
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        return res.status(404).send(errorPage);
      }
    }

    // 根据格式处理
    if (format === 'svg') {
      // SVG格式 - 直接生成并返回
      console.log(`✅ Generating SVG for slide ${slideIdx}`);
      
      const defaultWidth = pptData.viewportSize || 1000;
      const defaultHeight = Math.ceil(defaultWidth * (pptData.viewportRatio || 0.5625));
      const finalWidth = requestWidth ? parseInt(requestWidth) : defaultWidth;
      const finalHeight = requestHeight ? parseInt(requestHeight) : defaultHeight;
      
      const slide = pptData.slides[slideIdx];
      const svgContent = generateSlideSVG(slide, pptData, { 
        width: finalWidth, 
        height: finalHeight 
      });
      
      console.log(`🎉 SVG generated successfully, returning image data`);
      
      res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
      res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('X-Force-Update', 'true');
      res.setHeader('X-Generation-Time', '< 10ms');
      res.send(svgContent);
      
    } else {
      // JPG/PNG格式 - 使用优化的截图方法
      console.log(`✅ Generating ${format} image using optimized screenshot method`);
      
      try {
        // 使用共享模块生成HTML用于后端截图
        const htmlContent = generateSlideHTML(pptData, slideIdx, { format: 'screenshot' });
        
        const screenshot = await screenshotService.generateScreenshot(htmlContent, {
          format: format === 'jpg' ? 'jpeg' : format,
          quality: parseInt(quality),
          width: pptData.viewportSize || 1000,
          height: Math.ceil((pptData.viewportSize || 1000) * (pptData.viewportRatio || 0.5625))
        });
        
        res.setHeader('Content-Type', `image/${format === 'jpg' ? 'jpeg' : format}`);
        res.setHeader('X-Screenshot-Type', 'backend-generated');
        res.setHeader('X-Generation-Time', '1-3s'); // 优化后的时间估计
        res.setHeader('Cache-Control', 'public, max-age=3600'); // 缓存1小时
        res.send(screenshot);
        
      } catch (error) {
        console.error(`Backend ${format} generation failed:`, error);
        
        // 生成后备图片
        const fallbackImage = screenshotService.generateFallbackImage(
          pptData.viewportSize || 1000, 
          Math.ceil((pptData.viewportSize || 1000) * (pptData.viewportRatio || 0.5625)),
          `PPT ${format.toUpperCase()} Image`,
          'Image generation failed'
        );
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        res.setHeader('X-Screenshot-Type', 'fallback-generated');
        res.setHeader('X-Generation-Time', '< 50ms');
        res.send(fallbackImage);
      }
    }
    
  } catch (error) {
    console.error('❌ Image generation failed:', error);
    
    // 根据格式返回错误
    if (req.query.format === 'svg') {
      res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
      res.setHeader('Access-Control-Allow-Origin', '*');
      
      const errorSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

        <rect width="100%" height="100%" fill="#ffe6e6"/>

        <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#cc0000">Generation Error</text>

        <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#cc0000">Failed to generate image</text>

        <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

      </svg>`;
      
      res.send(errorSvg);
    } else {
      const errorPage = generateErrorPage('Generation Error', 'Failed to generate the requested image format.');
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      res.status(500).send(errorPage);
    }
  }
});

// Screenshot data endpoint - For frontend direct rendering
router.get('/screenshot-data/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.params;
    const { format = 'jpeg', quality = 90 } = req.query;
    
    console.log(`Screenshot data request: userId=${userId}, pptId=${pptId}, slideIndex=${slideIndex}`);
    
    // Get PPT data
    const fileName = `${pptId}.json`;
    let pptData = null;
    
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      return res.status(404).json({ error: 'PPT not found' });
    }

    // Check if slides array exists
    if (!pptData.slides || !Array.isArray(pptData.slides)) {
      return res.status(400).json({ error: 'Invalid PPT data: slides not found' });
    }

    const slideIdx = parseInt(slideIndex);
    
    // 安全检查:确保 slides 数组存在
    if (!pptData.slides || !Array.isArray(pptData.slides)) {
      console.log(`❌ Invalid PPT data: slides array not found`);
      
      if (format === 'svg') {
        const invalidDataSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

          <rect width="100%" height="100%" fill="#f8f9fa"/>

          <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">Invalid PPT Data</text>

          <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">Slides data not found</text>

          <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

        </svg>`;
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        return res.send(invalidDataSvg);
      } else {
        const errorPage = generateErrorPage('Invalid PPT Data', 'PPT slides data not found or corrupted.');
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        return res.status(400).send(errorPage);
      }
    }
    
    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      return res.status(404).json({ error: 'Invalid slide index' });
    }

    // Return PPT data for frontend rendering
    const responseData = {
      pptData: {
        id: pptData.id,
        title: pptData.title,
        theme: pptData.theme,
        viewportSize: pptData.viewportSize,
        viewportRatio: pptData.viewportRatio,
        slide: pptData.slides[slideIdx]
      },
      slideIndex: slideIdx,
      totalSlides: pptData.slides.length,
      exportConfig: {
        format,
        quality: parseInt(quality),
        width: pptData.viewportSize || 1000,
        height: Math.ceil((pptData.viewportSize || 1000) * (pptData.viewportRatio || 0.5625))
      },
      strategy: 'frontend-direct-rendering',
      timestamp: new Date().toISOString()
    };
    
    res.setHeader('X-Screenshot-Strategy', 'frontend-data-api');
    res.json(responseData);
    
  } catch (error) {
    next(error);
  }
});

// Screenshot health check
router.get('/screenshot-health', async (req, res, next) => {
  try {
    const status = {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      environment: {
        nodeEnv: process.env.NODE_ENV,
        isHuggingFace: process.env.SPACE_ID ? true : false,
        platform: process.platform
      },
      screenshotService: {
        available: true,
        strategy: 'frontend-first',
        backendFallback: false, // Disable backend browsers
        screenshotSize: 0
      }
    };

    // Test fallback image generation
    try {
      const testImage = screenshotService.generateFallbackImage(100, 100);
      status.screenshotService.screenshotSize = testImage.length;
      status.screenshotService.fallbackAvailable = true;
    } catch (error) {
      status.screenshotService.fallbackAvailable = false;
      status.screenshotService.fallbackError = error.message;
    }

    res.json(status);
  } catch (error) {
    res.status(500).json({
      status: 'error',
      timestamp: new Date().toISOString(),
      error: error.message
    });
  }
});

// 新增:截图工具页面端点(原来的image端点功能)
router.get('/screenshot-tool/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.params;
    const { format = 'jpeg', quality = 90 } = req.query;
    
    console.log(`Screenshot tool request: userId=${userId}, pptId=${pptId}, slideIndex=${slideIndex}`);
    
    // Get PPT data
    const fileName = `${pptId}.json`;
    let pptData = null;
    
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          console.log(`✅ PPT data found in repository ${i}`);
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      const errorPage = generateErrorPage('PPT Not Found', `PPT ${pptId} not found for user ${userId}`);
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      return res.status(404).send(errorPage);
    }

    const slideIdx = parseInt(slideIndex);
    
    // 安全检查:确保 slides 数组存在
    if (!pptData.slides || !Array.isArray(pptData.slides)) {
      console.log(`❌ Invalid PPT data: slides array not found`);
      
      if (format === 'svg') {
        const invalidDataSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

          <rect width="100%" height="100%" fill="#f8f9fa"/>

          <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">Invalid PPT Data</text>

          <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">Slides data not found</text>

          <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

        </svg>`;
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        return res.send(invalidDataSvg);
      } else {
        const errorPage = generateErrorPage('Invalid PPT Data', 'PPT slides data not found or corrupted.');
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        return res.status(400).send(errorPage);
      }
    }
    
    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      const errorPage = generateErrorPage('Invalid Slide', `Slide ${slideIndex} not found in PPT`);
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      return res.status(404).send(errorPage);
    }

    // 使用共享模块生成导出页面
    const htmlPage = generateExportPage(pptData, slideIdx, {
      format,
      quality: parseInt(quality),
      autoDownload: false // 不自动下载,需要用户手动操作
    });
    
    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.setHeader('X-Screenshot-Strategy', 'frontend-screenshot-tool');
    res.setHeader('X-Generation-Time', '< 50ms');
    res.send(htmlPage);
    
  } catch (error) {
    next(error);
  }
});

// 新增:PPT JSON导出端点
router.get('/export-json/:userId/:pptId', async (req, res, next) => {
  try {
    const { userId, pptId } = req.params;
    const fileName = `${pptId}.json`;

    let pptData = null;
    
    // Try all GitHub repositories
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      return res.status(404).json({ error: 'PPT not found' });
    }

    // 使用共享模块导出JSON
    const jsonData = exportPPTToJSON(pptData);
    
    res.setHeader('Content-Type', 'application/json; charset=utf-8');
    res.setHeader('Content-Disposition', `attachment; filename="${pptData.title || 'presentation'}.json"`);
    res.json(jsonData);
  } catch (error) {
    next(error);
  }
});

// 新增:PPT HTML演示文稿导出端点
router.get('/export-html/:userId/:pptId', async (req, res, next) => {
  try {
    const { userId, pptId } = req.params;
    const { interactive = 'true', standalone = 'true', css = 'true' } = req.query;
    const fileName = `${pptId}.json`;

    let pptData = null;
    
    // Try all GitHub repositories
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      return res.status(404).json({ error: 'PPT not found' });
    }

    // 使用共享模块生成完整HTML演示文稿
    const htmlContent = generateHTMLPresentation(pptData, {
      includeInteractivity: interactive === 'true',
      standalone: standalone === 'true',
      includeCSS: css === 'true'
    });
    
    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.setHeader('Content-Disposition', `attachment; filename="${pptData.title || 'presentation'}.html"`);
    res.send(htmlContent);
  } catch (error) {
    next(error);
  }
});

// 新增:PPT完整演示文稿查看端点(在线查看,非下载)
router.get('/presentation/:userId/:pptId', async (req, res, next) => {
  try {
    const { userId, pptId } = req.params;
    const fileName = `${pptId}.json`;

    let pptData = null;
    
    // Try all GitHub repositories
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      return res.status(404).send(generateErrorPage('PPT Not Found', 'The presentation you are looking for does not exist.'));
    }

    // 使用共享模块生成完整HTML演示文稿用于在线查看
    const htmlContent = generateHTMLPresentation(pptData, {
      includeInteractivity: true,
      standalone: true,
      includeCSS: true
    });
    
    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.send(htmlContent);
  } catch (error) {
    next(error);
  }
});

// 新增:直接返回图片的端点 - 必须放在其他路由之前避免被覆盖
router.get('/direct-image/:userId/:pptId/:slideIndex?', async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex = 0 } = req.params;
    const { format = 'svg', quality = 90, width: requestWidth, height: requestHeight } = req.query;
    
    console.log(`🖼️ Direct image request: userId=${userId}, pptId=${pptId}, slideIndex=${slideIndex}, format=${format}`);
    
    // Get PPT data
    const fileName = `${pptId}.json`;
    let pptData = null;
    
    for (let i = 0; i < githubService.repositories.length; i++) {
      try {
        const result = await githubService.getFile(userId, fileName, i);
        if (result) {
          pptData = result.content;
          console.log(`✅ PPT data found in repository ${i}`);
          break;
        }
      } catch (error) {
        continue;
      }
    }

    if (!pptData) {
      console.log(`❌ PPT not found: ${pptId}`);
      // 返回404图片SVG
      const notFoundSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

        <rect width="100%" height="100%" fill="#f8f9fa"/>

        <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">PPT Not Found</text>

        <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">PPT ${pptId} does not exist</text>

      </svg>`;
      
      res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
      res.setHeader('Cache-Control', 'no-cache');
      res.setHeader('Access-Control-Allow-Origin', '*');
      return res.send(notFoundSvg);
    }

    const slideIdx = parseInt(slideIndex);
    
    // 安全检查:确保 slides 数组存在
    if (!pptData.slides || !Array.isArray(pptData.slides)) {
      console.log(`❌ Invalid PPT data: slides array not found`);
      
      if (format === 'svg') {
        const invalidDataSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

          <rect width="100%" height="100%" fill="#f8f9fa"/>

          <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">Invalid PPT Data</text>

          <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">Slides data not found</text>

          <text x="400" y="300" text-anchor="middle" font-family="Arial, sans-serif" font-size="12" fill="#999">${new Date().toISOString()}</text>

        </svg>`;
        
        res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
        return res.send(invalidDataSvg);
      } else {
        const errorPage = generateErrorPage('Invalid PPT Data', 'PPT slides data not found or corrupted.');
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        return res.status(400).send(errorPage);
      }
    }
    
    if (slideIdx >= pptData.slides.length || slideIdx < 0) {
      console.log(`❌ Invalid slide index: ${slideIndex}`);
      // 返回404幻灯片SVG
      const invalidSlideSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

        <rect width="100%" height="100%" fill="#f8f9fa"/>

        <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#6c757d">Invalid Slide</text>

        <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#6c757d">Slide ${slideIndex} not found</text>

      </svg>`;
      
      res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
      res.setHeader('Cache-Control', 'no-cache');
      res.setHeader('Access-Control-Allow-Origin', '*');
      return res.send(invalidSlideSvg);
    }

    console.log(`✅ Generating SVG for slide ${slideIdx}`);
    
    // 计算图片尺寸
    const defaultWidth = pptData.viewportSize || 1000;
    const defaultHeight = Math.ceil(defaultWidth * (pptData.viewportRatio || 0.5625));
    const finalWidth = requestWidth ? parseInt(requestWidth) : defaultWidth;
    const finalHeight = requestHeight ? parseInt(requestHeight) : defaultHeight;
    
    // 生成PPT幻灯片的SVG图片
    const slide = pptData.slides[slideIdx];
    const svgContent = generateSlideSVG(slide, pptData, { 
      width: finalWidth, 
      height: finalHeight 
    });
    
    console.log(`✅ SVG generated successfully, size: ${svgContent.length} characters`);
    
    // 设置正确的响应头,使其可以被其他网站作为图片引用
    res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
    res.setHeader('Cache-Control', 'public, max-age=3600'); // 缓存1小时
    res.setHeader('Access-Control-Allow-Origin', '*'); // 允许跨域引用
    res.setHeader('X-Generation-Time', '< 10ms');
    res.setHeader('X-Content-Source', 'direct-svg-generation');
    res.setHeader('Content-Disposition', 'inline'); // 确保浏览器内联显示图片
    
    // 直接返回SVG图片内容
    res.send(svgContent);
    
  } catch (error) {
    console.error('❌ Direct image generation failed:', error);
    
    // 返回错误图片SVG
    const errorSvg = `<svg width="800" height="450" xmlns="http://www.w3.org/2000/svg">

      <rect width="100%" height="100%" fill="#ffe6e6"/>

      <text x="400" y="200" text-anchor="middle" font-family="Arial, sans-serif" font-size="24" fill="#cc0000">Generation Error</text>

      <text x="400" y="250" text-anchor="middle" font-family="Arial, sans-serif" font-size="16" fill="#cc0000">Failed to generate image: ${error.message}</text>

    </svg>`;
    
    res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.send(errorSvg);
  }
});

// 存储前端生成的图片数据
const imageCache = new Map();

// POST endpoint to receive frontend-generated images
router.post('/save-image/:userId/:pptId/:slideIndex', express.json({ limit: '10mb' }), async (req, res, next) => {
  try {
    const { userId, pptId, slideIndex } = req.params;
    const { imageData, format = 'jpeg', quality = 90 } = req.body;
    
    if (!imageData) {
      return res.status(400).json({ error: 'Image data is required' });
    }
    
    // 生成唯一的图片ID
    const imageId = `${userId}-${pptId}-${slideIndex}-${Date.now()}`;
    
    // 存储图片数据到内存缓存
    imageCache.set(imageId, {
      data: imageData,
      format,
      quality,
      userId,
      pptId,
      slideIndex,
      timestamp: new Date().toISOString(),
      contentType: `image/${format === 'jpg' ? 'jpeg' : format}`
    });
    
    // 设置过期时间(1小时后自动清理)
    setTimeout(() => {
      imageCache.delete(imageId);
    }, 3600000);
    
    // 返回图片访问URL
    const baseUrl = req.protocol + '://' + req.get('host');
    const imageUrl = `${baseUrl}/api/public/cached-image/${imageId}`;
    
    console.log(`✅ Image saved with ID: ${imageId}`);
    
    res.json({
      success: true,
      imageId,
      imageUrl,
      expiresAt: new Date(Date.now() + 3600000).toISOString()
    });
    
  } catch (error) {
    console.error('❌ Failed to save image:', error);
    next(error);
  }
});

// GET endpoint to serve cached images
router.get('/cached-image/:imageId', async (req, res, next) => {
  try {
    const { imageId } = req.params;
    
    const cachedImage = imageCache.get(imageId);
    if (!cachedImage) {
      return res.status(404).json({ error: 'Image not found or expired' });
    }
    
    // 设置响应头
    res.setHeader('Content-Type', cachedImage.contentType);
    res.setHeader('Cache-Control', 'public, max-age=3600');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('X-Image-Source', 'frontend-generated');
    res.setHeader('X-Generation-Time', cachedImage.timestamp);
    
    // 如果是base64数据,需要转换
    if (cachedImage.data.startsWith('data:')) {
      const base64Data = cachedImage.data.split(',')[1];
      const buffer = Buffer.from(base64Data, 'base64');
      res.send(buffer);
    } else {
      res.send(cachedImage.data);
    }
    
  } catch (error) {
    console.error('❌ Failed to serve cached image:', error);
    next(error);
  }
});

export default router;