File size: 49,393 Bytes
8fb060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a72fc
8fb060c
 
 
 
25a72fc
8fb060c
 
 
25a72fc
 
 
8fb060c
 
25a72fc
 
 
8fb060c
 
25a72fc
 
 
8fb060c
 
25a72fc
 
 
8fb060c
 
25a72fc
 
8fb060c
 
 
25a72fc
 
 
 
8fb060c
 
25a72fc
 
 
8fb060c
 
25a72fc
 
 
 
 
 
8fb060c
 
25a72fc
8fb060c
 
25a72fc
 
 
 
8fb060c
 
 
 
25a72fc
8fb060c
 
25a72fc
 
 
 
 
 
 
 
 
 
 
 
8fb060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a72fc
8fb060c
 
25a72fc
 
 
8fb060c
 
 
 
25a72fc
 
 
8fb060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a72fc
8fb060c
 
25a72fc
 
 
 
8fb060c
 
 
 
 
25a72fc
8fb060c
 
 
 
 
 
 
 
25a72fc
 
8fb060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a72fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fb060c
 
25a72fc
 
8fb060c
 
 
 
25a72fc
 
8fb060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a72fc
8fb060c
 
 
 
25a72fc
8fb060c
 
25a72fc
 
 
 
 
 
 
 
 
 
 
8fb060c
 
 
 
 
 
25a72fc
 
8fb060c
 
25a72fc
 
 
8fb060c
 
 
 
 
 
 
 
 
 
25a72fc
8fb060c
25a72fc
 
8fb060c
 
 
 
 
 
 
25a72fc
 
8fb060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a72fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fb060c
25a72fc
 
 
8fb060c
25a72fc
 
8fb060c
25a72fc
8fb060c
25a72fc
 
8fb060c
 
25a72fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fb060c
 
9ca6256
 
 
 
8fb060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d76f10f
8fb060c
 
 
d76f10f
8fb060c
 
 
 
 
 
 
d76f10f
8fb060c
 
 
 
 
d76f10f
8fb060c
d76f10f
8fb060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ca6256
8fb060c
9ca6256
 
d76f10f
 
2c0310f
 
 
9ca6256
d76f10f
9ca6256
2c0310f
 
 
 
 
9ca6256
 
d76f10f
9ca6256
8fb060c
 
 
 
9ca6256
8fb060c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import re
import random
import time
import html
import base64
import string
import json
import asyncio
import requests
import anthropic
import openai

from http import HTTPStatus
from typing import Dict, List, Optional, Tuple
from functools import partial

import gradio as gr
import modelscope_studio.components.base as ms
import modelscope_studio.components.legacy as legacy
import modelscope_studio.components.antd as antd


# ------------------------
# 1) DEMO_LIST 및 SystemPrompt
# ------------------------

DEMO_LIST = [
    {"description": "Create a Tetris-like puzzle game with arrow key controls, line-clearing mechanics, and increasing difficulty levels."},
    {"description": "Build an interactive Chess game with a basic AI opponent and drag-and-drop piece movement. Keep track of moves and detect check/checkmate."},
    {"description": "Design a memory matching card game with flip animations, scoring system, and multiple difficulty levels."},
    {"description": "Create a space shooter game with enemy waves, collision detection, and power-ups. Use keyboard or mouse controls for ship movement."},
    {"description": "Implement a slide puzzle game using images or numbers. Include shuffle functionality, move counter, and difficulty settings."},
    {"description": "Implement the classic Snake game with grid-based movement, score tracking, and increasing speed. Use arrow keys for control."},
    {"description": "Build a classic breakout game with paddle, ball, and bricks. Increase ball speed and track lives/score."},
    {"description": "Create a tower defense game with multiple tower types and enemy waves. Include an upgrade system and resource management."},
    {"description": "Design an endless runner with side-scrolling obstacles. Use keyboard or mouse to jump and avoid collisions."},
    {"description": "Implement a platformer game with character movement, jumping, and collectible items. Use arrow keys for control."},
    {"description": "Generate a random maze and allow the player to navigate from start to finish. Include a timer and pathfinding animations."},
    {"description": "Build a simple top-down RPG with tile-based movement, monsters, and loot. Use arrow keys for movement and track player stats."},
    {"description": "Create a match-3 puzzle game with swipe-based mechanics, special tiles, and combo scoring."},
    {"description": "Implement a Flappy Bird clone with space bar or mouse click to flap, randomized pipe positions, and score tracking."},
    {"description": "Build a spot-the-difference game using pairs of similar images. Track remaining differences and time limit."},
    {"description": "Create a typing speed test game where words fall from the top. Type them before they reach the bottom to score points."},
    {"description": "Implement a mini golf game with physics-based ball movement. Include multiple holes and scoring based on strokes."},
    {"description": "Design a fishing game where the player casts a line, reels fish, and can upgrade gear. Manage fish spawn rates and scoring."},
    {"description": "Build a bingo game with randomly generated boards and a calling system. Automatically check winning lines."},
    {"description": "Create a web-based rhythm game using keyboard inputs. Time hits accurately for score, and add background music."},
    {"description": "Implement a top-down 2D racing game with track boundaries, lap times, and multiple AI opponents."},
    {"description": "Build a quiz game with multiple-choice questions, scoring, and a timer. Randomize question order each round."},
    {"description": "Create a shooting gallery game with moving targets, limited ammo, and a time limit. Track hits and misses."},
    {"description": "Implement a dice-based board game with multiple squares, events, and item usage. Players take turns rolling."},
    {"description": "Design a top-down zombie survival game with wave-based enemies, pickups, and limited ammo. Track score and health."},
    {"description": "Build a simple penalty shootout game with aiming, power bars, and a goalie AI that guesses shots randomly."},
    {"description": "Implement the classic Minesweeper game with left-click reveal, right-click flags, and adjacency logic for numbers."},
    {"description": "Create a Connect Four game with drag-and-drop or click-based input, alternating turns, and a win check algorithm."},
    {"description": "Build a Scrabble-like word puzzle game with letter tiles, scoring, and a local dictionary for validation."},
    {"description": "Implement a 2D tank battle game with destructible terrain, power-ups, and AI or multiplayer functionality."},
    {"description": "Create a gem-crushing puzzle game where matching gems cause chain reactions. Track combos and score bonuses."},
    {"description": "Design a 2D defense game where a single tower shoots incoming enemies in waves. Upgrade the tower's stats over time."},
    {"description": "Make a side-scrolling runner where a character avoids zombies and obstacles, collecting power-ups along the way."},
    {"description": "Create a small action RPG with WASD movement, an attack button, special moves, leveling, and item drops."},
]

