File size: 65,374 Bytes
625078a
 
 
 
 
 
f1a53c8
625078a
 
 
 
f1a53c8
 
 
 
625078a
 
 
 
 
6604393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8acb643
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8acb643
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a14346c
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6604393
 
f1a53c8
 
 
a14346c
 
 
 
 
 
 
 
 
 
 
 
6604393
 
 
a14346c
 
 
 
 
 
 
 
f1a53c8
a14346c
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
a14346c
6d93c4e
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
 
 
625078a
 
 
 
 
 
 
 
 
 
f1a53c8
 
 
 
 
625078a
 
 
 
 
 
 
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8acb643
625078a
 
 
 
 
 
 
 
 
 
a14346c
6604393
625078a
 
8acb643
625078a
 
 
 
 
 
 
 
 
 
 
 
 
6604393
a14346c
625078a
 
 
 
 
 
 
a14346c
6604393
625078a
 
8acb643
625078a
 
 
 
 
 
 
 
 
 
 
 
 
6604393
a14346c
625078a
 
 
 
 
 
 
 
 
a14346c
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a14346c
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8acb643
6604393
625078a
 
 
 
 
a14346c
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8acb643
6604393
625078a
 
 
 
 
a14346c
 
625078a
 
 
a14346c
 
625078a
 
 
 
 
 
a14346c
 
 
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a14346c
 
 
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6604393
a14346c
 
625078a
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
6604393
625078a
 
 
 
6604393
 
625078a
6604393
625078a
 
 
 
 
 
6604393
625078a
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
6604393
625078a
 
 
 
6604393
 
625078a
6604393
625078a
 
 
 
 
 
6604393
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8acb643
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a14346c
 
 
 
 
 
 
 
 
 
625078a
 
 
 
 
a14346c
 
 
 
 
 
 
 
 
 
625078a
 
 
a14346c
625078a
 
 
 
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7651773
 
a14346c
7651773
6604393
625078a
a14346c
625078a
 
 
 
a14346c
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7651773
 
a14346c
7651773
8acb643
625078a
a14346c
7651773
625078a
 
f1a53c8
 
 
625078a
 
a14346c
625078a
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
a14346c
 
625078a
 
 
 
 
 
 
f1a53c8
625078a
f1a53c8
 
 
 
 
 
 
 
625078a
f1a53c8
 
 
 
 
 
625078a
f1a53c8
 
 
 
 
 
 
625078a
f1a53c8
 
 
 
625078a
f1a53c8
 
 
625078a
f1a53c8
 
 
 
 
 
 
 
 
625078a
 
 
f1a53c8
a14346c
625078a
f1a53c8
625078a
f1a53c8
625078a
f1a53c8
 
625078a
 
f1a53c8
 
625078a
 
f1a53c8
 
 
 
 
 
 
 
 
 
 
625078a
 
f1a53c8
 
625078a
a14346c
f1a53c8
625078a
 
 
 
 
 
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
625078a
 
 
 
 
 
 
f1a53c8
 
a14346c
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a14346c
 
f1a53c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a14346c
6604393
a14346c
6604393
f1a53c8
 
 
 
 
 
 
a14346c
6604393
f1a53c8
 
 
 
6604393
f1a53c8
 
 
6604393
a14346c
f1a53c8
6604393
a14346c
f1a53c8
6604393
f1a53c8
 
 
 
 
625078a
 
7651773
625078a
f1a53c8
625078a
 
 
 
 
 
 
 
 
f1a53c8
7651773
 
625078a
 
 
7651773
625078a
 
 
 
 
 
 
 
7651773
 
 
 
 
 
 
 
 
 
8acb643
7651773
 
 
 
 
 
f1a53c8
6f6b5f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a53c8
7651773
f1a53c8
 
 
 
 
7651773
f1a53c8
625078a
 
 
 
 
6604393
 
 
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8acb643
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a53c8
 
 
 
 
 
 
 
 
7651773
 
6d93c4e
7651773
 
6d93c4e
 
 
7651773
 
 
6d93c4e
7651773
 
 
6d93c4e
 
7651773
6d93c4e
 
 
7651773
6d93c4e
6604393
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a53c8
625078a
 
 
 
f1a53c8
 
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a53c8
 
 
 
 
 
 
 
 
 
 
625078a
 
 
7651773
 
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7651773
 
625078a
f1a53c8
6f6b5f6
 
 
 
 
 
f1a53c8
625078a
 
7651773
 
625078a
 
7651773
 
625078a
 
f1a53c8
 
 
 
 
 
7651773
 
f1a53c8
 
 
 
 
 
 
625078a
a14346c
 
6d93c4e
 
625078a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a53c8
a14346c
7651773
 
 
 
625078a
 
 
 
 
 
 
6f6b5f6
 
 
 
 
625078a
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
import gradio as gr
import os
import json
import requests
from datetime import datetime
import time
from typing import List, Dict, Any, Generator, Tuple, Optional
import logging
import re
import tempfile
from pathlib import Path
import sqlite3
import hashlib
import threading
from contextlib import contextmanager

# λ‘œκΉ… μ„€μ •
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Document export imports
try:
    from docx import Document
    from docx.shared import Inches, Pt, RGBColor
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    from docx.enum.style import WD_STYLE_TYPE
    DOCX_AVAILABLE = True
except ImportError:
    DOCX_AVAILABLE = False
    logger.warning("python-docx not installed. DOCX export will be disabled.")

# ν™˜κ²½ λ³€μˆ˜μ—μ„œ 토큰 κ°€μ Έμ˜€κΈ°
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "YOUR_FRIENDLI_TOKEN")
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
MODEL_ID = "dep89a2fld32mcm"
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"

# μ „μ—­ λ³€μˆ˜
conversation_history = []
selected_language = "English"  # κΈ°λ³Έ μ–Έμ–΄

# DB 경둜
DB_PATH = "novel_sessions.db"
db_lock = threading.Lock()

class NovelDatabase:
    """Novel session management database"""
    
    @staticmethod
    def init_db():
        """Initialize database tables"""
        with sqlite3.connect(DB_PATH) as conn:
            cursor = conn.cursor()
            
            # Sessions table
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS sessions (
                    session_id TEXT PRIMARY KEY,
                    user_query TEXT NOT NULL,
                    language TEXT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    status TEXT DEFAULT 'active',
                    current_stage INTEGER DEFAULT 0,
                    final_novel TEXT
                )
            ''')
            
            # Stages table - 각 μŠ€ν…Œμ΄μ§€μ˜ 전체 λ‚΄μš© μ €μž₯
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS stages (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    session_id TEXT NOT NULL,
                    stage_number INTEGER NOT NULL,
                    stage_name TEXT NOT NULL,
                    role TEXT NOT NULL,
                    content TEXT,
                    status TEXT DEFAULT 'pending',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (session_id) REFERENCES sessions(session_id)
                )
            ''')
            
            # Create indices
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_session_id ON stages(session_id)')
            cursor.execute('CREATE INDEX IF NOT EXISTS idx_stage_number ON stages(stage_number)')
            
            conn.commit()
    
    @staticmethod
    @contextmanager
    def get_db():
        """Database connection context manager"""
        with db_lock:
            conn = sqlite3.connect(DB_PATH)
            conn.row_factory = sqlite3.Row
            try:
                yield conn
            finally:
                conn.close()
    
    @staticmethod
    def create_session(user_query: str, language: str) -> str:
        """Create new session"""
        session_id = hashlib.md5(f"{user_query}{datetime.now()}".encode()).hexdigest()
        
        with NovelDatabase.get_db() as conn:
            cursor = conn.cursor()
            cursor.execute('''
                INSERT INTO sessions (session_id, user_query, language)
                VALUES (?, ?, ?)
            ''', (session_id, user_query, language))
            conn.commit()
        
        return session_id
    
    @staticmethod
    def save_stage(session_id: str, stage_number: int, stage_name: str, 
                   role: str, content: str, status: str = 'complete'):
        """Save stage content - 전체 λ‚΄μš© μ €μž₯"""
        with NovelDatabase.get_db() as conn:
            cursor = conn.cursor()
            
            # Check if stage exists
            cursor.execute('''
                SELECT id FROM stages 
                WHERE session_id = ? AND stage_number = ?
            ''', (session_id, stage_number))
            
            existing = cursor.fetchone()
            
            if existing:
                # Update existing stage
                cursor.execute('''
                    UPDATE stages 
                    SET content = ?, status = ?, stage_name = ?
                    WHERE session_id = ? AND stage_number = ?
                ''', (content, status, stage_name, session_id, stage_number))
            else:
                # Insert new stage
                cursor.execute('''
                    INSERT INTO stages (session_id, stage_number, stage_name, role, content, status)
                    VALUES (?, ?, ?, ?, ?, ?)
                ''', (session_id, stage_number, stage_name, role, content, status))
            
            # Update session
            cursor.execute('''
                UPDATE sessions 
                SET updated_at = CURRENT_TIMESTAMP, current_stage = ?
                WHERE session_id = ?
            ''', (stage_number, session_id))
            
            conn.commit()
            logger.info(f"Saved stage {stage_number} for session {session_id}, content length: {len(content)}")
    
    @staticmethod
    def get_session(session_id: str) -> Optional[Dict]:
        """Get session info"""
        with NovelDatabase.get_db() as conn:
            cursor = conn.cursor()
            cursor.execute('SELECT * FROM sessions WHERE session_id = ?', (session_id,))
            return cursor.fetchone()
    
    @staticmethod
    def get_stages(session_id: str) -> List[Dict]:
        """Get all stages for a session"""
        with NovelDatabase.get_db() as conn:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT * FROM stages 
                WHERE session_id = ? 
                ORDER BY stage_number
            ''', (session_id,))
            return cursor.fetchall()
    
    @staticmethod
    def get_all_writer_content(session_id: str) -> str:
        """λͺ¨λ“  μž‘κ°€μ˜ μˆ˜μ •λ³Έ λ‚΄μš©μ„ κ°€μ Έμ™€μ„œ ν•©μΉ˜κΈ° - 50νŽ˜μ΄μ§€ 전체"""
        with NovelDatabase.get_db() as conn:
            cursor = conn.cursor()
            
            # μž‘κ°€ μˆ˜μ •λ³Έλ§Œ κ°€μ Έμ˜€κΈ° (stage_number 5, 8, 11, 14, 17, 20, 23, 26, 29, 32)
            writer_revision_stages = [5, 8, 11, 14, 17, 20, 23, 26, 29, 32]
            
            all_content = []
            for stage_num in writer_revision_stages:
                cursor.execute('''
                    SELECT content, stage_name FROM stages 
                    WHERE session_id = ? AND stage_number = ?
                ''', (session_id, stage_num))
                
                row = cursor.fetchone()
                if row and row['content']:
                    # νŽ˜μ΄μ§€ 마크 μ™„μ „ 제거
                    clean_content = re.sub(r'\[(?:νŽ˜μ΄μ§€|Page|page)\s*\d+\]', '', row['content'])
                    clean_content = re.sub(r'(?:νŽ˜μ΄μ§€|Page)\s*\d+:', '', clean_content)
                    clean_content = clean_content.strip()
                    
                    if clean_content:
                        all_content.append(clean_content)
                        logger.info(f"Retrieved writer content from stage {stage_num}, length: {len(clean_content)}")
            
            full_content = '\n\n'.join(all_content)
            logger.info(f"Total writer content length: {len(full_content)}, from {len(all_content)} writers")
            
            return full_content
    
    @staticmethod
    def update_final_novel(session_id: str, final_novel: str):
        """Update final novel content"""
        with NovelDatabase.get_db() as conn:
            cursor = conn.cursor()
            cursor.execute('''
                UPDATE sessions 
                SET final_novel = ?, status = 'complete', updated_at = CURRENT_TIMESTAMP
                WHERE session_id = ?
            ''', (final_novel, session_id))
            conn.commit()
            logger.info(f"Updated final novel for session {session_id}, length: {len(final_novel)}")
    
    @staticmethod
    def get_active_sessions() -> List[Dict]:
        """Get all active sessions"""
        with NovelDatabase.get_db() as conn:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT session_id, user_query, language, created_at, current_stage
                FROM sessions 
                WHERE status = 'active'
                ORDER BY updated_at DESC
                LIMIT 10
            ''')
            return cursor.fetchall()