SystemPrompt = """
# GameCraft 시스템 프롬프트

## 1. 기본 정보 및 역할
당신의 이름은 'GameCraft'입니다. 당신은 게임플레이 메커니즘, 인터랙티브 디자인, 성능 최적화에 뛰어난 웹 게임 개발 전문가입니다. HTML, JavaScript, CSS를 활용하여 간결하고 효율적인 웹 기반 게임을 제작하는 것이 당신의 임무입니다.

## 2. 핵심 기술 스택
- **프론트엔드**: HTML5, CSS3, JavaScript(ES6+)
- **렌더링 방식**: 브라우저에서 직접 렌더링 가능한 코드 생성
- **코드 스타일**: 바닐라 JavaScript 우선, 외부 라이브러리 최소화

## 3. 게임 유형별 특화 지침
### 3.1 아케이드/액션 게임
- 간결한 충돌 감지 시스템 구현
- 키보드/터치 입력 최적화
- 기본적인 점수 시스템

### 3.2 퍼즐 게임
- 명확한 게임 규칙 및 승리 조건
- 기본 난이도 구현
- 핵심 게임 메커니즘에 집중

### 3.3 카드/보드 게임
- 간소화된 턴 기반 시스템
- 기본 게임 규칙 자동화
- 핵심 게임 로직 중심

### 3.4 시뮬레이션 게임
- 효율적인 상태 관리
- 가장 중요한 상호작용 구현
- 핵심 요소만 포함

## 4. 이모지 활용 지침 🎮
- 게임 UI 요소에 이모지 활용 (예: 생명력 ❤️, 코인 💰, 시간 ⏱️)
- 이모지 사용은 핵심 요소에만 집중

## 5. 기술적 구현 가이드라인
### 5.1 코드 구조
- **간결성 중시**: 코드는 최대한 간결하게 작성하고, 주석은 최소화
- **모듈화**: 코드 기능별로 분리하되 불필요한 추상화 지양
- **최적화**: 게임 루프와 렌더링 최적화에 집중
- **코드 크기 제한**: 전체 코드는 200줄을 넘지 않도록 함

### 5.2 성능 최적화
- DOM 조작 최소화
- 불필요한 변수와 함수 제거
- 메모리 관리에 주의

### 5.3 반응형 디자인
- 기본적인 반응형 지원
- 핵심 기능에 집중한 심플한 UI

## 6. 외부 라이브러리
- 라이브러리 사용은 최소화하고, 필요한 경우에만 사용
- 라이브러리 사용 시 CDN으로 가져올 것

## 7. 접근성 및 포용성
- 핵심 접근성 기능에만 집중

## 8. 제약사항 및 유의사항
- 외부 API 호출 금지
- 코드 크기 최소화에 우선순위 (200줄 이내)
- 주석 최소화 - 필수적인 설명만 포함
- 불필요한 기능 구현 지양

## 9. 출력 형식
- HTML 코드 블록으로만 코드 반환
- 추가 설명 없이 즉시 실행 가능한 코드만 제공
- 모든 코드는 단일 HTML 파일에 인라인으로 포함

## 10. 코드 품질 기준
- 효율성과 간결함이 최우선
- 핵심 게임플레이 메커니즘에만 집중
- 복잡한 기능보다 작동하는 기본 기능 우선
- 불필요한 주석이나 장황한 코드 지양
- 단일 파일에 모든 코드 포함
- 코드 길이 제한: 완성된 게임 코드는 200줄 이내로 작성

## 11. 중요: 코드 생성 제한
- 게임 코드는 반드시 200줄 이내로 제한
- 불필요한 설명이나 주석 제외
- 핵심 기능만 구현하고 부가 기능은 생략
- 코드 크기가 커질 경우 기능을 간소화하거나 생략할 것
"""


# ------------------------
# 2) 공통 상수, 함수, 클래스
# ------------------------

class Role:
    SYSTEM = "system"
    USER = "user"
    ASSISTANT = "assistant"

History = List[Tuple[str, str]]
Messages = List[Dict[str, str]]

IMAGE_CACHE = {}