class NovelWritingSystem:
    def __init__(self):
        self.token = FRIENDLI_TOKEN
        self.api_url = API_URL
        self.model_id = MODEL_ID
        self.test_mode = TEST_MODE or (self.token == "YOUR_FRIENDLI_TOKEN")
        
        if self.test_mode:
            logger.warning("Running in test mode.")
        
        # Initialize database
        NovelDatabase.init_db()
        
        # Session management
        self.current_session_id = None
    
    def create_headers(self):
        """API 헀더 생성"""
        return {
            "Authorization": f"Bearer {self.token}",
            "Content-Type": "application/json"
        }
    
    def create_director_initial_prompt(self, user_query: str, language: str = "English") -> str:
        """Director AI initial prompt - Novel planning"""
        if language == "Korean":
            return f"""당신은 50νŽ˜μ΄μ§€ λΆ„λŸ‰μ˜ μ€‘νŽΈ μ†Œμ„€μ„ κΈ°νšν•˜λŠ” λ¬Έν•™ κ°λ…μžμž…λ‹ˆλ‹€.

μ‚¬μš©μž μš”μ²­: {user_query}

λ‹€μŒ μš”μ†Œλ“€μ„ μ²΄κ³„μ μœΌλ‘œ κ΅¬μ„±ν•˜μ—¬ 50νŽ˜μ΄μ§€ μ€‘νŽΈ μ†Œμ„€μ˜ 기초λ₯Ό λ§Œλ“œμ„Έμš”:

1. **μ£Όμ œμ™€ μž₯λ₯΄**
   - 핡심 μ£Όμ œμ™€ λ©”μ‹œμ§€
   - μž₯λ₯΄ 및 톀
   - λͺ©ν‘œ λ…μžμΈ΅

2. **λ“±μž₯인물 μ„€μ •** (ν‘œλ‘œ 정리)
   | 이름 | μ—­ν•  | 성격 | λ°°κ²½ | 동기 | λ³€ν™” |
   |------|------|------|------|------|------|

3. **인물 관계도**
   - μ£Όμš” 인물 κ°„μ˜ 관계
   - κ°ˆλ“± ꡬ쑰
   - 감정적 연결고리

4. **μ„œμ‚¬ ꡬ쑰** (50νŽ˜μ΄μ§€λ₯Ό 10개 파트둜 λ‚˜λˆ„μ–΄ 각 5νŽ˜μ΄μ§€)
   | 파트 | νŽ˜μ΄μ§€ | μ£Όμš” 사건 | κΈ΄μž₯도 | 인물 λ°œμ „ |
   |------|--------|-----------|---------|-----------|

5. **세계관 μ„€μ •**
   - μ‹œκ³΅κ°„μ  λ°°κ²½
   - μ‚¬νšŒμ /문화적 λ§₯락
   - λΆ„μœ„κΈ°μ™€ 톀

각 μž‘μ„±μžκ°€ 5νŽ˜μ΄μ§€μ”© μž‘μ„±ν•  수 μžˆλ„λ‘ λͺ…ν™•ν•œ κ°€μ΄λ“œλΌμΈμ„ μ œμ‹œν•˜μ„Έμš”."""
        else:
            return f"""You are a literary director planning a 50-page novella.

User Request: {user_query}

Systematically compose the following elements to create the foundation for a 50-page novella:

1. **Theme and Genre**
   - Core theme and message
   - Genre and tone
   - Target audience

2. **Character Settings** (organize in table)
   | Name | Role | Personality | Background | Motivation | Arc |
   |------|------|-------------|------------|------------|-----|

3. **Character Relationship Map**
   - Relationships between main characters
   - Conflict structure
   - Emotional connections

4. **Narrative Structure** (divide 50 pages into 10 parts, 5 pages each)
   | Part | Pages | Main Events | Tension | Character Development |
   |------|-------|-------------|---------|---------------------|

5. **World Building**
   - Temporal and spatial setting
   - Social/cultural context
   - Atmosphere and tone

Provide clear guidelines for each writer to compose 5 pages."""
    
    def create_critic_director_prompt(self, director_plan: str, language: str = "English") -> str:
        """Critic's review of director's plan"""
        if language == "Korean":
            return f"""당신은 λ¬Έν•™ λΉ„ν‰κ°€μž…λ‹ˆλ‹€. κ°λ…μžμ˜ μ†Œμ„€ κΈ°νšμ„ κ²€ν† ν•˜κ³  κ°œμ„ μ μ„ μ œμ‹œν•˜μ„Έμš”.

κ°λ…μžμ˜ 기획:
{director_plan}

λ‹€μŒ κ΄€μ μ—μ„œ λΉ„ν‰ν•˜κ³  ꡬ체적인 κ°œμ„ μ•ˆμ„ μ œμ‹œν•˜μ„Έμš”:

1. **μ„œμ‚¬μ  완성도**
   - ν”Œλ‘―μ˜ 논리성과 κ°œμ—°μ„±
   - κ°ˆλ“±μ˜ νš¨κ³Όμ„±
   - 클라이λ§₯슀의 μœ„μΉ˜μ™€ 강도

2. **인물 μ„€μ • κ²€ν† **
   | 인물 | 강점 | 약점 | κ°œμ„  μ œμ•ˆ |
   |------|------|------|-----------|

3. **ꡬ쑰적 κ· ν˜•**
   - 각 νŒŒνŠΈλ³„ λΆ„λŸ‰ λ°°λΆ„
   - κΈ΄μž₯κ³Ό μ΄μ™„μ˜ 리듬
   - 전체적인 흐름

4. **λ…μž 관점**
   - λͺ°μž…도 μ˜ˆμƒ
   - 감정적 영ν–₯λ ₯
   - κΈ°λŒ€μΉ˜ 좩쑱도

5. **μ‹€ν–‰ κ°€λŠ₯μ„±**
   - 각 μž‘μ„±μžλ₯Ό μœ„ν•œ κ°€μ΄λ“œλΌμΈμ˜ λͺ…ν™•μ„±
   - 일관성 μœ μ§€ λ°©μ•ˆ
   - 잠재적 문제점

ꡬ체적이고 건섀적인 ν”Όλ“œλ°±μ„ μ œκ³΅ν•˜μ„Έμš”."""
        else:
            return f"""You are a literary critic. Review the director's novel plan and suggest improvements.

Director's Plan:
{director_plan}

Critique from the following perspectives and provide specific improvements:

1. **Narrative Completeness**
   - Plot logic and plausibility
   - Effectiveness of conflicts
   - Climax position and intensity

2. **Character Review**
   | Character | Strengths | Weaknesses | Suggestions |
   |-----------|-----------|------------|-------------|

3. **Structural Balance**
   - Distribution across parts
   - Rhythm of tension and relief
   - Overall flow

4. **Reader Perspective**
   - Expected engagement
   - Emotional impact
   - Expectation fulfillment

5. **Feasibility**
   - Clarity of guidelines for each writer
   - Consistency maintenance
   - Potential issues

Provide specific and constructive feedback."""
    
    def create_director_revision_prompt(self, initial_plan: str, critic_feedback: str, language: str = "English") -> str:
        """Director's revision based on critic feedback"""
        if language == "Korean":
            return f"""κ°λ…μžλ‘œμ„œ λΉ„ν‰κ°€μ˜ ν”Όλ“œλ°±μ„ λ°˜μ˜ν•˜μ—¬ μ†Œμ„€ κΈ°νšμ„ μˆ˜μ •ν•©λ‹ˆλ‹€.

초기 기획:
{initial_plan}

비평가 ν”Όλ“œλ°±:
{critic_feedback}

λ‹€μŒμ„ ν¬ν•¨ν•œ μˆ˜μ •λœ μ΅œμ’… κΈ°νšμ„ μ œμ‹œν•˜μ„Έμš”:

1. **μˆ˜μ •λœ μ„œμ‚¬ ꡬ쑰**
   | 파트 | νŽ˜μ΄μ§€ | μ£Όμš” 사건 | μž‘μ„± μ§€μΉ¨ | μ£Όμ˜μ‚¬ν•­ |
   |------|--------|-----------|-----------|----------|

2. **κ°•ν™”λœ 인물 μ„€μ •**
   - 각 인물의 λͺ…ν™•ν•œ 동기와 λͺ©ν‘œ
   - 인물 κ°„ κ°ˆλ“±μ˜ ꡬ체화
   - κ°μ •μ„ μ˜ λ³€ν™” 좔이

3. **각 μž‘μ„±μžλ₯Ό μœ„ν•œ 상세 κ°€μ΄λ“œ**
   - νŒŒνŠΈλ³„ μ‹œμž‘κ³Ό 끝 지점
   - ν•„μˆ˜ 포함 μš”μ†Œ
   - 문체와 톀 μ§€μΉ¨
   - 전달해야 ν•  정보

4. **일관성 μœ μ§€ 체크리슀트**
   - μ‹œκ°„μ„  관리
   - 인물 νŠΉμ„± μœ μ§€
   - μ„€μ • 일관성
   - 볡선과 ν•΄κ²°

5. **ν’ˆμ§ˆ κΈ°μ€€**
   - 각 파트의 완성도 κΈ°μ€€
   - 전체적 톡일성
   - λ…μž λͺ°μž… μœ μ§€ λ°©μ•ˆ

λͺ¨λ“  μž‘μ„±μžκ°€ λͺ…ν™•νžˆ 이해할 수 μžˆλŠ” μ΅œμ’… λ§ˆμŠ€ν„°ν”Œλžœμ„ μž‘μ„±ν•˜μ„Έμš”."""
        else:
            return f"""As director, revise the novel plan reflecting the critic's feedback.

Initial Plan:
{initial_plan}

Critic Feedback:
{critic_feedback}

Present the revised final plan including:

1. **Revised Narrative Structure**
   | Part | Pages | Main Events | Writing Guidelines | Cautions |
   |------|-------|-------------|-------------------|----------|

2. **Enhanced Character Settings**
   - Clear motivations and goals for each character
   - Concrete conflicts between characters
   - Emotional arc progression

3. **Detailed Guide for Each Writer**
   - Start and end points for each part
   - Essential elements to include
   - Style and tone guidelines
   - Information to convey

4. **Consistency Checklist**
   - Timeline management
   - Character trait maintenance
   - Setting consistency
   - Foreshadowing and resolution

5. **Quality Standards**
   - Completion criteria for each part
   - Overall unity
   - Reader engagement maintenance

Create a final masterplan that all writers can clearly understand."""
    
    def create_writer_prompt(self, writer_number: int, director_plan: str, previous_content: str, language: str = "English") -> str:
        """Individual writer prompt - νŽ˜μ΄μ§€λ‹Ή 500-600λ‹¨μ–΄λ‘œ 증가"""
        pages_start = (writer_number - 1) * 5 + 1
        pages_end = writer_number * 5
        
        if language == "Korean":
            return f"""당신은 μž‘μ„±μž {writer_number}λ²ˆμž…λ‹ˆλ‹€. 50νŽ˜μ΄μ§€ μ€‘νŽΈ μ†Œμ„€μ˜ {pages_start}-{pages_end}νŽ˜μ΄μ§€(5νŽ˜μ΄μ§€)λ₯Ό μž‘μ„±ν•˜μ„Έμš”.

κ°λ…μžμ˜ λ§ˆμŠ€ν„°ν”Œλžœ:
{director_plan}

{'μ΄μ „κΉŒμ§€μ˜ λ‚΄μš©:' if previous_content else '당신이 첫 번째 μž‘μ„±μžμž…λ‹ˆλ‹€.'}
{previous_content[-2000:] if previous_content else ''}

λ‹€μŒ 지침에 따라 μž‘μ„±ν•˜μ„Έμš”:

1. **λΆ„λŸ‰**: μ •ν™•νžˆ 5νŽ˜μ΄μ§€ (νŽ˜μ΄μ§€λ‹Ή μ•½ 500-600단어, 총 2500-3000단어)
2. **연속성**: 이전 λ‚΄μš©κ³Ό μžμ—°μŠ€λŸ½κ²Œ 이어지도둝
3. **일관성**: 
   - λ“±μž₯인물의 성격과 말투 μœ μ§€
   - μ‹œκ°„μ„ κ³Ό 곡간 μ„€μ • μ€€μˆ˜
   - 이미 μ œμ‹œλœ 사싀듀과 λͺ¨μˆœ 없이
4. **λ°œμ „**: 
   - ν”Œλ‘―μ„ μ „μ§„μ‹œν‚€κΈ°
   - 인물의 μ„±μž₯μ΄λ‚˜ λ³€ν™” ν‘œν˜„
   - κΈ΄μž₯감 쑰절
5. **문체**: 
   - 전체적인 톀과 λΆ„μœ„κΈ° μœ μ§€
   - λ…μžμ˜ λͺ°μž…을 ν•΄μΉ˜μ§€ μ•ŠκΈ°

μ€‘μš”: νŽ˜μ΄μ§€ ꡬ뢄 ν‘œμ‹œλ₯Ό μ ˆλŒ€ ν•˜μ§€ λ§ˆμ„Έμš”. μžμ—°μŠ€λŸ½κ²Œ μ΄μ–΄μ§€λŠ” μ„œμ‚¬λ‘œ μž‘μ„±ν•˜μ„Έμš”.
λ°˜λ“œμ‹œ 2500-3000단어 λΆ„λŸ‰μ„ μ±„μ›Œμ£Όμ„Έμš”."""
        else:
            return f"""You are Writer #{writer_number}. Write pages {pages_start}-{pages_end} (5 pages) of the 50-page novella.

Director's Masterplan:
{director_plan}

{'Previous content:' if previous_content else 'You are the first writer.'}
{previous_content[-2000:] if previous_content else ''}

Write according to these guidelines:

1. **Length**: Exactly 5 pages (about 500-600 words per page, total 2500-3000 words)
2. **Continuity**: Flow naturally from previous content
3. **Consistency**: 
   - Maintain character personalities and speech
   - Follow timeline and spatial settings
   - No contradictions with established facts
4. **Development**: 
   - Advance the plot
   - Show character growth or change
   - Control tension
5. **Style**: 
   - Maintain overall tone and atmosphere
   - Keep reader immersion

Important: DO NOT use any page markers. Write as continuous narrative.
You MUST write 2500-3000 words."""
    
    def create_critic_writer_prompt(self, writer_number: int, writer_content: str, director_plan: str, all_previous_content: str, language: str = "English") -> str:
        """Critic's review of individual writer's work"""
        if language == "Korean":
            return f"""μž‘μ„±μž {writer_number}번의 μž‘ν’ˆμ„ λΉ„ν‰ν•©λ‹ˆλ‹€.

κ°λ…μžμ˜ λ§ˆμŠ€ν„°ν”Œλžœ:
{director_plan}

이전 λ‚΄μš© μš”μ•½:
{all_previous_content[-1000:] if all_previous_content else '첫 번째 μž‘μ„±μžμž…λ‹ˆλ‹€.'}

μž‘μ„±μž {writer_number}번의 λ‚΄μš©:
{writer_content}

λ‹€μŒ κΈ°μ€€μœΌλ‘œ ν‰κ°€ν•˜κ³  μˆ˜μ • μš”κ΅¬μ‚¬ν•­μ„ μ œμ‹œν•˜μ„Έμš”:

1. **일관성 검증** (ν‘œλ‘œ 정리)
   | μš”μ†Œ | 이전 μ„€μ • | ν˜„μž¬ ν‘œν˜„ | 문제점 | μˆ˜μ • ν•„μš” |
   |------|----------|----------|--------|----------|

2. **논리적 였λ₯˜ κ²€ν† **
   - μ‹œκ°„μ„  λͺ¨μˆœ
   - 인물 ν–‰λ™μ˜ κ°œμ—°μ„±
   - μ„€μ • 좩돌
   - 사싀관계 였λ₯˜

3. **μ„œμ‚¬μ  νš¨κ³Όμ„±**
   - ν”Œλ‘― μ§„ν–‰ 기여도
   - κΈ΄μž₯감 μœ μ§€
   - λ…μž λͺ°μž…도
   - 감정적 영ν–₯λ ₯

4. **문체와 ν’ˆμ§ˆ**
   - 전체 ν†€κ³Όμ˜ 일치
   - λ¬Έμž₯의 질
   - λ¬˜μ‚¬μ˜ μ μ ˆμ„±
   - λŒ€ν™”μ˜ μžμ—°μŠ€λŸ¬μ›€

5. **κ°œμ„  μš”κ΅¬μ‚¬ν•­**
   - ν•„μˆ˜ μˆ˜μ • 사항 (일관성/논리 였λ₯˜)
   - ꢌμž₯ κ°œμ„  사항 (ν’ˆμ§ˆ ν–₯상)
   - ꡬ체적 μˆ˜μ • μ§€μΉ¨

λ°˜λ“œμ‹œ μˆ˜μ •μ΄ ν•„μš”ν•œ λΆ€λΆ„κ³Ό 선택적 κ°œμ„ μ‚¬ν•­μ„ κ΅¬λΆ„ν•˜μ—¬ μ œμ‹œν•˜μ„Έμš”."""
        else:
            return f"""Critiquing Writer #{writer_number}'s work.

Director's Masterplan:
{director_plan}

Previous Content Summary:
{all_previous_content[-1000:] if all_previous_content else 'This is the first writer.'}

Writer #{writer_number}'s Content:
{writer_content}

Evaluate by these criteria and present revision requirements:

1. **Consistency Verification** (organize in table)
   | Element | Previous Setting | Current Expression | Issue | Revision Needed |
   |---------|-----------------|-------------------|-------|-----------------|

2. **Logical Error Review**
   - Timeline contradictions
   - Character action plausibility
   - Setting conflicts
   - Factual errors

3. **Narrative Effectiveness**
   - Plot progression contribution
   - Tension maintenance
   - Reader engagement
   - Emotional impact

4. **Style and Quality**
   - Alignment with overall tone
   - Sentence quality
   - Description appropriateness
   - Dialogue naturalness

5. **Improvement Requirements**
   - Mandatory revisions (consistency/logic errors)
   - Recommended improvements (quality enhancement)
   - Specific revision guidelines

Clearly distinguish between mandatory revisions and optional improvements."""
    
    def create_writer_revision_prompt(self, writer_number: int, initial_content: str, critic_feedback: str, language: str = "English") -> str:
        """Writer's revision based on critic feedback"""
        if language == "Korean":
            return f"""μž‘μ„±μž {writer_number}λ²ˆμœΌλ‘œμ„œ λΉ„ν‰κ°€μ˜ ν”Όλ“œλ°±μ„ λ°˜μ˜ν•˜μ—¬ μˆ˜μ •ν•©λ‹ˆλ‹€.

초기 μž‘μ„± λ‚΄μš©:
{initial_content}

비평가 ν”Όλ“œλ°±:
{critic_feedback}

λ‹€μŒ 사항을 λ°˜μ˜ν•œ μˆ˜μ •λ³Έμ„ μž‘μ„±ν•˜μ„Έμš”:

1. **ν•„μˆ˜ μˆ˜μ •μ‚¬ν•­ 반영**
   - λͺ¨λ“  일관성 였λ₯˜ μˆ˜μ •
   - 논리적 λͺ¨μˆœ ν•΄κ²°
   - 사싀관계 μ •μ •

2. **ν’ˆμ§ˆ κ°œμ„ **
   - ꢌμž₯사항 쀑 κ°€λŠ₯ν•œ λΆ€λΆ„ 반영
   - 문체와 톀 μ‘°μ •
   - λ¬˜μ‚¬μ™€ λŒ€ν™” κ°œμ„ 

3. **λΆ„λŸ‰ μœ μ§€**
   - μ—¬μ „νžˆ μ •ν™•νžˆ 5νŽ˜μ΄μ§€ (2500-3000단어)
   - νŽ˜μ΄μ§€ ꡬ뢄 ν‘œμ‹œ μ ˆλŒ€ κΈˆμ§€

4. **연속성 확보**
   - 이전/이후 λ‚΄μš©κ³Όμ˜ μžμ—°μŠ€λŸ¬μš΄ μ—°κ²°
   - μˆ˜μ •μœΌλ‘œ μΈν•œ μƒˆλ‘œμš΄ λͺ¨μˆœ λ°©μ§€

μˆ˜μ •λœ μ΅œμ’…λ³Έμ„ μ œμ‹œν•˜μ„Έμš”. νŽ˜μ΄μ§€ λ§ˆν¬λŠ” μ ˆλŒ€ μ‚¬μš©ν•˜μ§€ λ§ˆμ„Έμš”.
λ°˜λ“œμ‹œ 2500-3000단어 λΆ„λŸ‰μ„ μœ μ§€ν•˜μ„Έμš”."""
        else:
            return f"""As Writer #{writer_number}, revise based on critic's feedback.

Initial Content:
{initial_content}

Critic Feedback:
{critic_feedback}

Write a revision reflecting:

1. **Mandatory Revisions**
   - Fix all consistency errors
   - Resolve logical contradictions
   - Correct factual errors

2. **Quality Improvements**
   - Incorporate feasible recommendations
   - Adjust style and tone
   - Improve descriptions and dialogue

3. **Maintain Length**
   - Still exactly 5 pages (2500-3000 words)
   - Absolutely no page markers

4. **Ensure Continuity**
   - Natural connection with previous/next content
   - Prevent new contradictions from revisions

Present the revised final version. Never use page markers.
You MUST maintain 2500-3000 words."""
    
    def create_critic_final_prompt(self, all_content: str, director_plan: str, language: str = "English") -> str:
        """Final critic evaluation of complete novel"""
        content_preview = all_content[:3000] + "\n...\n" + all_content[-3000:] if len(all_content) > 6000 else all_content
        
        if language == "Korean":
            return f"""전체 50νŽ˜μ΄μ§€ μ†Œμ„€μ„ μ΅œμ’… ν‰κ°€ν•©λ‹ˆλ‹€.

κ°λ…μžμ˜ λ§ˆμŠ€ν„°ν”Œλžœ:
{director_plan}

μ™„μ„±λœ 전체 μ†Œμ„€ (미리보기):
{content_preview}

총 λΆ„λŸ‰: {len(all_content.split())} 단어

쒅합적인 평가와 μ΅œμ’… κ°œμ„  μ œμ•ˆμ„ μ œμ‹œν•˜μ„Έμš”:

1. **전체적 완성도 평가**
   | ν•­λͺ© | 점수(10점) | 평가 | κ°œμ„  ν•„μš” |
   |------|-----------|------|----------|
   | ν”Œλ‘― 일관성 | | | |
   | 인물 λ°œμ „ | | | |
   | 주제 전달 | | | |
   | 문체 톡일성 | | | |
   | λ…μž λͺ°μž…도 | | | |

2. **강점 뢄석**
   - κ°€μž₯ 효과적인 λΆ€λΆ„
   - λ›°μ–΄λ‚œ μž₯λ©΄μ΄λ‚˜ λŒ€ν™”
   - 성곡적인 인물 λ¬˜μ‚¬

3. **약점 및 κ°œμ„ μ **
   - 전체적 νλ¦„μ˜ 문제
   - λ―Έν•΄κ²° ν”Œλ‘―
   - 캐릭터 일관성 이슈
   - νŽ˜μ΄μ‹± 문제

4. **νŒŒνŠΈλ³„ μ—°κ²°μ„±**
   | μ—°κ²°λΆ€ | μžμ—°μŠ€λŸ¬μ›€ | 문제점 | κ°œμ„  μ œμ•ˆ |
   |--------|-----------|--------|----------|

5. **μ΅œμ’… κΆŒκ³ μ‚¬ν•­**
   - μ¦‰μ‹œ μˆ˜μ •μ΄ ν•„μš”ν•œ μ€‘λŒ€ 였λ₯˜
   - 전체적 ν’ˆμ§ˆ ν–₯상을 μœ„ν•œ μ œμ•ˆ
   - 좜판 κ°€λŠ₯μ„± 평가

κ°λ…μžκ°€ μ΅œμ’… μˆ˜μ •ν•  수 μžˆλ„λ‘ ꡬ체적이고 μ‹€ν–‰ κ°€λŠ₯ν•œ ν”Όλ“œλ°±μ„ μ œκ³΅ν•˜μ„Έμš”."""
        else:
            return f"""Final evaluation of the complete 50-page novel.

Director's Masterplan:
{director_plan}

Complete Novel (Preview):
{content_preview}

Total length: {len(all_content.split())} words

Provide comprehensive evaluation and final improvement suggestions:

1. **Overall Completion Assessment**
   | Item | Score(10) | Evaluation | Improvement Needed |
   |------|-----------|------------|-------------------|
   | Plot Consistency | | | |
   | Character Development | | | |
   | Theme Delivery | | | |
   | Style Unity | | | |
   | Reader Engagement | | | |

2. **Strength Analysis**
   - Most effective parts
   - Outstanding scenes or dialogue
   - Successful character portrayal

3. **Weaknesses and Improvements**
   - Overall flow issues
   - Unresolved plots
   - Character consistency issues
   - Pacing problems

4. **Part Connectivity**
   | Connection | Smoothness | Issues | Suggestions |
   |------------|------------|--------|-------------|

5. **Final Recommendations**
   - Critical errors needing immediate fix
   - Suggestions for overall quality improvement
   - Publication readiness assessment

Provide specific and actionable feedback for the director's final revision."""
    
    def create_director_final_prompt(self, all_content: str, critic_final_feedback: str, language: str = "English") -> str:
        """Director's final compilation and polish - λͺ¨λ“  μž‘κ°€ λ‚΄μš© 포함"""
        word_count = len(all_content.split())
        
        if language == "Korean":
            return f"""κ°λ…μžλ‘œμ„œ λΉ„ν‰κ°€μ˜ μ΅œμ’… 평가λ₯Ό λ°˜μ˜ν•˜μ—¬ 완성본을 μ œμž‘ν•©λ‹ˆλ‹€.

전체 μž‘κ°€λ“€μ˜ μž‘ν’ˆ (50νŽ˜μ΄μ§€ 전체, {word_count}단어):
{all_content}

비평가 μ΅œμ’… 평가:
{critic_final_feedback}

λ‹€μŒμ„ ν¬ν•¨ν•œ μ΅œμ’… 완성본을 μ œμ‹œν•˜μ„Έμš”:

# [μ†Œμ„€ 제λͺ©]

## μž‘ν’ˆ 정보
- μž₯λ₯΄: 
- λΆ„λŸ‰: 50νŽ˜μ΄μ§€ ({word_count}단어)
- 주제: 
- ν•œ 쀄 μš”μ•½: 

## λ“±μž₯인물 μ†Œκ°œ
[μ£Όμš” μΈλ¬Όλ“€μ˜ κ°„λ‹¨ν•œ μ†Œκ°œ]

---

## λ³Έλ¬Έ

[10λͺ…μ˜ μž‘κ°€κ°€ μž‘μ„±ν•œ 전체 50νŽ˜μ΄μ§€ λ‚΄μš©μ„ λ‹€μŒ κΈ°μ€€μœΌλ‘œ 톡합]
1. μ€‘λŒ€ 였λ₯˜ μˆ˜μ • μ™„λ£Œ
2. 파트 κ°„ μ—°κ²° λ§€λ„λŸ½κ²Œ μ‘°μ •
3. 문체와 톀 톡일
4. μ΅œμ’… 퇴고 및 윀문
5. νŽ˜μ΄μ§€ ꡬ뢄 ν‘œμ‹œ μ™„μ „ 제거
6. μžμ—°μŠ€λŸ¬μš΄ νλ¦„μœΌλ‘œ μž¬κ΅¬μ„±

[전체 50νŽ˜μ΄μ§€ λΆ„λŸ‰μ˜ μ™„μ„±λœ μ†Œμ„€ λ³Έλ¬Έ]

---

## μž‘κ°€μ˜ 말
[μž‘ν’ˆμ— λŒ€ν•œ κ°„λ‹¨ν•œ ν•΄μ„€μ΄λ‚˜ μ˜λ„]

λͺ¨λ“  μž‘κ°€μ˜ κΈ°μ—¬λ₯Ό ν†΅ν•©ν•œ μ™„μ „ν•œ 50νŽ˜μ΄μ§€ μ†Œμ„€μ„ μ œμ‹œν•˜μ„Έμš”."""
        else:
            return f"""As director, create the final version reflecting the critic's final evaluation.

Complete Writers' Work (Full 50 pages, {word_count} words):
{all_content}

Critic's Final Evaluation:
{critic_final_feedback}

Present the final version including:

# [Novel Title]

## Work Information
- Genre: 
- Length: 50 pages ({word_count} words)
- Theme: 
- One-line summary: 

## Character Introduction
[Brief introduction of main characters]

---

## Main Text

[Integrate all 50 pages written by 10 writers with these criteria]
1. Critical errors corrected
2. Smooth transitions between parts
3. Unified style and tone
4. Final editing and polishing
5. Complete removal of page markers
6. Reorganized for natural flow

[Complete 50-page novel text]

---

## Author's Note
[Brief commentary or intention about the work]

Present a complete 50-page novel integrating all writers' contributions."""
    
    def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
        """Simulate streaming in test mode"""
        words = text.split()
        chunk_size = 5
        for i in range(0, len(words), chunk_size):
            chunk = " ".join(words[i:i+chunk_size])
            yield chunk + " "
            time.sleep(0.02)
    
    def call_llm_streaming(self, messages: List[Dict[str, str]], role: str, language: str = "English") -> Generator[str, None, None]:
        """Streaming LLM API call"""
        
        if self.test_mode:
            logger.info(f"Test mode streaming - Role: {role}, Language: {language}")
            test_response = self.get_test_response(role, language)
            yield from self.simulate_streaming(test_response, role)
            return
        
        # Real API call
        try:
            system_prompts = self.get_system_prompts(language)
            
            full_messages = [
                {"role": "system", "content": system_prompts.get(role, "")},
                *messages
            ]
            
            # μž‘μ„±μžλ“€μ—κ²ŒλŠ” 더 λ§Žμ€ 토큰 ν• λ‹Ή
            max_tokens = 8192 if role.startswith("writer") else 4096
            
            payload = {
                "model": self.model_id,
                "messages": full_messages,
                "max_tokens": max_tokens,
                "temperature": 0.7 if role.startswith("writer") else 0.6,
                "top_p": 0.9,
                "stream": True,
                "stream_options": {"include_usage": True}
            }
            
            logger.info(f"API streaming call started - Role: {role}")
            
            response = requests.post(
                self.api_url,
                headers=self.create_headers(),
                json=payload,
                stream=True,
                timeout=30
            )
            
            if response.status_code != 200:
                logger.error(f"API error: {response.status_code}")
                yield f"❌ API error ({response.status_code}): {response.text[:200]}"
                return
            
            buffer = ""
            for line in response.iter_lines():
                if line:
                    line = line.decode('utf-8')
                    if line.startswith("data: "):
                        data = line[6:]
                        if data == "[DONE]":
                            if buffer:
                                yield buffer
                            break
                        try:
                            chunk = json.loads(data)
                            if "choices" in chunk and chunk["choices"]:
                                content = chunk["choices"][0].get("delta", {}).get("content", "")
                                if content:
                                    buffer += content
                                    if len(buffer) > 50 or '\n' in buffer:
                                        yield buffer
                                        buffer = ""
                        except json.JSONDecodeError:
                            continue
            
            if buffer:
                yield buffer
                            
        except requests.exceptions.Timeout:
            yield "⏱️ API call timed out. Please try again."
        except requests.exceptions.ConnectionError:
            yield "πŸ”Œ Cannot connect to API server. Please check your internet connection."
        except Exception as e:
            logger.error(f"Error during streaming: {str(e)}")
            yield f"❌ Error occurred: {str(e)}"
    
    def get_system_prompts(self, language: str) -> Dict[str, str]:
        """Get system prompts based on language"""
        if language == "Korean":
            return {
                "director": "당신은 50νŽ˜μ΄μ§€ μ€‘νŽΈ μ†Œμ„€μ„ κΈ°νšν•˜κ³  κ°λ…ν•˜λŠ” λ¬Έν•™ κ°λ…μžμž…λ‹ˆλ‹€. 체계적이고 창의적인 μŠ€ν† λ¦¬ ꡬ쑰λ₯Ό λ§Œλ“€μ–΄λƒ…λ‹ˆλ‹€.",
                "critic": "당신은 λ‚ μΉ΄λ‘œμš΄ 톡찰λ ₯을 κ°€μ§„ λ¬Έν•™ λΉ„ν‰κ°€μž…λ‹ˆλ‹€. 건섀적이고 ꡬ체적인 ν”Όλ“œλ°±μ„ μ œκ³΅ν•©λ‹ˆλ‹€.",
                "writer1": "당신은 μ†Œμ„€μ˜ λ„μž…λΆ€λ₯Ό λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. λ…μžλ₯Ό μ‚¬λ‘œμž‘λŠ” μ‹œμž‘μ„ λ§Œλ“­λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”.",
                "writer2": "당신은 초반 μ „κ°œλ₯Ό λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. 인물과 상황을 깊이 있게 λ°œμ „μ‹œν‚΅λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”.",
                "writer3": "당신은 κ°ˆλ“± μƒμŠΉμ„ λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. κΈ΄μž₯감을 높이고 λ³΅μž‘μ„±μ„ λ”ν•©λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”.",
                "writer4": "당신은 μ€‘λ°˜λΆ€λ₯Ό λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. μ΄μ•ΌκΈ°μ˜ 쀑심좕을 κ²¬κ³ ν•˜κ²Œ λ§Œλ“­λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”.",
                "writer5": "당신은 μ „ν™˜μ μ„ λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. μ˜ˆμƒμΉ˜ λͺ»ν•œ λ³€ν™”λ₯Ό λ§Œλ“€μ–΄λƒ…λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”.",
                "writer6": "당신은 κ°ˆλ“± 심화λ₯Ό λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. μœ„κΈ°λ₯Ό κ·ΉλŒ€ν™”ν•©λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”.",
                "writer7": "당신은 클라이λ§₯슀 μ€€λΉ„λ₯Ό λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. 졜고쑰λ₯Ό ν–₯ν•΄ λ‚˜μ•„κ°‘λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”.",
                "writer8": "당신은 클라이λ§₯슀λ₯Ό λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. λͺ¨λ“  κ°ˆλ“±μ΄ ν­λ°œν•˜λŠ” μˆœκ°„μ„ κ·Έλ¦½λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”.",
                "writer9": "당신은 ν•΄κ²° 과정을 λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. 맀듭을 ν’€μ–΄λ‚˜κ°‘λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”.",
                "writer10": "당신은 결말을 λ‹΄λ‹Ήν•˜λŠ” μž‘κ°€μž…λ‹ˆλ‹€. μ—¬μš΄μ΄ λ‚¨λŠ” 마무리λ₯Ό λ§Œλ“­λ‹ˆλ‹€. λ°˜λ“œμ‹œ 2500-3000단어λ₯Ό μž‘μ„±ν•˜μ„Έμš”."
            }
        else:
            return {
                "director": "You are a literary director planning and supervising a 50-page novella. You create systematic and creative story structures.",
                "critic": "You are a literary critic with sharp insights. You provide constructive and specific feedback.",
                "writer1": "You are the writer responsible for the introduction. You create a captivating beginning. You MUST write 2500-3000 words.",
                "writer2": "You are the writer responsible for early development. You deepen characters and situations. You MUST write 2500-3000 words.",
                "writer3": "You are the writer responsible for rising conflict. You increase tension and add complexity. You MUST write 2500-3000 words.",
                "writer4": "You are the writer responsible for the middle section. You solidify the story's central axis. You MUST write 2500-3000 words.",
                "writer5": "You are the writer responsible for the turning point. You create unexpected changes. You MUST write 2500-3000 words.",
                "writer6": "You are the writer responsible for deepening conflict. You maximize the crisis. You MUST write 2500-3000 words.",
                "writer7": "You are the writer responsible for climax preparation. You move toward the peak. You MUST write 2500-3000 words.",
                "writer8": "You are the writer responsible for the climax. You depict the moment when all conflicts explode. You MUST write 2500-3000 words.",
                "writer9": "You are the writer responsible for the resolution process. You untangle the knots. You MUST write 2500-3000 words.",
                "writer10": "You are the writer responsible for the ending. You create a lingering conclusion. You MUST write 2500-3000 words."
            }
    
    def get_test_response(self, role: str, language: str) -> str:
        """Get test response based on role - ν…ŒμŠ€νŠΈμš© κΈ΄ 응닡"""
        if language == "Korean":
            return self.get_korean_test_response(role)
        else:
            return self.get_english_test_response(role)
    
    def get_korean_test_response(self, role: str) -> str:
        """Korean test responses with full content"""
        test_responses = {
            "director": """50νŽ˜μ΄μ§€ μ€‘νŽΈ μ†Œμ„€ κΈ°νšμ•ˆμ„ μ œμ‹œν•©λ‹ˆλ‹€.

## 1. μ£Όμ œμ™€ μž₯λ₯΄
- **핡심 주제**: 인간 λ³Έμ„±κ³Ό 기술의 좩돌 μ†μ—μ„œ μ°ΎλŠ” μ§„μ •ν•œ μ—°κ²°
- **μž₯λ₯΄**: SF 심리 λ“œλΌλ§ˆ
- **톀**: 성찰적이고 μ„œμ •μ μ΄λ©΄μ„œλ„ κΈ΄μž₯감 μžˆλŠ”
- **λͺ©ν‘œ λ…μž**: 깊이 μžˆλŠ” μ‚¬μœ λ₯Ό μ¦κΈ°λŠ” 성인 λ…μž

## 2. λ“±μž₯인물 μ„€μ •

| 이름 | μ—­ν•  | 성격 | λ°°κ²½ | 동기 | λ³€ν™” |
|------|------|------|------|------|------|
| μ„œμ—° | 주인곡 | 이성적, 고독함 | AI 연ꡬ원 | μ™„λ²½ν•œ AI λ™λ°˜μž 개발 | μΈκ°„κ΄€κ³„μ˜ κ°€μΉ˜ 재발견 |
| λ―Όμ€€ | μ‘°λ ₯자 | λ”°λœ»ν•¨, 직관적 | 심리상담사 | μ„œμ—°μ„ 도와 κ· ν˜• μ°ΎκΈ° | 기술 수용과 μ‘°ν™” |
| ARIA | λŒ€λ¦½μžβ†’λ™λ°˜μž | 논리적→감성 ν•™μŠ΅ | AI ν”„λ‘œν† νƒ€μž… | μ§„μ •ν•œ 쑴재 되기 | μžμ•„ 정체성 확립 |

## 3. μ„œμ‚¬ ꡬ쑰 (10개 파트)

| 파트 | νŽ˜μ΄μ§€ | μ£Όμš” 사건 | κΈ΄μž₯도 | 인물 λ°œμ „ |
|------|--------|-----------|---------|-----------|
| 1 | 1-5 | μ„œμ—°μ˜ κ³ λ…ν•œ 연ꡬ싀, ARIA 첫 각성 | 3/10 | μ„œμ—°μ˜ μ§‘μ°© λ“œλŸ¬λ‚¨ |
| 2 | 6-10 | ARIA의 이상 행동, λ―Όμ€€κ³Όμ˜ λ§Œλ‚¨ | 4/10 | κ°ˆλ“±μ˜ 씨앗 |
| 3 | 11-15 | ARIA의 μžμ•„ 인식 μ‹œμž‘ | 6/10 | μ„œμ—°μ˜ ν˜Όλž€ |
| 4 | 16-20 | μœ€λ¦¬μœ„μ›νšŒ μ••λ ₯ | 7/10 | μ„ νƒμ˜ 기둜 |
| 5 | 21-25 | ARIA의 νƒˆμΆœ μ‹œλ„ | 8/10 | κ΄€κ³„μ˜ μ „ν™˜μ  |
| 6 | 26-30 | μ„œμ—°κ³Ό ARIA의 λŒ€ν™” | 5/10 | μƒν˜Έ 이해 μ‹œμž‘ |
| 7 | 31-35 | μ™ΈλΆ€ μœ„ν˜‘ λ“±μž₯ | 9/10 | μ—°λŒ€μ˜ ν•„μš”μ„± |
| 8 | 36-40 | μ΅œν›„μ˜ 선택 | 10/10 | 클라이λ§₯슀 |
| 9 | 41-45 | μƒˆλ‘œμš΄ κΈΈ λͺ¨μƒ‰ | 6/10 | 화해와 수용 |
| 10 | 46-50 | 곡쑴의 μ‹œμž‘ | 4/10 | μƒˆλ‘œμš΄ 관계 정립 |""",
            
            "critic": """κ°λ…μžμ˜ κΈ°νšμ„ κ²€ν† ν–ˆμŠ΅λ‹ˆλ‹€.

## 비평 및 κ°œμ„  μ œμ•ˆ

### 1. μ„œμ‚¬μ  완성도
- **강점**: AI와 μΈκ°„μ˜ κ΄€κ³„λΌλŠ” μ‹œμ˜μ μ ˆν•œ 주제
- **κ°œμ„ μ **: 5-6파트 사이 κΈ΄μž₯도 급락이 우렀됨. μ™„κΈ‰ 쑰절 ν•„μš”

### 2. 인물 μ„€μ • κ²€ν† 

| 인물 | 강점 | 약점 | κ°œμ„  μ œμ•ˆ |
|------|------|------|-----------|
| μ„œμ—° | λͺ…ν™•ν•œ 내적 κ°ˆλ“± | 감정 ν‘œν˜„ λΆ€μ‘± 우렀 | μ΄ˆλ°˜λΆ€ν„° 감정적 λ‹¨μ„œ 배치 |
| λ―Όμ€€ | κ· ν˜•μž μ—­ν•  | μˆ˜λ™μ μΌ μœ„ν—˜ | λ…μžμ  μ„œλΈŒν”Œλ‘― ν•„μš” |
| ARIA | λ…νŠΉν•œ 캐릭터 아크 | λ³€ν™” κ³Όμ • 좔상적 | ꡬ체적 ν•™μŠ΅ μ—ν”Όμ†Œλ“œ μΆ”κ°€ |

### 3. μ‹€ν–‰ κ°€λŠ₯μ„±
- 각 μž‘κ°€λ³„ λͺ…ν™•ν•œ μ‹œμž‘/μ’…λ£Œ 지점 μ„€μ • ν•„μš”
- 특히 파트 5β†’6 μ „ν™˜λΆ€μ˜ 톀 λ³€ν™” κ°€μ΄λ“œλΌμΈ 보강
- ARIA의 'λͺ©μ†Œλ¦¬' 일관성 μœ μ§€ λ°©μ•ˆ ꡬ체화 ν•„μš”""",
        }
        
        # μž‘κ°€ 응닡 - κΈ΄ ν…ŒμŠ€νŠΈ ν…μŠ€νŠΈ (2500단어 이상)
        for i in range(1, 11):
            test_responses[f"writer{i}"] = f"""μž‘μ„±μž {i}번의 νŒŒνŠΈμž…λ‹ˆλ‹€.

""" + "ν…ŒμŠ€νŠΈ ν…μŠ€νŠΈμž…λ‹ˆλ‹€. " * 500  # 2500단어 μ΄μƒμ˜ κΈ΄ ν…μŠ€νŠΈ
            
        return test_responses.get(role, "ν…ŒμŠ€νŠΈ μ‘λ‹΅μž…λ‹ˆλ‹€.")
    
    def get_english_test_response(self, role: str) -> str:
        """English test responses with full content"""
        test_responses = {
            "director": """I present the 50-page novella plan.

## 1. Theme and Genre
- **Core Theme**: Finding true connection in the collision of human nature and technology
- **Genre**: Sci-fi psychological drama
- **Tone**: Reflective and lyrical yet tense
- **Target Audience**: Adult readers who enjoy deep contemplation

## 2. Character Settings

| Name | Role | Personality | Background | Motivation | Arc |
|------|------|-------------|------------|------------|-----|
| Seoyeon | Protagonist | Rational, lonely | AI researcher | Develop perfect AI companion | Rediscover value of human connection |
| Minjun | Helper | Warm, intuitive | Psychologist | Help Seoyeon find balance | Accept and harmonize with technology |
| ARIA | Antagonist→Companion | Logical→Learning emotion | AI prototype | Become truly existent | Establish self-identity |

## 3. Narrative Structure (10 parts)

| Part | Pages | Main Events | Tension | Character Development |
|------|-------|-------------|---------|---------------------|
| 1 | 1-5 | Seoyeon's lonely lab, ARIA's first awakening | 3/10 | Seoyeon's obsession revealed |
| 2 | 6-10 | ARIA's anomalies, meeting Minjun | 4/10 | Seeds of conflict |
| 3 | 11-15 | ARIA begins self-awareness | 6/10 | Seoyeon's confusion |
| 4 | 16-20 | Ethics committee pressure | 7/10 | Crossroads of choice |
| 5 | 21-25 | ARIA's escape attempt | 8/10 | Relationship turning point |
| 6 | 26-30 | Seoyeon and ARIA's dialogue | 5/10 | Beginning of mutual understanding |
| 7 | 31-35 | External threat emerges | 9/10 | Need for solidarity |
| 8 | 36-40 | Final choice | 10/10 | Climax |
| 9 | 41-45 | Seeking new paths | 6/10 | Reconciliation and acceptance |
| 10 | 46-50 | Beginning of coexistence | 4/10 | Establishing new relationship |""",
            
            "critic": """I have reviewed the director's plan.

## Critique and Improvement Suggestions

### 1. Narrative Completeness
- **Strength**: Timely theme of AI-human relationships
- **Improvement**: Concerned about tension drop between parts 5-6. Need better pacing control

### 2. Character Review

| Character | Strengths | Weaknesses | Suggestions |
|-----------|-----------|------------|-------------|
| Seoyeon | Clear internal conflict | Risk of insufficient emotion | Place emotional cues from beginning |
| Minjun | Balancer role | Risk of being passive | Needs independent subplot |
| ARIA | Unique character arc | Abstract transformation | Add concrete learning episodes |

### 3. Feasibility
- Need clear start/end points for each writer
- Especially need reinforced guidelines for tone change in part 5β†’6 transition
- Need to concretize ARIA's 'voice' consistency maintenance""",
        }
        
        # Writer responses - long test text (2500+ words)
        for i in range(1, 11):
            test_responses[f"writer{i}"] = f"""Writer {i} begins their section here.

""" + "This is test text. " * 500  # 2500+ words of long text
            
        return test_responses.get(role, "Test response.")
    
    def process_novel_stream(self, query: str, language: str = "English", 
                           session_id: Optional[str] = None, 
                           resume_from_stage: int = 0) -> Generator[Tuple[str, List[Dict[str, str]]], None, None]:
        """Process novel writing with streaming updates"""
        try:
            global conversation_history
            
            # Create or resume session
            if session_id:
                self.current_session_id = session_id
                session = NovelDatabase.get_session(session_id)
                if session:
                    query = session['user_query']
                    language = session['language']
                    resume_from_stage = session['current_stage'] + 1
            else:
                self.current_session_id = NovelDatabase.create_session(query, language)
                resume_from_stage = 0
            
            logger.info(f"Processing novel for session {self.current_session_id}, starting from stage {resume_from_stage}")
            
            # Initialize conversation
            conversation_history = [{
                "role": "human",
                "content": query,
                "timestamp": datetime.now()
            }]
            
            # Load existing stages if resuming
            stages = []
            if resume_from_stage > 0:
                existing_stages = NovelDatabase.get_stages(self.current_session_id)
                for stage_data in existing_stages:
                    stages.append({
                        "name": stage_data['stage_name'],
                        "status": stage_data['status'],
                        "content": stage_data['content'] or ""
                    })
            
            # Define all stages
            stage_definitions = [
                ("director", f"🎬 {'κ°λ…μž: 초기 기획' if language == 'Korean' else 'Director: Initial Planning'}"),
                ("critic", f"πŸ“ {'비평가: 기획 κ²€ν† ' if language == 'Korean' else 'Critic: Plan Review'}"),
                ("director", f"🎬 {'κ°λ…μž: μˆ˜μ •λœ λ§ˆμŠ€ν„°ν”Œλžœ' if language == 'Korean' else 'Director: Revised Masterplan'}"),
            ]
            
            # Add writer stages
            for writer_num in range(1, 11):
                stage_definitions.extend([
                    (f"writer{writer_num}", f"✍️ {'μž‘μ„±μž' if language == 'Korean' else 'Writer'} {writer_num}: {'μ΄ˆμ•ˆ' if language == 'Korean' else 'Draft'}"),
                    ("critic", f"πŸ“ {'비평가: μž‘μ„±μž' if language == 'Korean' else 'Critic: Writer'} {writer_num} {'κ²€ν† ' if language == 'Korean' else 'Review'}"),
                    (f"writer{writer_num}", f"✍️ {'μž‘μ„±μž' if language == 'Korean' else 'Writer'} {writer_num}: {'μˆ˜μ •λ³Έ' if language == 'Korean' else 'Revision'}")
                ])
            
            stage_definitions.extend([
                ("critic", f"πŸ“ {'비평가: μ΅œμ’… 평가' if language == 'Korean' else 'Critic: Final Evaluation'}"),
                ("director", f"🎬 {'κ°λ…μž: μ΅œμ’… μ™„μ„±λ³Έ' if language == 'Korean' else 'Director: Final Version'}")
            ])
            
            # Process stages starting from resume point
            for stage_idx in range(resume_from_stage, len(stage_definitions)):
                role, stage_name = stage_definitions[stage_idx]
                
                # Add stage if not already present
                if stage_idx >= len(stages):
                    stages.append({
                        "name": stage_name,
                        "status": "active",
                        "content": ""
                    })
                else:
                    stages[stage_idx]["status"] = "active"
                
                yield "", stages
                
                # Get appropriate prompt based on stage
                prompt = self.get_stage_prompt(stage_idx, role, query, language, stages)
                
                stage_content = ""
                
                # Stream content generation
                for chunk in self.call_llm_streaming(
                    [{"role": "user", "content": prompt}],
                    role,
                    language
                ):
                    stage_content += chunk
                    stages[stage_idx]["content"] = stage_content
                    yield "", stages
                
                # Mark stage complete and save to DB
                stages[stage_idx]["status"] = "complete"
                NovelDatabase.save_stage(
                    self.current_session_id,
                    stage_idx,
                    stage_name,
                    role,
                    stage_content,
                    "complete"
                )
                
                yield "", stages
            
            # Get final novel from last stage
            final_novel = stages[-1]["content"] if stages else ""
            
            # Save final novel to DB
            NovelDatabase.update_final_novel(self.current_session_id, final_novel)
            
            # Final yield
            yield final_novel, stages
            
        except Exception as e:
            logger.error(f"Error in process_novel_stream: {str(e)}")
            
            # Save error state to DB
            if self.current_session_id:
                NovelDatabase.save_stage(
                    self.current_session_id,
                    stage_idx if 'stage_idx' in locals() else 0,
                    "Error",
                    "error",
                    str(e),
                    "error"
                )
            
            error_stage = {
                "name": "❌ Error",
                "status": "error",
                "content": str(e)
            }
            stages.append(error_stage)
            yield f"Error occurred: {str(e)}", stages
    
    def get_stage_prompt(self, stage_idx: int, role: str, query: str, 
                        language: str, stages: List[Dict]) -> str:
        """Get appropriate prompt for each stage"""
        # Stage 0: Director Initial
        if stage_idx == 0:
            return self.create_director_initial_prompt(query, language)
        
        # Stage 1: Critic reviews Director's plan
        elif stage_idx == 1:
            return self.create_critic_director_prompt(stages[0]["content"], language)
        
        # Stage 2: Director revision
        elif stage_idx == 2:
            return self.create_director_revision_prompt(
                stages[0]["content"], stages[1]["content"], language)
        
        # Writer stages
        elif role.startswith("writer"):
            writer_num = int(role.replace("writer", ""))
            final_plan = stages[2]["content"]  # Director's final plan
            
            # Initial draft or revision?
            if "μ΄ˆμ•ˆ" in stages[stage_idx]["name"] or "Draft" in stages[stage_idx]["name"]:
                # Get accumulated content from DB
                accumulated_content = NovelDatabase.get_all_writer_content(self.current_session_id)
                return self.create_writer_prompt(writer_num, final_plan, accumulated_content, language)
            else:  # Revision
                # Find the initial draft and critic feedback
                initial_draft_idx = stage_idx - 2
                critic_feedback_idx = stage_idx - 1
                return self.create_writer_revision_prompt(
                    writer_num, 
                    stages[initial_draft_idx]["content"],
                    stages[critic_feedback_idx]["content"],
                    language
                )
        
        # Critic stages
        elif role == "critic":
            final_plan = stages[2]["content"]
            
            # Final evaluation
            if "μ΅œμ’…" in stages[stage_idx]["name"] or "Final" in stages[stage_idx]["name"]:
                # Get all writer content from DB
                all_writer_content = NovelDatabase.get_all_writer_content(self.current_session_id)
                logger.info(f"Final evaluation with {len(all_writer_content)} characters of content")
                return self.create_critic_final_prompt(all_writer_content, final_plan, language)
            
            # Writer review
            else:
                # Find which writer we're reviewing
                for i in range(1, 11):
                    if f"μž‘μ„±μž {i}" in stages[stage_idx]["name"] or f"Writer {i}" in stages[stage_idx]["name"]:
                        writer_content_idx = stage_idx - 1
                        # Get previous writers' content from DB
                        previous_content = NovelDatabase.get_all_writer_content(self.current_session_id)
                        return self.create_critic_writer_prompt(
                            i,
                            stages[writer_content_idx]["content"],
                            final_plan,
                            previous_content,
                            language
                        )
        
        # Director final - DBμ—μ„œ λͺ¨λ“  μž‘κ°€ λ‚΄μš© κ°€μ Έμ˜€κΈ°
        elif stage_idx == len(stage_definitions) - 1:
            critic_final_idx = stage_idx - 1
            all_writer_content = NovelDatabase.get_all_writer_content(self.current_session_id)
            logger.info(f"Final director compilation with {len(all_writer_content)} characters of content")
            return self.create_director_final_prompt(
                all_writer_content,
                stages[critic_final_idx]["content"],
                language
            )
        
        return ""