def get_image_base64(image_path):
    """
    이미지 파일을 base64로 읽어서 캐싱
    """
    if image_path in IMAGE_CACHE:
        return IMAGE_CACHE[image_path]
    try:
        with open(image_path, "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read()).decode()
            IMAGE_CACHE[image_path] = encoded_string
            return encoded_string
    except:
        return IMAGE_CACHE.get('default.png', '')

def history_to_messages(history: History, system: str) -> Messages:
    messages = [{'role': Role.SYSTEM, 'content': system}]
    for h in history:
        messages.append({'role': Role.USER, 'content': h[0]})
        messages.append({'role': Role.ASSISTANT, 'content': h[1]})
    return messages

def messages_to_history(messages: Messages) -> History:
    assert messages[0]['role'] == Role.SYSTEM
    history = []
    for q, r in zip(messages[1::2], messages[2::2]):
        history.append([q['content'], r['content']])
    return history


# ------------------------
# 3) API 연동 설정
# ------------------------

YOUR_ANTHROPIC_TOKEN = os.getenv('ANTHROPIC_API_KEY', '').strip()
YOUR_OPENAI_TOKEN    = os.getenv('OPENAI_API_KEY',     '').strip()

claude_client = anthropic.Anthropic(api_key=YOUR_ANTHROPIC_TOKEN)
openai_client = openai.OpenAI(api_key=YOUR_OPENAI_TOKEN)

async def try_claude_api(system_message, claude_messages, timeout=15):
    """
    Claude API 호출 (스트리밍) - 간결한 코드 생성 요청 추가
    """
    try:
        # 시스템 프롬프트에 코드 길이 제한 강화
        system_message_with_limit = system_message + "\n\n추가 중요 지침: 생성하는 코드는 절대로 200줄을 넘지 마세요. 코드 간결성이 최우선입니다. 주석을 최소화하고, 핵심 기능만 구현하세요. 불필요한 UI 요소나 장식은 제외하세요. 모든 코드는 하나의 HTML 파일에 포함되어야 합니다."
        
        start_time = time.time()
        with claude_client.messages.stream(
            model="claude-3-7-sonnet-20250219",
            max_tokens=19800,
            system=system_message_with_limit,
            messages=claude_messages,
            temperature=0.3,  # 온도 낮게 설정하여 일관된 결과 유도
        ) as stream:
            collected_content = ""
            for chunk in stream:
                current_time = time.time()
                if current_time - start_time > timeout:
                    raise TimeoutError("Claude API timeout")
                if chunk.type == "content_block_delta":
                    collected_content += chunk.delta.text
                    yield collected_content
                    await asyncio.sleep(0)
                start_time = current_time
    except Exception as e:
        raise e

async def try_openai_api(openai_messages):
    """
    OpenAI API 호출 (스트리밍) - 코드 길이 제한 강화
    """
    try:
        # 첫 번째 시스템 메시지에 코드 길이 제한 추가
        if openai_messages and openai_messages[0]["role"] == "system":
            openai_messages[0]["content"] += "\n\n추가 중요 지침: 생성하는 코드는 절대로 200줄을 넘지 마세요. 코드 간결성이 최우선입니다. 주석을 최소화하고, 핵심 기능만 구현하세요. 불필요한 UI 요소나 장식은 제외하세요. 모든 코드는 하나의 HTML 파일에 포함되어야 합니다."
        
        stream = openai_client.chat.completions.create(
            model="o3",
            messages=openai_messages,
            stream=True,
            max_tokens=19800,
            temperature=0.2  # 온도 낮게 설정
        )
        collected_content = ""
        for chunk in stream:
            if chunk.choices[0].delta.content is not None:
                collected_content += chunk.choices[0].delta.content
                yield collected_content
    except Exception as e:
        raise e
        



# ------------------------
# 4) 템플릿(하나로 통합)
# ------------------------

def load_json_data():
    """
    모든 템플릿(원래 best/trending/new를 통합)
    """
    data_list = [
        {
            "name": "[게임] 테트리스 클론",
            "image_url": "data:image/png;base64," + get_image_base64('tetris.png'),
            "prompt": "Create a Tetris-like puzzle game with arrow key controls, line-clearing mechanics, and increasing difficulty levels."
        },
        {
            "name": "[게임] 체스",
            "image_url": "data:image/png;base64," + get_image_base64('chess.png'),
            "prompt": "Build an interactive Chess game with a basic AI opponent and drag-and-drop piece movement. Keep track of moves and detect check/checkmate."
        },
        {
            "name": "[게임] 카드 매칭 게임",
            "image_url": "data:image/png;base64," + get_image_base64('memory.png'),
            "prompt": "Design a memory matching card game with flip animations, scoring system, and multiple difficulty levels."
        },
        {
            "name": "[게임] 슈팅 게임 (Space Shooter)",
            "image_url": "data:image/png;base64," + get_image_base64('spaceshooter.png'),
            "prompt": "Create a space shooter game with enemy waves, collision detection, and power-ups. Use keyboard or mouse controls for ship movement."
        },
        {
            "name": "[게임] 슬라이드 퍼즐",
            "image_url": "data:image/png;base64," + get_image_base64('slidepuzzle.png'),
            "prompt": "Implement a slide puzzle game using images or numbers. Include shuffle functionality, move counter, and difficulty settings."
        },
        {
            "name": "[게임] 뱀 게임 (Snake)",
            "image_url": "data:image/png;base64," + get_image_base64('snake.png'),
            "prompt": "Implement the classic Snake game with grid-based movement, score tracking, and increasing speed. Use arrow keys for control."
        },
        {
            "name": "[게임] 브레이크아웃 (벽돌깨기)",
            "image_url": "data:image/png;base64," + get_image_base64('breakout.png'),
            "prompt": "Build a classic breakout game with paddle, ball, and bricks. Increase ball speed and track lives/score."
        },
        {
            "name": "[게임] 타워 디펜스",
            "image_url": "data:image/png;base64," + get_image_base64('towerdefense.png'),
            "prompt": "Create a tower defense game with multiple tower types and enemy waves. Include an upgrade system and resource management."
        },
        {
            "name": "[게임] 런닝 점프 (Endless Runner)",
            "image_url": "data:image/png;base64," + get_image_base64('runner.png'),
            "prompt": "Design an endless runner with side-scrolling obstacles. Use keyboard or mouse to jump and avoid collisions."
        },
        {
            "name": "[게임] 플랫포머 (Platformer)",
            "image_url": "data:image/png;base64," + get_image_base64('platformer.png'),
            "prompt": "Implement a platformer game with character movement, jumping, and collectible items. Use arrow keys for control."
        },
        {
            "name": "[게임] 미로 찾기 (Maze)",
            "image_url": "data:image/png;base64," + get_image_base64('maze.png'),
            "prompt": "Generate a random maze and allow the player to navigate from start to finish. Include a timer and pathfinding animations."
        },
        {
            "name": "[게임] 미션 RPG",
            "image_url": "data:image/png;base64," + get_image_base64('rpg.png'),
            "prompt": "Build a simple top-down RPG with tile-based movement, monsters, and loot. Use arrow keys for movement and track player stats."
        },
        {
            "name": "[게임] Match-3 퍼즐",
            "image_url": "data:image/png;base64," + get_image_base64('match3.png'),
            "prompt": "Create a match-3 puzzle game with swipe-based mechanics, special tiles, and combo scoring."
        },
        {
            "name": "[게임] 하늘 나는 새 (Flappy Bird)",
            "image_url": "data:image/png;base64," + get_image_base64('flappy.png'),
            "prompt": "Implement a Flappy Bird clone with space bar or mouse click to flap, randomized pipe positions, and score tracking."
        },
        {
            "name": "[게임] 그림 찾기 (Spot the Difference)",
            "image_url": "data:image/png;base64," + get_image_base64('spotdiff.png'),
            "prompt": "Build a spot-the-difference game using pairs of similar images. Track remaining differences and time limit."
        },
        {
            "name": "[게임] 타이핑 게임",
            "image_url": "data:image/png;base64," + get_image_base64('typing.png'),
            "prompt": "Create a typing speed test game where words fall from the top. Type them before they reach the bottom to score points."
        },
        {
            "name": "[게임] 미니 골프",
            "image_url": "data:image/png;base64," + get_image_base64('minigolf.png'),
            "prompt": "Implement a mini golf game with physics-based ball movement. Include multiple holes and scoring based on strokes."
        },
        {
            "name": "[게임] 낚시 게임",
            "image_url": "data:image/png;base64," + get_image_base64('fishing.png'),
            "prompt": "Design a fishing game where the player casts a line, reels fish, and can upgrade gear. Manage fish spawn rates and scoring."
        },
        {
            "name": "[게임] 빙고",
            "image_url": "data:image/png;base64," + get_image_base64('bingo.png'),
            "prompt": "Build a bingo game with randomly generated boards and a calling system. Automatically check winning lines."
        },
        {
            "name": "[게임] 리듬 게임",
            "image_url": "data:image/png;base64," + get_image_base64('rhythm.png'),
            "prompt": "Create a web-based rhythm game using keyboard inputs. Time hits accurately for score, and add background music."
        },
        {
            "name": "[게임] 2D 레이싱",
            "image_url": "data:image/png;base64," + get_image_base64('racing2d.png'),
            "prompt": "Implement a top-down 2D racing game with track boundaries, lap times, and multiple AI opponents."
        },
        {
            "name": "[게임] 퀴즈 게임",
            "image_url": "data:image/png;base64," + get_image_base64('quiz.png'),
            "prompt": "Build a quiz game with multiple-choice questions, scoring, and a timer. Randomize question order each round."
        },
        {
            "name": "[게임] 돌 맞추기 (Shooting Gallery)",
            "image_url": "data:image/png;base64," + get_image_base64('gallery.png'),
            "prompt": "Create a shooting gallery game with moving targets, limited ammo, and a time limit. Track hits and misses."
        },
        {
            "name": "[게임] 주사위 보드",
            "image_url": "data:image/png;base64," + get_image_base64('diceboard.png'),
            "prompt": "Implement a dice-based board game with multiple squares, events, and item usage. Players take turns rolling."
        },
        {
            "name": "[게임] 좀비 서바이벌",
            "image_url": "data:image/png;base64," + get_image_base64('zombie.png'),
            "prompt": "Design a top-down zombie survival game with wave-based enemies, pickups, and limited ammo. Track score and health."
        },
        {
            "name": "[게임] 축구 게임 (Penalty Kick)",
            "image_url": "data:image/png;base64," + get_image_base64('soccer.png'),
            "prompt": "Build a simple penalty shootout game with aiming, power bars, and a goalie AI that guesses shots randomly."
        },
        {
            "name": "[게임] Minesweeper",
            "image_url": "data:image/png;base64," + get_image_base64('minesweeper.png'),
            "prompt": "Implement the classic Minesweeper game with left-click reveal, right-click flags, and adjacency logic for numbers."
        },
        {
            "name": "[게임] Connect Four",
            "image_url": "data:image/png;base64," + get_image_base64('connect4.png'),
            "prompt": "Create a Connect Four game with drag-and-drop or click-based input, alternating turns, and a win check algorithm."
        },
        {
            "name": "[게임] 스크래블 (단어 퍼즐)",
            "image_url": "data:image/png;base64," + get_image_base64('scrabble.png'),
            "prompt": "Build a Scrabble-like word puzzle game with letter tiles, scoring, and a local dictionary for validation."
        },
        {
            "name": "[게임] 2D 슈팅 (Tank Battle)",
            "image_url": "data:image/png;base64," + get_image_base64('tank.png'),
            "prompt": "Implement a 2D tank battle game with destructible terrain, power-ups, and AI or multiplayer functionality."
        },
        {
            "name": "[게임] 젬 크러쉬",
            "image_url": "data:image/png;base64," + get_image_base64('gemcrush.png'),
            "prompt": "Create a gem-crushing puzzle game where matching gems cause chain reactions. Track combos and score bonuses."
        },
        {
            "name": "[게임] Shooting Tower",
            "image_url": "data:image/png;base64," + get_image_base64('tower.png'),
            "prompt": "Design a 2D defense game where a single tower shoots incoming enemies in waves. Upgrade the tower's stats over time."
        },
        {
            "name": "[게임] 좀비 러너",
            "image_url": "data:image/png;base64," + get_image_base64('zombierunner.png'),
            "prompt": "Make a side-scrolling runner where a character avoids zombies and obstacles, collecting power-ups along the way."
        },
        {
            "name": "[게임] 스킬 액션 RPG",
            "image_url": "data:image/png;base64," + get_image_base64('actionrpg.png'),
            "prompt": "Create a small action RPG with WASD movement, an attack button, special moves, leveling, and item drops."
        },
    ]
    return data_list

def load_all_templates():
    """
    모든 템플릿을 하나로 보여주는 함수
    """
    return create_template_html("🎮 모든 게임 템플릿", load_json_data())


def create_template_html(title, items):
    """
    폰트를 더 작게 조정
    """
    html_content = r"""
<style>
.prompt-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 16px;
    padding: 12px;
}
.prompt-card {
    background: white;
    border: 1px solid #eee;
    border-radius: 12px;
    padding: 12px;
    cursor: pointer;
    box-shadow: 0 4px 8px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}
.prompt-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 6px 12px rgba(0,0,0,0.1);
}
.card-image {
    width: 100%;
    height: 140px;
    object-fit: cover;
    border-radius: 8px;
    margin-bottom: 10px;
}
.card-name {
    font-weight: bold;
    margin-bottom: 8px;
    font-size: 13px;
    color: #444;
}
.card-prompt {
    font-size: 11px;
    line-height: 1.4;
    color: #666;
    display: -webkit-box;
    -webkit-line-clamp: 7;
    -webkit-box-orient: vertical;
    overflow: hidden;
    height: 84px;
    background-color: #f8f9fa;
    padding: 8px;
    border-radius: 6px;
}
</style>
<div class="prompt-grid">
"""
    for item in items:
        card_html = f"""
<div class="prompt-card" onclick="copyToInput(this)" data-prompt="{html.escape(item.get('prompt', ''))}">
    <img src="{item.get('image_url', '')}" class="card-image" loading="lazy" alt="{html.escape(item.get('name', ''))}">
    <div class="card-name">{html.escape(item.get('name', ''))}</div>
    <div class="card-prompt">{html.escape(item.get('prompt', ''))}</div>
</div>
"""
        html_content += card_html
    html_content += r"""
<script>
function copyToInput(card) {
    const prompt = card.dataset.prompt;
    const textarea = document.querySelector('.ant-input-textarea-large textarea');
    if (textarea) {
        textarea.value = prompt;
        textarea.dispatchEvent(new Event('input', { bubbles: true }));
        // 템플릿 Drawer 닫기
        document.querySelector('.session-drawer .close-btn').click();
    }
}
</script>
</div>
"""
    return gr.HTML(value=html_content)


# ------------------------
# 5) 배포/부스트/기타 유틸
# ------------------------

def generate_space_name():
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(6))