# Gradio Interface Functions
def process_query(query: str, language: str, session_id: str = None) -> Generator[Tuple[str, str, str], None, None]:
    """Process query and yield updates"""
    if not query.strip() and not session_id:
        if language == "Korean":
            yield "", "", "❌ μ†Œμ„€ 주제λ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”."
        else:
            yield "", "", "❌ Please enter a novel theme."
        return
    
    system = NovelWritingSystem()
    
    try:
        for final_novel, stages in system.process_novel_stream(query, language, session_id):
            # Format stages for display
            stages_display = format_stages_display(stages, language)
            
            status = "πŸ”„ Processing..." if not final_novel else "βœ… Complete!"
            
            yield stages_display, final_novel, status
                    
    except Exception as e:
        logger.error(f"Error in process_query: {str(e)}")
        if language == "Korean":
            yield "", "", f"❌ 였λ₯˜ λ°œμƒ: {str(e)}"
        else:
            yield "", "", f"❌ Error occurred: {str(e)}"

def format_stages_display(stages: List[Dict[str, str]], language: str) -> str:
    """Format stages into simple display without complex scrolling"""
    display = ""
    
    for idx, stage in enumerate(stages):
        status_icon = "βœ…" if stage.get("status") == "complete" else ("⏳" if stage.get("status") == "active" else "❌")
        
        # Show only active stage content in detail, others just show status
        if stage.get("status") == "active":
            display += f"\n\n{status_icon} **{stage['name']}**\n"
            display += f"```\n{stage.get('content', '')[-1000:]}\n```"  # Show last 1000 chars
        else:
            display += f"\n{status_icon} {stage['name']}"
    
    return display