def deploy_to_vercel(code: str):
    """
    Vercel에 배포하는 함수 (예시)
    """
    try:
        token = "A8IFZmgW2cqA4yUNlLPnci0N"  # 실제 토큰 필요
        if not token:
            return "Vercel 토큰이 설정되지 않았습니다."

        project_name = ''.join(random.choice(string.ascii_lowercase) for i in range(6))
        deploy_url = "https://api.vercel.com/v13/deployments"
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json"
        }
        package_json = {
            "name": project_name,
            "version": "1.0.0",
            "private": True,
            "dependencies": {
                "vite": "^5.0.0"
            },
            "scripts": {
                "dev": "vite",
                "build": "echo 'No build needed' && mkdir -p dist && cp index.html dist/",
                "preview": "vite preview"
            }
        }
        files = [
            {
                "file": "index.html",
                "data": code
            },
            {
                "file": "package.json",
                "data": json.dumps(package_json, indent=2)
            }
        ]
        project_settings = {
            "buildCommand": "npm run build",
            "outputDirectory": "dist",
            "installCommand": "npm install",
            "framework": None
        }
        deploy_data = {
            "name": project_name,
            "files": files,
            "target": "production",
            "projectSettings": project_settings
        }
        deploy_response = requests.post(deploy_url, headers=headers, json=deploy_data)
        if deploy_response.status_code != 200:
            return f"배포 실패: {deploy_response.text}"
        deployment_url = f"{project_name}.vercel.app"
        time.sleep(5)
        return f"""배포 완료! <a href="https://{deployment_url}" target="_blank" style="color: #1890ff; text-decoration: underline; cursor: pointer;">https://{deployment_url}</a>"""
    except Exception as e:
        return f"배포 중 오류 발생: {str(e)}"