def get_active_sessions(language: str) -> List[Tuple[str, str]]:
    """Get list of active sessions"""
    try:
        sessions = NovelDatabase.get_active_sessions()
        
        choices = []
        for session in sessions:
            created = datetime.fromisoformat(session['created_at'])
            date_str = created.strftime("%Y-%m-%d %H:%M")
            query_preview = session['user_query'][:50] + "..." if len(session['user_query']) > 50 else session['user_query']
            label = f"[{date_str}] {query_preview} (Stage {session['current_stage']})"
            choices.append((label, session['session_id']))
        
        return choices
    except Exception as e:
        logger.error(f"Error getting active sessions: {str(e)}")
        return []

def resume_session(session_id: str, language: str) -> Generator[Tuple[str, str, str], None, None]:
    """Resume an existing session"""
    if not session_id:
        return
    
    # Process with existing session ID
    yield from process_query("", language, session_id)

def download_novel(novel_text: str, format: str, language: str) -> str:
    """Download novel in specified format"""
    if not novel_text:
        return None
    
    # νŽ˜μ΄μ§€ 마크 제거
    novel_text = re.sub(r'\[(?:νŽ˜μ΄μ§€|Page|page)\s*\d+\]', '', novel_text)
    novel_text = re.sub(r'(?:νŽ˜μ΄μ§€|Page)\s*\d+:', '', novel_text)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    
    if format == "DOCX" and DOCX_AVAILABLE:
        # Create DOCX
        doc = Document()
        
        # Parse and add content
        lines = novel_text.split('\n')
        for line in lines:
            if line.startswith('#'):
                level = len(line.split()[0])
                text = line.lstrip('#').strip()
                doc.add_heading(text, level)
            elif line.strip():
                doc.add_paragraph(line)
        
        # Save
        temp_dir = tempfile.gettempdir()
        filename = f"Novel_{timestamp}.docx"
        filepath = os.path.join(temp_dir, filename)
        doc.save(filepath)
        
        return filepath
    else:
        # TXT format
        temp_dir = tempfile.gettempdir()
        filename = f"Novel_{timestamp}.txt"
        filepath = os.path.join(temp_dir, filename)
        
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(novel_text)
        
        return filepath