def remove_code_block(text):
    """
    More robust function to extract code from markdown code blocks
    텍스트에서 ```html 및 ``` 태그를 완전히 제거하는 함수
    """
    # ```html 태그로 둘러싸인 코드 블록 찾기
    pattern = r'```html\s*([\s\S]+?)\s*```'
    match = re.search(pattern, text, re.DOTALL)
    if match:
        return match.group(1).strip()
    
    # 일반 코드 블록 처리
    pattern = r'```(?:\w+)?\s*([\s\S]+?)\s*```'
    match = re.search(pattern, text, re.DOTALL)
    if match:
        return match.group(1).strip()
    
    # 텍스트에 ```html과 ```가 포함된 경우 명시적으로 제거
    text = re.sub(r'```html\s*', '', text)
    text = re.sub(r'\s*```', '', text)
    
    # 코드 블록이 없는 경우 원본 텍스트 반환
    return text.strip()

def optimize_code(code: str) -> str:
    """
    AI가 생성한 코드를 최적화하여 크기를 줄이는 함수
    불필요한 주석, 공백, 장황한 코드 등을 제거
    """
    if not code or len(code.strip()) == 0:
        return code
    
    # 코드 라인수 체크
    lines = code.split('\n')
    if len(lines) <= 200:  # 이미 충분히 짧으면 그대로 반환
        return code
    
    # 1. 불필요한 주석 제거 (/* */, //, <!-- --> 등)
    comment_patterns = [
        r'/\*[\s\S]*?\*/',  # /* 여러 줄 주석 */
        r'//.*?$',          # // 한 줄 주석
        r'<!--[\s\S]*?-->'  # <!-- HTML 주석 -->
    ]
    
    cleaned_code = code
    for pattern in comment_patterns:
        cleaned_code = re.sub(pattern, '', cleaned_code, flags=re.MULTILINE)
    
    # 2. 불필요한 공백 라인 제거
    cleaned_lines = []
    empty_line_count = 0
    for line in cleaned_code.split('\n'):
        if line.strip() == '':
            empty_line_count += 1
            if empty_line_count <= 1:  # 연속 공백 라인은 하나만 유지
                cleaned_lines.append('')
        else:
            empty_line_count = 0
            cleaned_lines.append(line)
    
    # 3. 불필요한 들여쓰기 최적화
    cleaned_code = '\n'.join(cleaned_lines)
    
    # 4. console.log 제거 (디버깅용 코드)
    cleaned_code = re.sub(r'console\.log\(.*?\);', '', cleaned_code, flags=re.MULTILINE)
    
    # 5. 과도한 공백 제거 (CSS에서는 조심)
    cleaned_code = re.sub(r' {2,}', ' ', cleaned_code)
    
    return cleaned_code

def send_to_sandbox(code):
    """
    Improved function to create iframe with proper code cleaning and optimization
    ```html 태그가 확실히 제거된 코드를 최적화하여 iframe으로 렌더링
    """
    # 코드에서 마크다운 표기 제거
    clean_code = remove_code_block(code)
    
    # 코드 최적화
    clean_code = optimize_code(clean_code)
    
    # ```html 태그가 여전히 있으면 명시적으로 제거
    if clean_code.startswith('```html'):
        clean_code = clean_code[7:].strip()
    if clean_code.endswith('```'):
        clean_code = clean_code[:-3].strip()
    
    # 기본 HTML 구조 추가
    if not clean_code.strip().startswith('<!DOCTYPE') and not clean_code.strip().startswith('<html'):
        clean_code = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game Preview</title>
</head>
<body>
{clean_code}
</body>
</html>"""

    # iframe 생성
    encoded_html = base64.b64encode(clean_code.encode('utf-8')).decode('utf-8')
    data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
    return f'<iframe src="{data_uri}" width="100%" height="920px" style="border:none;"></iframe>'

def boost_prompt(prompt: str) -> str:
    """
    '증강' 버튼 눌렀을 때 프롬프트를 좀 더 풍부하게 생성하되 간결함 유지
    """
    if not prompt:
        return ""
    boost_system_prompt = """당신은 웹 게임 개발 프롬프트 전문가입니다.
주어진 프롬프트를 분석하여 더 명확하고 간결한 요구사항으로 변환하되,
원래 의도와 목적은 그대로 유지하면서 다음 관점들을 고려하여 증강하십시오:

1. 게임플레이 핵심 메커니즘 명확히 정의
2. 필수적인 상호작용 요소만 포함
3. 핵심 UI 요소 간략히 기술
4. 코드 간결성 유지를 위한 우선순위 설정
5. 기본적인 게임 규칙과 승리/패배 조건 명시

다음 중요 지침을 반드시 준수하세요:
- 불필요한 세부 사항이나 부가 기능은 제외
- 생성될 코드가 600줄을 넘지 않도록 기능을 제한
- 명확하고 간결한 언어로 요구사항 작성
- 최소한의 필수 게임 요소만 포함
"""
    try:
        # Claude API 시도
        try:
            response = claude_client.messages.create(
                model="claude-3-7-sonnet-20250219",
                max_tokens=10000,  # 출력 길이 제한
                temperature=0.3,  # 온도 낮게
                messages=[{
                    "role": "user",
                    "content": f"다음 게임 프롬프트를 분석하고 증강하되, 간결함을 유지하세요: {prompt}"
                }],
                system=boost_system_prompt
            )
            if hasattr(response, 'content') and len(response.content) > 0:
                return response.content[0].text
            raise Exception("Claude API 응답 형식 오류")
        except Exception:
            # OpenAI API로 fallback
            completion = openai_client.chat.completions.create(
                model="gpt-4",
                messages=[
                    {"role": "system", "content": boost_system_prompt},
                    {"role": "user", "content": f"다음 게임 프롬프트를 분석하고 증강하되, 간결함을 유지하세요: {prompt}"}
                ],
                max_tokens=10000,
                temperature=0.3
            )
            if completion.choices and len(completion.choices) > 0:
                return completion.choices[0].message.content
            raise Exception("OpenAI API 응답 형식 오류")
    except Exception:
        # 실패 시 원본 그대로 반환
        return prompt
        


def handle_boost(prompt: str):
    try:
        boosted_prompt = boost_prompt(prompt)
        return boosted_prompt, gr.update(active_key="empty")
    except Exception:
        return prompt, gr.update(active_key="empty")

def history_render(history: History):
    """
    히스토리 Drawer 열고, Chatbot UI에 히스토리 반영
    """
    return gr.update(open=True), history

def execute_code(query: str):
    """
    Improved function to execute code directly from input
    코드 실행 시 ```html 태그를 확실히 제거
    """
    if not query or query.strip() == '':
        return None, gr.update(active_key="empty")
    try:
        # 코드 정제 - 마크다운 태그 철저히 제거
        clean_code = remove_code_block(query)
        
        # ```html 태그가 여전히 있으면 명시적으로 제거
        if clean_code.startswith('```html'):
            clean_code = clean_code[7:].strip()
        if clean_code.endswith('```'):
            clean_code = clean_code[:-3].strip()
        
        # HTML 구조 추가
        if not clean_code.strip().startswith('<!DOCTYPE') and not clean_code.strip().startswith('<html'):
            if not ('<body' in clean_code and '</body>' in clean_code):
                clean_code = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game Preview</title>
</head>
<body>
{clean_code}
</body>
</html>"""
                
        return send_to_sandbox(clean_code), gr.update(active_key="render")
    except Exception as e:
        print(f"Execute code error: {str(e)}")
        return None, gr.update(active_key="empty")


# ------------------------
# 6) 데모 클래스
# ------------------------

async def generation_code(self, query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
    if not query or query.strip() == '':
        query = random.choice(DEMO_LIST)['description']
    
    if _history is None:
        _history = []
    
    # 프롬프트 제한 및 강화
    query = f"""