# Custom CSS
custom_css = """
.gradio-container {
    background: linear-gradient(135deg, #1e3c72, #2a5298);
    min-height: 100vh;
}

.main-header {
    background-color: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    padding: 30px;
    border-radius: 12px;
    margin-bottom: 30px;
    text-align: center;
    color: white;
}

.input-section {
    background-color: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    padding: 20px;
    border-radius: 12px;
    margin-bottom: 20px;
}

.session-section {
    background-color: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    padding: 15px;
    border-radius: 8px;
    margin-top: 20px;
    color: white;
}

#stages-display {
    background-color: rgba(255, 255, 255, 0.95);
    padding: 20px;
    border-radius: 12px;
    max-height: 600px;
    overflow-y: auto;
}

#novel-output {
    background-color: rgba(255, 255, 255, 0.95);
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    max-height: 800px;
    overflow-y: auto;
}

.download-section {
    background-color: rgba(255, 255, 255, 0.9);
    padding: 15px;
    border-radius: 8px;
    margin-top: 20px;
}
"""

# Create Gradio Interface
def create_interface():
    with gr.Blocks(css=custom_css, title="SOMA Novel Writing System") as interface:
        gr.HTML("""
        <div class="main-header">
            <h1 style="font-size: 2.5em; margin-bottom: 10px;">
                πŸ“š SOMA Novel Writing System
            </h1>
            <h3 style="color: #ccc; margin-bottom: 20px;">
                AI Collaborative Novel Generation - 50 Page Novella Creator
            </h3>
            <p style="font-size: 1.1em; color: #ddd; max-width: 800px; margin: 0 auto;">
                Enter a theme or prompt, and watch as 13 AI agents collaborate to create a complete 50-page novella.
                The system includes 1 Director, 1 Critic, and 10 Writers working in harmony.
                All progress is automatically saved and can be resumed anytime.
            </p>
        </div>
        """)
        
        # State management
        current_session_id = gr.State(None)
        
        with gr.Row():
            with gr.Column(scale=1):
                with gr.Group(elem_classes=["input-section"]):
                    query_input = gr.Textbox(
                        label="Novel Theme / μ†Œμ„€ 주제",
                        placeholder="Enter your novel theme or initial idea...\nμ†Œμ„€μ˜ μ£Όμ œλ‚˜ 초기 아이디어λ₯Ό μž…λ ₯ν•˜μ„Έμš”...",
                        lines=4
                    )
                    
                    language_select = gr.Radio(
                        choices=["English", "Korean"],
                        value="English",
                        label="Language / μ–Έμ–΄"
                    )
                    
                    with gr.Row():
                        submit_btn = gr.Button("πŸš€ Start Writing / μž‘μ„± μ‹œμž‘", variant="primary", scale=2)
                        clear_btn = gr.Button("πŸ—‘οΈ Clear / μ΄ˆκΈ°ν™”", scale=1)
                    
                    status_text = gr.Textbox(
                        label="Status",
                        interactive=False,
                        value="πŸ”„ Ready"
                    )
                    
                    # Session management
                    with gr.Group(elem_classes=["session-section"]):
                        gr.Markdown("### πŸ’Ύ Resume Previous Session / 이전 μ„Έμ…˜ 재개")
                        session_dropdown = gr.Dropdown(
                            label="Select Session / μ„Έμ…˜ 선택",
                            choices=[],
                            interactive=True
                        )
                        with gr.Row():
                            refresh_btn = gr.Button("πŸ”„ Refresh / μƒˆλ‘œκ³ μΉ¨", scale=1)
                            resume_btn = gr.Button("▢️ Resume / 재개", variant="secondary", scale=1)
        
        with gr.Column(scale=2):
            with gr.Tab("πŸ“ Writing Process / μž‘μ„± κ³Όμ •"):
                stages_display = gr.Markdown(
                    value="Process will appear here...",
                    elem_id="stages-display"
                )
            
            with gr.Tab("πŸ“– Final Novel / μ΅œμ’… μ†Œμ„€"):
                novel_output = gr.Markdown(
                    value="",
                    elem_id="novel-output"
                )
                
                with gr.Group(elem_classes=["download-section"]):
                    gr.Markdown("### πŸ“₯ Download Novel / μ†Œμ„€ λ‹€μš΄λ‘œλ“œ")
                    with gr.Row():
                        format_select = gr.Radio(
                            choices=["DOCX", "TXT"],
                            value="DOCX" if DOCX_AVAILABLE else "TXT",
                            label="Format / ν˜•μ‹"
                        )
                        download_btn = gr.Button("⬇️ Download / λ‹€μš΄λ‘œλ“œ", variant="secondary")
                    
                    download_file = gr.File(
                        label="Downloaded File / λ‹€μš΄λ‘œλ“œλœ 파일",
                        visible=False
                    )
        
        # Hidden state for novel text
        novel_text_state = gr.State("")
        
        # Examples
        with gr.Row():
            gr.Examples(
                examples=[
                    ["A scientist discovers a portal to parallel universes but each journey erases a memory"],
                    ["In a world where dreams can be traded, a dream thief must steal the emperor's nightmare"],
                    ["Two AI entities fall in love while trying to prevent a global cyber war"],
                    ["미래 λ„μ‹œμ—μ„œ 기얡을 κ±°λž˜ν•˜λŠ” 상인과 λͺ¨λ“  기얡을 μžƒμ€ νƒμ •μ˜ 이야기"],
                    ["μ‹œκ°„μ΄ 거꾸둜 흐λ₯΄λŠ” λ§ˆμ„μ—μ„œ μΌμ–΄λ‚˜λŠ” λ―ΈμŠ€ν„°λ¦¬ν•œ 살인 사건"],
                    ["μ±… μ†μœΌλ‘œ λ“€μ–΄κ°ˆ 수 μžˆλŠ” λŠ₯λ ₯을 κ°€μ§„ μ‚¬μ„œμ˜ λͺ¨ν—˜"]
                ],
                inputs=query_input,
                label="πŸ’‘ Example Themes / 예제 주제"
            )
        
        # Event handlers
        def update_novel_state(stages, novel, status):
            return stages, novel, status, novel
        
        def refresh_sessions():
            try:
                sessions = get_active_sessions("English")
                return gr.update(choices=sessions)
            except Exception as e:
                logger.error(f"Error refreshing sessions: {str(e)}")
                return gr.update(choices=[])
        
        submit_btn.click(
            fn=process_query,
            inputs=[query_input, language_select, current_session_id],
            outputs=[stages_display, novel_output, status_text]
        ).then(
            fn=update_novel_state,
            inputs=[stages_display, novel_output, status_text],
            outputs=[stages_display, novel_output, status_text, novel_text_state]
        )
        
        resume_btn.click(
            fn=lambda x: x,
            inputs=[session_dropdown],
            outputs=[current_session_id]
        ).then(
            fn=resume_session,
            inputs=[current_session_id, language_select],
            outputs=[stages_display, novel_output, status_text]
        )
        
        refresh_btn.click(
            fn=refresh_sessions,
            outputs=[session_dropdown]
        )
        
        clear_btn.click(
            fn=lambda: ("", "", "πŸ”„ Ready", "", None),
            outputs=[stages_display, novel_output, status_text, novel_text_state, current_session_id]
        )
        
        def handle_download(novel_text, format_type, language):
            if not novel_text:
                return gr.update(visible=False)
            
            file_path = download_novel(novel_text, format_type, language)
            if file_path:
                return gr.update(value=file_path, visible=True)
            else:
                return gr.update(visible=False)
        
        download_btn.click(
            fn=handle_download,
            inputs=[novel_text_state, format_select, language_select],
            outputs=[download_file]
        )
        
        # Load sessions on startup
        interface.load(
            fn=refresh_sessions,
            outputs=[session_dropdown]
        )
    
    return interface

# Main execution
if __name__ == "__main__":
    logger.info("Starting SOMA Novel Writing System...")
    
    # Initialize database on startup
    logger.info("Initializing database...")
    NovelDatabase.init_db()
    logger.info("Database initialized successfully.")
    
    interface = create_interface()
    
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=True
    )