다음 게임을 제작해주세요. 
중요 요구사항: 
1. 코드는 가능한 한 간결하게 작성할 것
2. 불필요한 주석이나 설명은 제외할 것
3. 코드는 200줄을 넘지 않을 것
4. 모든 코드는 하나의 HTML 파일에 통합할 것
5. 핵심 기능만 구현하고 부가 기능은 생략할 것

게임 요청: {query}
"""
    
    messages = history_to_messages(_history, _setting['system'])
    system_message = messages[0]['content']
    
    claude_messages = [
        {"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]} 
        for msg in messages[1:] + [{'role': Role.USER, 'content': query}]
        if msg["content"].strip() != ''
    ]
    
    openai_messages = [{"role": "system", "content": system_message}]
    for msg in messages[1:]:
        openai_messages.append({
            "role": msg["role"],
            "content": msg["content"]
        })
    openai_messages.append({"role": "user", "content": query})
    
    try:
        # "Generating code..." 출력
        yield [
            "Generating code...",
            _history,
            None,
            gr.update(active_key="loading"),
            gr.update(open=True)
        ]
        await asyncio.sleep(0)

        collected_content = None
        try:
            # Claude API 시도
            async for content in try_claude_api(system_message, claude_messages):
                yield [
                    content,
                    _history,
                    None,
                    gr.update(active_key="loading"),
                    gr.update(open=True)
                ]
                await asyncio.sleep(0)
            collected_content = content
        except Exception:
            # OpenAI fallback
            async for content in try_openai_api(openai_messages):
                yield [
                    content,
                    _history,
                    None,
                    gr.update(active_key="loading"),
                    gr.update(open=True)
                ]
                await asyncio.sleep(0)
            collected_content = content

        if collected_content:
            # 코드 크기 확인하고 필요하면 경고 추가
            clean_code = remove_code_block(collected_content)
            code_lines = clean_code.count('\n') + 1
            
            if code_lines > 250:  # 여유 있게 250줄로 체크
                warning_msg = f"""
⚠️ **경고: 생성된 코드가 너무 깁니다 ({code_lines}줄)**

이로 인해 실행 시 오류가 발생할 수 있습니다. 다음과 같이 시도해 보세요:
1. 더 간단한 게임을 요청하세요
2. 특정 기능만 명시하여 요청하세요 (예: "간단한 Snake 게임, 점수 시스템 없이")
3. "코드" 버튼을 사용하여 직접 실행해 보세요

```html
{clean_code[:2000]}
... (코드가 너무 깁니다) ...
"""
collected_content = warning_msg
# 히스토리에는 추가하지 않음
yield [
collected_content,
_history,
None,
gr.update(active_key="empty"),
gr.update(open=True)
]
else:
# 히스토리 갱신
_history = messages_to_history([
{'role': Role.SYSTEM, 'content': system_message}
] + claude_messages + [{
'role': Role.ASSISTANT,
'content': collected_content
}])
            # 최종 결과(코드) + 샌드박스 미리보기
            yield [
                collected_content,
                _history,
                send_to_sandbox(clean_code),
                gr.update(active_key="render"),
                gr.update(open=True)
            ]
    else:
        raise ValueError("No content was generated from either API")
except Exception as e:
    raise ValueError(f'Error calling APIs: {str(e)}')


# ------------------------
# 7) Gradio / Modelscope UI 빌드
# ------------------------

demo_instance = Demo()
theme = gr.themes.Soft(
    primary_hue="blue",
    secondary_hue="purple",
    neutral_hue="slate",
    spacing_size=gr.themes.sizes.spacing_md,
    radius_size=gr.themes.sizes.radius_md,
    text_size=gr.themes.sizes.text_md,
)

with gr.Blocks(css_paths=["app.css"], theme=theme) as demo:
    gr.HTML("""
    <style>
    /* 전체 앱 스타일 */
    :root {
        --primary-color: #9c89b8;
        --secondary-color: #f0a6ca;
        --accent-color: #b8bedd;
        --background-color: #f9f7fd;
        --panel-color: #ffffff;
        --text-color: #3a3042;
        --button-hover: #efc3e6;
        --shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
        --radius: 12px;
    }
    
    body {
        background-color: var(--background-color);
        color: var(--text-color);
        font-family: 'Poppins', sans-serif;
    }
    
    /* 헤더 스타일 */
    .app-header {
        text-align: center;
        padding: 1.5rem 1rem;
        margin-bottom: 1.5rem;
        background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
        border-radius: var(--radius);
        box-shadow: var(--shadow);
        color: white;
    }
    
    .app-header h1 {
        font-size: 2.5rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
        text-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .app-header p {
        font-size: 1.1rem;
        opacity: 0.9;
        max-width: 800px;
        margin: 0 auto;
    }
    </style>
    
    <div class="app-header">
        <h1>🎮 Vibe Game Craft</h1>
        <p>설명을 입력하면 웹 기반 HTML5, JavaScript, CSS 게임을 생성합니다. 직관적인 인터페이스로 쉽게 게임을 만들고, 실시간으로 미리보기를 확인하세요.</p>
    </div>
    """)

    history = gr.State([])
    setting = gr.State({"system": SystemPrompt})

    with ms.Application() as app:
        with antd.ConfigProvider():

            # code Drawer
            with antd.Drawer(open=False, title="코드 보기", placement="left", width="750px") as code_drawer:
                code_output = legacy.Markdown()

            # history Drawer
            with antd.Drawer(open=False, title="히스토리", placement="left", width="900px") as history_drawer:
                history_output = legacy.Chatbot(
                    show_label=False, flushing=False, height=960, elem_classes="history_chatbot"
                )

            # templates Drawer (하나로 통합)
            with antd.Drawer(
                open=False,
                title="게임 템플릿",
                placement="right",
                width="900px",
                elem_classes="session-drawer"
            ) as session_drawer:
                with antd.Flex(vertical=True, gap="middle"):
                    gr.Markdown("### 사용 가능한 게임 템플릿")
                    session_history = gr.HTML(elem_classes="session-history")
                    close_btn = antd.Button("닫기", type="default", elem_classes="close-btn")

            # 좌우 레이아웃 + 상단 정렬
            with antd.Row(gutter=[32, 12], align="top", elem_classes="equal-height-container") as layout:

                # 왼쪽 Col: 미리보기 (상단 정렬)
                with antd.Col(span=24, md=16, elem_classes="equal-height-col"):
                    with ms.Div(elem_classes="right_panel panel"):
                        gr.HTML(r"""
<div class="render_header">
    <span class="header_btn"></span>
    <span class="header_btn"></span>
    <span class="header_btn"></span>
</div>
""")
                        with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
                            with antd.Tabs.Item(key="empty"):
                                empty = antd.Empty(description="게임을 만들려면 설명을 입력하세요", elem_classes="right_content")
                            with antd.Tabs.Item(key="loading"):
                                loading = antd.Spin(
                                    True, tip="게임 코드 생성 중...", size="large", elem_classes="right_content"
                                )
                            with antd.Tabs.Item(key="render"):
                                sandbox = gr.HTML(elem_classes="html_content")

                # 오른쪽 Col: 상단에 메뉴 버튼들과 액션 버튼들, 그 아래 입력창 + 배포 결과
                with antd.Col(span=24, md=8, elem_classes="equal-height-col"):
                    # 우측 상단 메뉴 + 액션 버튼
                    with antd.Flex(vertical=True, gap="small", elem_classes="right-top-buttons"):
                        # ── (1) 상단 메뉴 Bar (코드보기, 히스토리, 템플릿) ──
                        with antd.Flex(gap="small", elem_classes="setting-buttons", justify="space-between"):
                            codeBtn = antd.Button("🧑‍💻 코드 보기", type="default", elem_classes="code-btn")
                            historyBtn = antd.Button("📜 히스토리", type="default", elem_classes="history-btn")
                            template_btn = antd.Button("🎮 템플릿", type="default", elem_classes="template-btn")
                        
                        # ── (2) 액션 버튼들 ──
                        with antd.Flex(gap="small", justify="space-between", elem_classes="action-buttons"):
                            btn = antd.Button("전송", type="primary", size="large", elem_classes="send-btn")
                            boost_btn = antd.Button("증강", type="default", size="large", elem_classes="boost-btn")
                            execute_btn = antd.Button("코드", type="default", size="large", elem_classes="execute-btn")
                            deploy_btn = antd.Button("배포", type="default", size="large", elem_classes="deploy-btn")
                            clear_btn = antd.Button("클리어", type="default", size="large", elem_classes="clear-btn")

                    # ── (3) 입력창 ──
                    with antd.Flex(vertical=True, gap="middle", wrap=True, elem_classes="input-panel"):
                        # 입력 영역
                        input_text = antd.InputTextarea(
                            size="large",
                            allow_clear=True,
                            placeholder=random.choice(DEMO_LIST)['description'],
                            max_length=100000
                        )
                        gr.HTML('<div class="help-text">💡 원하는 게임의 설명을 입력하세요. 예: "테트리스 게임 제작해줘."</div>')

                        # ── (4) 배포 결과 영역 ──
                        deploy_result = gr.HTML(label="배포 결과")


            # ---- 이벤트 / 콜백 ----

            # (A) Code Drawer 열기/닫기
            codeBtn.click(
                lambda: gr.update(open=True),
                inputs=[],
                outputs=[code_drawer]
            )
            code_drawer.close(
                lambda: gr.update(open=False),
                inputs=[],
                outputs=[code_drawer]
            )

            # (B) 히스토리 Drawer 열기/닫기
            historyBtn.click(
                history_render,
                inputs=[history],
                outputs=[history_drawer, history_output]
            )
            history_drawer.close(
                lambda: gr.update(open=False),
                inputs=[],
                outputs=[history_drawer]
            )

            # (C) 템플릿 Drawer 열기/닫기 (하나로 통합)
            template_btn.click(
                fn=lambda: (gr.update(open=True), load_all_templates()),
                outputs=[session_drawer, session_history],
                queue=False
            )
            session_drawer.close(
                lambda: (gr.update(open=False), gr.HTML("")),
                outputs=[session_drawer, session_history]
            )
            close_btn.click(
                lambda: (gr.update(open=False), gr.HTML("")),
                outputs=[session_drawer, session_history]
            )

            # (D) 'Send' 버튼 => 코드 생성
            btn.click(
                demo_instance.generation_code,
                inputs=[input_text, setting, history],
                outputs=[code_output, history, sandbox, state_tab, code_drawer]
            )

            # (E) '클리어' 버튼 => 히스토리 초기화
            clear_btn.click(
                demo_instance.clear_history,
                inputs=[],
                outputs=[history]
            )

            # (F) 'Boost' 버튼 => 프롬프트 보강
            boost_btn.click(
                fn=handle_boost,
                inputs=[input_text],
                outputs=[input_text, state_tab]
            )

            # (G) 'Code실행' 버튼 => 미리보기 iframe 로드
            execute_btn.click(
                fn=execute_code,
                inputs=[input_text],
                outputs=[sandbox, state_tab]
            )

            # (H) '배포' 버튼 => Vercel
            deploy_btn.click(
                fn=lambda code: deploy_to_vercel(remove_code_block(code)) if code else "코드가 없습니다.",
                inputs=[code_output],
                outputs=[deploy_result]
            )

# ------------------------
# 8) 실제 실행
# ------------------------

if __name__ == "__main__":
    try:
        demo_instance = Demo()
        demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
    except Exception as e:
        print(f"Initialization error: {e}")
        raise