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

# --- λ‘œκΉ… μ„€μ • ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
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
    from docx.oxml.ns import qn
    from docx.oxml import OxmlElement
    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", "")
BRAVE_SEARCH_API_KEY = os.getenv("BRAVE_SEARCH_API_KEY", "")
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
MODEL_ID = "dep89a2fld32mcm"
DB_PATH = "novel_sessions_v5.db"

# λͺ©ν‘œ λΆ„λŸ‰ μ„€μ •
TARGET_WORDS = 8000  # μ•ˆμ „ λ§ˆμ§„μ„ μœ„ν•΄ 8000단어
MIN_WORDS_PER_WRITER = 800  # 각 μž‘κ°€ μ΅œμ†Œ λΆ„λŸ‰

# --- ν™˜κ²½ λ³€μˆ˜ 검증 ---
if not FRIENDLI_TOKEN:
    logger.error("FRIENDLI_TOKEN not set. Application will not work properly.")
    FRIENDLI_TOKEN = "dummy_token_for_testing"

if not BRAVE_SEARCH_API_KEY:
    logger.warning("BRAVE_SEARCH_API_KEY not set. Web search features will be disabled.")

# --- μ „μ—­ λ³€μˆ˜ ---
db_lock = threading.Lock()

# μ„œμ‚¬ μ§„ν–‰ 단계 μ •μ˜
NARRATIVE_PHASES = [
    "λ„μž…: 일상과 κ· μ—΄",
    "λ°œμ „ 1: λΆˆμ•ˆμ˜ κ³ μ‘°",
    "λ°œμ „ 2: μ™ΈλΆ€ 좩격",
    "λ°œμ „ 3: 내적 κ°ˆλ“± 심화",
    "μ ˆμ • 1: μœ„κΈ°μ˜ 정점",
    "μ ˆμ • 2: μ„ νƒμ˜ μˆœκ°„",
    "ν•˜κ°• 1: 결과와 μ—¬νŒŒ",
    "ν•˜κ°• 2: μƒˆλ‘œμš΄ 인식",
    "결말 1: λ³€ν™”λœ 일상",
    "결말 2: μ—΄λ¦° 질문"
]

# 단계별 ꡬ성
PROGRESSIVE_STAGES = [
    ("director", "🎬 κ°λ…μž: ν†΅ν•©λœ μ„œμ‚¬ ꡬ쑰 기획"),
    ("critic", "πŸ“ 비평가: μ„œμ‚¬ μ§„ν–‰μ„±κ³Ό 깊이 κ²€ν† "),
    ("director", "🎬 κ°λ…μž: μˆ˜μ •λœ λ§ˆμŠ€ν„°ν”Œλžœ"),
] + [
    (f"writer{i}", f"✍️ μž‘κ°€ {i}: μ΄ˆμ•ˆ - {NARRATIVE_PHASES[i-1]}")
    for i in range(1, 11)
] + [
    ("critic", "πŸ“ 비평가: 쀑간 κ²€ν†  (μ„œμ‚¬ λˆ„μ μ„±κ³Ό λ³€ν™”)"),
] + [
    (f"writer{i}", f"✍️ μž‘κ°€ {i}: μˆ˜μ •λ³Έ - {NARRATIVE_PHASES[i-1]}")
    for i in range(1, 11)
] + [
    ("critic", f"πŸ“ 비평가: μ΅œμ’… κ²€ν†  및 문학적 평가"),
]


# --- 데이터 클래슀 ---
@dataclass
class CharacterArc:
    """인물의 λ³€ν™” ꢀ적 좔적"""
    name: str
    initial_state: Dict[str, Any]  # 초기 μƒνƒœ
    phase_states: Dict[int, Dict[str, Any]] = field(default_factory=dict)  # 단계별 μƒνƒœ
    transformations: List[str] = field(default_factory=list)  # μ£Όμš” λ³€ν™”λ“€
    relationships_evolution: Dict[str, List[str]] = field(default_factory=dict)  # 관계 λ³€ν™”

@dataclass
class PlotThread:
    """ν”Œλ‘― 라인 좔적"""
    thread_id: str
    description: str
    introduction_phase: int
    development_phases: List[int]
    resolution_phase: Optional[int]
    status: str = "active"  # active, resolved, suspended

@dataclass
class SymbolicEvolution:
    """μƒμ§•μ˜ 의미 λ³€ν™” 좔적"""
    symbol: str
    initial_meaning: str
    phase_meanings: Dict[int, str] = field(default_factory=dict)
    transformation_complete: bool = False


# --- 핡심 둜직 클래슀 ---
class ProgressiveNarrativeTracker:
    """μ„œμ‚¬ μ§„ν–‰κ³Ό λˆ„μ μ„ μΆ”μ ν•˜λŠ” μ‹œμŠ€ν…œ"""
    def __init__(self):
        self.character_arcs: Dict[str, CharacterArc] = {}
        self.plot_threads: Dict[str, PlotThread] = {}
        self.symbolic_evolutions: Dict[str, SymbolicEvolution] = {}
        self.phase_summaries: Dict[int, str] = {}
        self.accumulated_events: List[Dict[str, Any]] = []
        self.thematic_deepening: List[str] = []
        
    def register_character_arc(self, name: str, initial_state: Dict[str, Any]):
        """캐릭터 아크 등둝"""
        self.character_arcs[name] = CharacterArc(name=name, initial_state=initial_state)
        logger.info(f"Character arc registered: {name}")
        
    def update_character_state(self, name: str, phase: int, new_state: Dict[str, Any], transformation: str):
        """캐릭터 μƒνƒœ μ—…λ°μ΄νŠΈ 및 λ³€ν™” 기둝"""
        if name in self.character_arcs:
            arc = self.character_arcs[name]
            arc.phase_states[phase] = new_state
            arc.transformations.append(f"Phase {phase}: {transformation}")
            logger.info(f"Character {name} transformed in phase {phase}: {transformation}")
            
    def add_plot_thread(self, thread_id: str, description: str, intro_phase: int):
        """μƒˆλ‘œμš΄ ν”Œλ‘― 라인 μΆ”κ°€"""
        self.plot_threads[thread_id] = PlotThread(
            thread_id=thread_id,
            description=description,
            introduction_phase=intro_phase,
            development_phases=[]
        )
        
    def develop_plot_thread(self, thread_id: str, phase: int):
        """ν”Œλ‘― 라인 λ°œμ „"""
        if thread_id in self.plot_threads:
            self.plot_threads[thread_id].development_phases.append(phase)
            
    def check_narrative_progression(self, current_phase: int) -> Tuple[bool, List[str]]:
        """μ„œμ‚¬κ°€ μ‹€μ œλ‘œ μ§„ν–‰λ˜κ³  μžˆλŠ”μ§€ 확인"""
        issues = []
        
        # 1. 캐릭터 λ³€ν™” 확인
        static_characters = []
        for name, arc in self.character_arcs.items():
            if len(arc.transformations) < current_phase // 3:  # μ΅œμ†Œ 3λ‹¨κ³„λ§ˆλ‹€ λ³€ν™” ν•„μš”
                static_characters.append(name)
        
        if static_characters:
            issues.append(f"λ‹€μŒ μΈλ¬Όλ“€μ˜ λ³€ν™”κ°€ λΆ€μ‘±ν•©λ‹ˆλ‹€: {', '.join(static_characters)}")
            
        # 2. ν”Œλ‘― μ§„ν–‰ 확인
        unresolved_threads = []
        for thread_id, thread in self.plot_threads.items():
            if thread.status == "active" and len(thread.development_phases) < 2:
                unresolved_threads.append(thread.description)
                
        if unresolved_threads:
            issues.append(f"μ§„μ „λ˜μ§€ μ•Šμ€ ν”Œλ‘―: {', '.join(unresolved_threads)}")
            
        # 3. 상징 λ°œμ „ 확인
        static_symbols = []
        for symbol, evolution in self.symbolic_evolutions.items():
            if len(evolution.phase_meanings) < current_phase // 4:
                static_symbols.append(symbol)
                
        if static_symbols:
            issues.append(f"μ˜λ―Έκ°€ λ°œμ „ν•˜μ§€ μ•Šμ€ 상징: {', '.join(static_symbols)}")
            
        return len(issues) == 0, issues
        
    def generate_phase_requirements(self, phase: int) -> str:
        """각 단계별 ν•„μˆ˜ μš”κ΅¬μ‚¬ν•­ 생성"""
        requirements = []
        
        # 이전 단계 μš”μ•½
        if phase > 1 and (phase-1) in self.phase_summaries:
            requirements.append(f"이전 단계 핡심: {self.phase_summaries[phase-1]}")
            
        # 단계별 특수 μš”κ΅¬μ‚¬ν•­
        phase_name = NARRATIVE_PHASES[phase-1] if phase <= 10 else "μˆ˜μ •"
        
        if "λ„μž…" in phase_name:
            requirements.append("- μΌμƒμ˜ 균열을 λ³΄μ—¬μ£Όλ˜, 큰 사건이 μ•„λ‹Œ λ―Έλ¬˜ν•œ λ³€ν™”λ‘œ μ‹œμž‘")
            requirements.append("- μ£Όμš” μΈλ¬Όλ“€μ˜ 초기 μƒνƒœμ™€ 관계 μ„€μ •")
            requirements.append("- 핡심 상징 λ„μž… (μžμ—°μŠ€λŸ½κ²Œ)")
            
        elif "λ°œμ „" in phase_name:
            requirements.append("- 이전 λ‹¨κ³„μ˜ κ· μ—΄/κ°ˆλ“±μ΄ κ΅¬μ²΄ν™”λ˜κ³  심화")
            requirements.append("- μƒˆλ‘œμš΄ μ‚¬κ±΄μ΄λ‚˜ 인식이 μΆ”κ°€λ˜μ–΄ λ³΅μž‘μ„± 증가")
            requirements.append("- 인물 κ°„ κ΄€κ³„μ˜ λ―Έλ¬˜ν•œ λ³€ν™”")
            
        elif "μ ˆμ •" in phase_name:
            requirements.append("- μΆ•μ λœ κ°ˆλ“±μ΄ μž„κ³„μ μ— 도달")
            requirements.append("- 인물의 내적 μ„ νƒμ΄λ‚˜ μΈμ‹μ˜ μ „ν™˜μ ")
            requirements.append("- μƒμ§•μ˜ μ˜λ―Έκ°€ μ „λ³΅λ˜κ±°λ‚˜ 심화")
            
        elif "ν•˜κ°•" in phase_name:
            requirements.append("- μ ˆμ •μ˜ μ—¬νŒŒμ™€ 그둜 μΈν•œ λ³€ν™”")
            requirements.append("- μƒˆλ‘œμš΄ κ· ν˜•μ μ„ μ°Ύμ•„κ°€λŠ” κ³Όμ •")
            requirements.append("- μΈλ¬Όλ“€μ˜ λ³€ν™”λœ 관계와 인식")
            
        elif "결말" in phase_name:
            requirements.append("- λ³€ν™”λœ μΌμƒμ˜ λͺ¨μŠ΅")
            requirements.append("- ν•΄κ²°λ˜μ§€ μ•Šμ€ μ§ˆλ¬Έλ“€")
            requirements.append("- μ—¬μš΄κ³Ό μ„±μ°°μ˜ μ—¬μ§€")
            
        # 반볡 λ°©μ§€ μš”κ΅¬μ‚¬ν•­
        requirements.append("\n⚠️ μ ˆλŒ€ κΈˆμ§€μ‚¬ν•­:")
        requirements.append("- 이전 단계와 λ™μΌν•œ μ‚¬κ±΄μ΄λ‚˜ κ°ˆλ“± 반볡")
        requirements.append("- 인물이 같은 μƒκ°μ΄λ‚˜ 감정에 머무λ₯΄κΈ°")
        requirements.append("- ν”Œλ‘―μ΄ μ œμžλ¦¬κ±ΈμŒν•˜κΈ°")
        
        return "\n".join(requirements)


class NovelDatabase:
    """λ°μ΄ν„°λ² μ΄μŠ€ 관리"""
    @staticmethod
    def init_db():
        with sqlite3.connect(DB_PATH) as conn:
            conn.execute("PRAGMA journal_mode=WAL")
            cursor = conn.cursor()
            
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS sessions (
                    session_id TEXT PRIMARY KEY,
                    user_query TEXT NOT NULL,
                    language TEXT NOT NULL,
                    created_at TEXT DEFAULT (datetime('now')),
                    updated_at TEXT DEFAULT (datetime('now')),
                    status TEXT DEFAULT 'active',
                    current_stage INTEGER DEFAULT 0,
                    final_novel TEXT,
                    literary_report TEXT,
                    total_words INTEGER DEFAULT 0,
                    narrative_tracker TEXT
                )
            ''')
            
            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,
                    word_count INTEGER DEFAULT 0,
                    status TEXT DEFAULT 'pending',
                    progression_score REAL DEFAULT 0.0,
                    created_at TEXT DEFAULT (datetime('now')),
                    updated_at TEXT DEFAULT (datetime('now')),
                    FOREIGN KEY (session_id) REFERENCES sessions(session_id),
                    UNIQUE(session_id, stage_number)
                )
            ''')
            
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS plot_threads (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    session_id TEXT NOT NULL,
                    thread_id TEXT NOT NULL,
                    description TEXT,
                    introduction_phase INTEGER,
                    status TEXT DEFAULT 'active',
                    created_at TEXT DEFAULT (datetime('now')),
                    FOREIGN KEY (session_id) REFERENCES sessions(session_id)
                )
            ''')
            
            conn.commit()

    # κΈ°μ‘΄ λ©”μ„œλ“œλ“€ μœ μ§€
    @staticmethod
    @contextmanager
    def get_db():
        with db_lock:
            conn = sqlite3.connect(DB_PATH, timeout=30.0)
            conn.row_factory = sqlite3.Row
            try:
                yield conn
            finally:
                conn.close()

    @staticmethod
    def create_session(user_query: str, language: str) -> str:
        session_id = hashlib.md5(f"{user_query}{datetime.now()}".encode()).hexdigest()
        with NovelDatabase.get_db() as conn:
            conn.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',
                   progression_score: float = 0.0):
        word_count = len(content.split()) if content else 0
        with NovelDatabase.get_db() as conn:
            cursor = conn.cursor()
            cursor.execute('''
                INSERT INTO stages (session_id, stage_number, stage_name, role, content, word_count, status, progression_score)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ON CONFLICT(session_id, stage_number)
                DO UPDATE SET content=?, word_count=?, status=?, stage_name=?, progression_score=?, updated_at=datetime('now')
            ''', (session_id, stage_number, stage_name, role, content, word_count, status, progression_score,
                  content, word_count, status, stage_name, progression_score))
            
            # 총 단어 수 μ—…λ°μ΄νŠΈ
            cursor.execute('''
                UPDATE sessions 
                SET total_words = (
                    SELECT SUM(word_count) 
                    FROM stages 
                    WHERE session_id = ? AND role LIKE 'writer%' AND content IS NOT NULL
                ),
                updated_at = datetime('now'),
                current_stage = ?
                WHERE session_id = ?
            ''', (session_id, stage_number, session_id))
            
            conn.commit()

    @staticmethod
    def get_writer_content(session_id: str) -> str:
        """μž‘κ°€ μ½˜ν…μΈ  κ°€μ Έμ˜€κΈ° (μˆ˜μ •λ³Έ μš°μ„ )"""
        with NovelDatabase.get_db() as conn:
            all_content = []
            for writer_num in range(1, 11):
                # μˆ˜μ •λ³Έμ΄ 있으면 μˆ˜μ •λ³Έμ„, μ—†μœΌλ©΄ μ΄ˆμ•ˆμ„
                row = conn.cursor().execute('''
                    SELECT content FROM stages 
                    WHERE session_id = ? AND role = ? 
                    AND stage_name LIKE '%μˆ˜μ •λ³Έ%'
                    ORDER BY stage_number DESC LIMIT 1
                ''', (session_id, f'writer{writer_num}')).fetchone()
                
                if not row or not row['content']:
                    # μˆ˜μ •λ³Έμ΄ μ—†μœΌλ©΄ μ΄ˆμ•ˆ μ‚¬μš©
                    row = conn.cursor().execute('''
                        SELECT content FROM stages 
                        WHERE session_id = ? AND role = ? 
                        AND stage_name LIKE '%μ΄ˆμ•ˆ%'
                        ORDER BY stage_number DESC LIMIT 1
                    ''', (session_id, f'writer{writer_num}')).fetchone()
                
                if row and row['content']:
                    all_content.append(row['content'].strip())
                    
            return '\n\n'.join(all_content)

    @staticmethod
    def get_total_words(session_id: str) -> int:
        """총 단어 수 κ°€μ Έμ˜€κΈ°"""
        with NovelDatabase.get_db() as conn:
            row = conn.cursor().execute(
                'SELECT total_words FROM sessions WHERE session_id = ?', 
                (session_id,)
            ).fetchone()
            return row['total_words'] if row and row['total_words'] else 0

    @staticmethod
    def save_narrative_tracker(session_id: str, tracker: ProgressiveNarrativeTracker):
        """μ„œμ‚¬ 좔적기 μ €μž₯"""
        with NovelDatabase.get_db() as conn:
            tracker_data = json.dumps({
                'character_arcs': {k: asdict(v) for k, v in tracker.character_arcs.items()},
                'plot_threads': {k: asdict(v) for k, v in tracker.plot_threads.items()},
                'phase_summaries': tracker.phase_summaries,
                'thematic_deepening': tracker.thematic_deepening
            })
            conn.cursor().execute(
                'UPDATE sessions SET narrative_tracker = ? WHERE session_id = ?',
                (tracker_data, session_id)
            )
            conn.commit()

    @staticmethod
    def load_narrative_tracker(session_id: str) -> Optional[ProgressiveNarrativeTracker]:
        """μ„œμ‚¬ 좔적기 λ‘œλ“œ"""
        with NovelDatabase.get_db() as conn:
            row = conn.cursor().execute(
                'SELECT narrative_tracker FROM sessions WHERE session_id = ?',
                (session_id,)
            ).fetchone()
            
            if row and row['narrative_tracker']:
                data = json.loads(row['narrative_tracker'])
                tracker = ProgressiveNarrativeTracker()
                
                # 데이터 볡원
                for name, arc_data in data.get('character_arcs', {}).items():
                    tracker.character_arcs[name] = CharacterArc(**arc_data)
                for thread_id, thread_data in data.get('plot_threads', {}).items():
                    tracker.plot_threads[thread_id] = PlotThread(**thread_data)
                tracker.phase_summaries = data.get('phase_summaries', {})
                tracker.thematic_deepening = data.get('thematic_deepening', [])
                
                return tracker
        return None

    @staticmethod
    def get_session(session_id: str) -> Optional[Dict]:
        with NovelDatabase.get_db() as conn:
            row = conn.cursor().execute('SELECT * FROM sessions WHERE session_id = ?', (session_id,)).fetchone()
            return dict(row) if row else None

    @staticmethod
    def get_stages(session_id: str) -> List[Dict]:
        with NovelDatabase.get_db() as conn:
            rows = conn.cursor().execute('SELECT * FROM stages WHERE session_id = ? ORDER BY stage_number', (session_id,)).fetchall()
            return [dict(row) for row in rows]

    @staticmethod
    def update_final_novel(session_id: str, final_novel: str, literary_report: str = ""):
        with NovelDatabase.get_db() as conn:
            conn.cursor().execute(
                "UPDATE sessions SET final_novel = ?, status = 'complete', updated_at = datetime('now'), literary_report = ? WHERE session_id = ?",
                (final_novel, literary_report, session_id)
            )
            conn.commit()

    @staticmethod
    def get_active_sessions() -> List[Dict]:
        with NovelDatabase.get_db() as conn:
            rows = conn.cursor().execute(
                "SELECT session_id, user_query, language, created_at, current_stage, total_words FROM sessions WHERE status = 'active' ORDER BY updated_at DESC LIMIT 10"
            ).fetchall()
            return [dict(row) for row in rows]


class WebSearchIntegration:
    """μ›Ή 검색 κΈ°λŠ₯"""
    def __init__(self):
        self.brave_api_key = BRAVE_SEARCH_API_KEY
        self.search_url = "https://api.search.brave.com/res/v1/web/search"
        self.enabled = bool(self.brave_api_key)

    def search(self, query: str, count: int = 3, language: str = "en") -> List[Dict]:
        if not self.enabled:
            return []
        headers = {
            "Accept": "application/json",
            "X-Subscription-Token": self.brave_api_key
        }
        params = {
            "q": query,
            "count": count,
            "search_lang": "ko" if language == "Korean" else "en",
            "text_decorations": False,
            "safesearch": "moderate"
        }
        try:
            response = requests.get(self.search_url, headers=headers, params=params, timeout=10)
            response.raise_for_status()
            results = response.json().get("web", {}).get("results", [])
            return results
        except requests.exceptions.RequestException as e:
            logger.error(f"μ›Ή 검색 API 였λ₯˜: {e}")
            return []

    def extract_relevant_info(self, results: List[Dict], max_chars: int = 1500) -> str:
        if not results:
            return ""
        extracted = []
        total_chars = 0
        for i, result in enumerate(results[:3], 1):
            title = result.get("title", "")
            description = result.get("description", "")
            info = f"[{i}] {title}: {description}"
            if total_chars + len(info) < max_chars:
                extracted.append(info)
                total_chars += len(info)
            else:
                break
        return "\n".join(extracted)


class ProgressiveLiterarySystem:
    """μ§„ν–‰ν˜• λ¬Έν•™ μ†Œμ„€ 생성 μ‹œμŠ€ν…œ"""
    def __init__(self):
        self.token = FRIENDLI_TOKEN
        self.api_url = API_URL
        self.model_id = MODEL_ID
        self.narrative_tracker = ProgressiveNarrativeTracker()
        self.web_search = WebSearchIntegration()
        self.current_session_id = None
        NovelDatabase.init_db()

    def create_headers(self):
        return {"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"}

    # --- ν”„λ‘¬ν”„νŠΈ 생성 ν•¨μˆ˜λ“€ ---
    def create_director_initial_prompt(self, user_query: str, language: str) -> str:
        """κ°λ…μž 초기 기획 - ν†΅ν•©λœ μ„œμ‚¬ ꡬ쑰"""
        search_results_str = ""
        if self.web_search.enabled:
            queries = [f"{user_query} μ‚¬νšŒ 문제", f"{user_query} ν˜„λŒ€ ν•œκ΅­"]
            for q in queries[:1]:
                results = self.web_search.search(q, count=2, language=language)
                if results:
                    search_results_str += self.web_search.extract_relevant_info(results) + "\n"

        lang_prompts = {
            "Korean": f"""당신은 ν˜„λŒ€ ν•œκ΅­ λ¬Έν•™μ˜ κ±°μž₯μž…λ‹ˆλ‹€. 
λ‹¨νŽΈμ΄ μ•„λ‹Œ μ€‘νŽΈ μ†Œμ„€(8,000단어 이상)을 μœ„ν•œ ν†΅ν•©λœ μ„œμ‚¬ ꡬ쑰λ₯Ό κΈ°νšν•˜μ„Έμš”.

**주제:** {user_query}

**참고 자료:**
{search_results_str if search_results_str else "N/A"}

**ν•„μˆ˜ μš”κ΅¬μ‚¬ν•­:**

1. **ν†΅ν•©λœ μ„œμ‚¬ ꡬ쑰 (κ°€μž₯ μ€‘μš”)**
   - 10개 단계가 유기적으둜 μ—°κ²°λœ 단일 μ„œμ‚¬
   - 각 λ‹¨κ³„λŠ” 이전 λ‹¨κ³„μ˜ 결과둜 μžμ—°μŠ€λŸ½κ²Œ 이어짐
   - 반볡이 μ•„λ‹Œ 좕적과 λ°œμ „
   
   단계별 μ„œμ‚¬ μ§„ν–‰:
   1) λ„μž…: 일상과 κ· μ—΄ - ν‰λ²”ν•œ 일상 속 첫 κ· μ—΄
   2) λ°œμ „ 1: λΆˆμ•ˆμ˜ κ³ μ‘° - 균열이 ν™•λŒ€λ˜λ©° λΆˆμ•ˆ 증폭
   3) λ°œμ „ 2: μ™ΈλΆ€ 좩격 - μ˜ˆμƒμΉ˜ λͺ»ν•œ μ™ΈλΆ€ 사건
   4) λ°œμ „ 3: 내적 κ°ˆλ“± 심화 - κ°€μΉ˜κ΄€μ˜ 좩돌
   5) μ ˆμ • 1: μœ„κΈ°μ˜ 정점 - λͺ¨λ“  κ°ˆλ“±μ΄ κ·ΉλŒ€ν™”
   6) μ ˆμ • 2: μ„ νƒμ˜ μˆœκ°„ - 결정적 선택
   7) ν•˜κ°• 1: 결과와 μ—¬νŒŒ - μ„ νƒμ˜ 직접적 κ²°κ³Ό
   8) ν•˜κ°• 2: μƒˆλ‘œμš΄ 인식 - λ³€ν™”λœ 세계관
   9) 결말 1: λ³€ν™”λœ 일상 - μƒˆλ‘œμš΄ κ· ν˜•
   10) 결말 2: μ—΄λ¦° 질문 - λ…μžμ—κ²Œ λ˜μ§€λŠ” 질문

2. **인물의 λ³€ν™” ꢀ적**
   - 주인곡: 초기 μƒνƒœ β†’ 쀑간 λ³€ν™” β†’ μ΅œμ’… μƒνƒœ (λͺ…ν™•ν•œ arc)
   - μ£Όμš” 인물듀도 각자의 λ³€ν™” κ²½ν—˜
   - κ΄€κ³„μ˜ 역동적 λ³€ν™”

3. **μ£Όμš” ν”Œλ‘― 라인** (2-3개)
   - 메인 ν”Œλ‘―: 전체λ₯Ό κ΄€ν†΅ν•˜λŠ” 핡심 κ°ˆλ“±
   - μ„œλΈŒ ν”Œλ‘―: 메인과 μ—°κ²°λ˜λ©° 주제λ₯Ό 심화

4. **μƒμ§•μ˜ μ§„ν™”**
   - 핡심 상징 1-2개 μ„€μ •
   - λ‹¨κ³„λ³„λ‘œ μ˜λ―Έκ°€ λ³€ν™”/심화/전볡

5. **μ‚¬νšŒμ  λ§₯락**
   - 개인의 λ¬Έμ œκ°€ μ‚¬νšŒ ꡬ쑰와 μ—°κ²°
   - ꡬ체적인 ν•œκ΅­ μ‚¬νšŒμ˜ ν˜„μ‹€ 반영

**μ ˆλŒ€ κΈˆμ§€μ‚¬ν•­:**
- λ™μΌν•œ μ‚¬κ±΄μ΄λ‚˜ μƒν™©μ˜ 반볡
- 인물이 같은 감정/생각에 머무λ₯΄κΈ°
- ν”Œλ‘―μ˜ λ¦¬μ…‹μ΄λ‚˜ μˆœν™˜ ꡬ쑰
- 각 단계가 λ…λ¦½λœ μ—ν”Όμ†Œλ“œλ‘œ 쑴재

**λΆ„λŸ‰ κ³„νš:**
- 총 8,000단어 이상
- 각 단계 평균 800단어
- κ· ν˜• 작힌 μ„œμ‚¬ μ „κ°œ

ν•˜λ‚˜μ˜ κ°•λ ₯ν•œ μ„œμ‚¬κ°€ μ‹œμž‘λΆ€ν„° λκΉŒμ§€ κ΄€ν†΅ν•˜λŠ” μž‘ν’ˆμ„ κΈ°νšν•˜μ„Έμš”.""",

            "English": f"""You are a master of contemporary literary fiction.
Plan an integrated narrative structure for a novella (8,000+ words), not a collection of short stories.

**Theme:** {user_query}

**Reference:**
{search_results_str if search_results_str else "N/A"}

**Essential Requirements:**

1. **Integrated Narrative Structure (Most Important)**
   - Single narrative with 10 organically connected phases
   - Each phase naturally follows from previous results
   - Accumulation and development, not repetition
   
   Phase Progression:
   1) Introduction: Daily life and first crack
   2) Development 1: Rising anxiety
   3) Development 2: External shock
   4) Development 3: Deepening internal conflict
   5) Climax 1: Peak crisis
   6) Climax 2: Moment of choice
   7) Falling Action 1: Direct consequences
   8) Falling Action 2: New awareness
   9) Resolution 1: Changed daily life
   10) Resolution 2: Open questions

2. **Character Transformation Arcs**
   - Protagonist: Clear progression from initial β†’ middle β†’ final state
   - Supporting characters also experience change
   - Dynamic relationship evolution

3. **Plot Threads** (2-3)
   - Main plot: Core conflict throughout
   - Subplots: Connected and deepening themes

4. **Symbolic Evolution**
   - 1-2 core symbols
   - Meaning transforms across phases

5. **Social Context**
   - Individual problems connected to social structures
   - Specific contemporary realities

**Absolutely Forbidden:**
- Repetition of same events/situations
- Characters stuck in same emotions
- Plot resets or circular structure
- Independent episodes

**Length Planning:**
- Total 8,000+ words
- ~800 words per phase
- Balanced progression

Create a work with one powerful narrative from beginning to end."""
        }
        
        return lang_prompts.get(language, lang_prompts["Korean"])

    def create_critic_director_prompt(self, director_plan: str, user_query: str, language: str) -> str:
        """λΉ„ν‰κ°€μ˜ κ°λ…μž 기획 κ²€ν†  - μ„œμ‚¬ 톡합성 쀑심"""
        lang_prompts = {
            "Korean": f"""당신은 μ„œμ‚¬ ꡬ쑰 μ „λ¬Έ λΉ„ν‰κ°€μž…λ‹ˆλ‹€. 
이 기획이 μ§„μ •ν•œ 'μž₯편 μ†Œμ„€'인지 μ—„κ²©νžˆ κ²€ν† ν•˜μ„Έμš”.

**원 주제:** {user_query}

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

**핡심 κ²€ν†  사항:**

1. **μ„œμ‚¬μ˜ 톡합성과 μ§„ν–‰μ„±**
   - 10개 단계가 ν•˜λ‚˜μ˜ μ΄μ•ΌκΈ°λ‘œ μ—°κ²°λ˜λŠ”κ°€?
   - 각 단계가 이전 λ‹¨κ³„μ˜ 필연적 결과인가?
   - λ™μΌν•œ μƒν™©μ˜ λ°˜λ³΅μ€ μ—†λŠ”κ°€?

2. **인물 λ³€ν™”μ˜ ꢀ적**
   - 주인곡이 λͺ…ν™•ν•œ λ³€ν™”μ˜ arcλ₯Ό κ°€μ§€λŠ”κ°€?
   - λ³€ν™”κ°€ ꡬ체적이고 μ‹ λΉ™μ„± μžˆλŠ”κ°€?
   - κ΄€κ³„μ˜ λ°œμ „μ΄ κ³„νšλ˜μ–΄ μžˆλŠ”κ°€?

3. **ν”Œλ‘―μ˜ 좕적성**
   - κ°ˆλ“±μ΄ μ μ§„μ μœΌλ‘œ μ‹¬ν™”λ˜λŠ”κ°€?
   - μƒˆλ‘œμš΄ μš”μ†Œκ°€ μΆ”κ°€λ˜λ©° λ³΅μž‘μ„±μ΄ μ¦κ°€ν•˜λŠ”κ°€?
   - 해결이 μžμ—°μŠ€λŸ½κ³  필연적인가?

4. **λΆ„λŸ‰κ³Ό 밀도**
   - 8,000단어λ₯Ό μ±„μšΈ μΆ©λΆ„ν•œ λ‚΄μš©μΈκ°€?
   - 각 단계가 800λ‹¨μ–΄μ˜ 밀도λ₯Ό κ°€μ§ˆ 수 μžˆλŠ”κ°€?

**νŒμ •:**
- 톡과: μ§„μ •ν•œ μž₯편 μ„œμ‚¬ ꡬ쑰
- μž¬μž‘μ„±: 반볡적/μˆœν™˜μ  ꡬ쑰

ꡬ체적 κ°œμ„  λ°©ν–₯을 μ œμ‹œν•˜μ„Έμš”.""",

            "English": f"""You are a narrative structure critic.
Strictly review whether this plan is a true 'novel' rather than repeated episodes.

**Original Theme:** {user_query}

**Director's Plan:**
{director_plan}

**Key Review Points:**

1. **Narrative Integration and Progression**
   - Do 10 phases connect as one story?
   - Does each phase necessarily follow from previous?
   - No repetition of same situations?

2. **Character Transformation Arcs**
   - Clear protagonist transformation arc?
   - Concrete and credible changes?
   - Planned relationship development?

3. **Plot Accumulation**
   - Progressive conflict deepening?
   - Added complexity through new elements?
   - Natural and inevitable resolution?

4. **Length and Density**
   - Sufficient content for 8,000 words?
   - Can each phase sustain 800 words?

**Verdict:**
- Pass: True novel structure
- Rewrite: Repetitive/circular structure

Provide specific improvements."""
        }
        
        return lang_prompts.get(language, lang_prompts["Korean"])

    def create_writer_prompt(self, writer_number: int, director_plan: str, 
                           previous_content: str, phase_requirements: str,
                           narrative_summary: str, language: str) -> str:
        """μž‘κ°€ ν”„λ‘¬ν”„νŠΈ - μ„œμ‚¬ μ§„ν–‰ κ°•μ œ"""
        
        phase_name = NARRATIVE_PHASES[writer_number-1]
        target_words = MIN_WORDS_PER_WRITER
        
        lang_prompts = {
            "Korean": f"""당신은 μž‘κ°€ {writer_number}λ²ˆμž…λ‹ˆλ‹€. 
**ν˜„μž¬ 단계: {phase_name}**

**전체 μ„œμ‚¬ ꡬ쑰:**
{director_plan}

**μ§€κΈˆκΉŒμ§€μ˜ 이야기 μš”μ•½:**
{narrative_summary}

**이전 λ‚΄μš© (직전 λΆ€λΆ„):**
{previous_content[-1500:] if previous_content else "μ‹œμž‘"}

**이번 단계 ν•„μˆ˜ μš”κ΅¬μ‚¬ν•­:**
{phase_requirements}

**μž‘μ„± μ§€μΉ¨:**

1. **λΆ„λŸ‰**: {target_words}-900 단어 (ν•„μˆ˜)
   - λ‚΄λ©΄ λ¬˜μ‚¬μ™€ ꡬ체적 λ””ν…ŒμΌλ‘œ λΆ„λŸ‰ 확보
   - μž₯면을 μΆ©λΆ„νžˆ μ „κ°œν•˜κ³  깊이 있게 λ¬˜μ‚¬

2. **μ„œμ‚¬ μ§„ν–‰ (κ°€μž₯ μ€‘μš”)**
   - 이전 λ‹¨κ³„μ—μ„œ μΌμ–΄λ‚œ 일의 직접적 결과둜 μ‹œμž‘
   - μƒˆλ‘œμš΄ 사건/인식/λ³€ν™”λ₯Ό μΆ”κ°€ν•˜μ—¬ 이야기 μ „μ§„
   - λ‹€μŒ λ‹¨κ³„λ‘œ μžμ—°μŠ€λŸ½κ²Œ 연결될 고리 마련

3. **인물의 λ³€ν™”**
   - 이 λ‹¨κ³„μ—μ„œ 인물이 κ²ͺλŠ” ꡬ체적 λ³€ν™” λ¬˜μ‚¬
   - λ‚΄λ©΄μ˜ λ―Έλ¬˜ν•œ 변화도 포착
   - κ΄€κ³„μ˜ μ—­ν•™ λ³€ν™” 반영

4. **문체와 기법**
   - ν•œκ΅­ ν˜„λŒ€ λ¬Έν•™μ˜ μ„¬μ„Έν•œ 심리 λ¬˜μ‚¬
   - 일상 속 μ‚¬νšŒμ  λ§₯락 λ…Ήμ—¬λ‚΄κΈ°
   - 감각적 λ””ν…ŒμΌκ³Ό λ‚΄λ©΄ μ˜μ‹μ˜ κ· ν˜•

5. **연속성 μœ μ§€**
   - 인물의 λͺ©μ†Œλ¦¬μ™€ 말투 일관성
   - 곡간과 μ‹œκ°„μ˜ 연속성
   - 상징과 λͺ¨ν‹°ν”„μ˜ λ°œμ „

**μ ˆλŒ€ κΈˆμ§€:**
- 이전과 λ™μΌν•œ 상황 반볡
- μ„œμ‚¬μ˜ μ •μ²΄λ‚˜ 후퇴
- λΆ„λŸ‰ 미달 (μ΅œμ†Œ {target_words}단어)

μ΄μ „μ˜ 흐름을 이어받아 μƒˆλ‘œμš΄ ꡭ면으둜 λ°œμ „μ‹œν‚€μ„Έμš”.""",

            "English": f"""You are Writer #{writer_number}.
**Current Phase: {phase_name}**

**Overall Narrative Structure:**
{director_plan}

**Story So Far:**
{narrative_summary}

**Previous Content (immediately before):**
{previous_content[-1500:] if previous_content else "Beginning"}

**Phase Requirements:**
{phase_requirements}

**Writing Guidelines:**

1. **Length**: {target_words}-900 words (mandatory)
   - Use interior description and concrete details
   - Fully develop scenes with depth

2. **Narrative Progression (Most Important)**
   - Start as direct result of previous phase
   - Add new events/awareness/changes to advance story
   - Create natural connection to next phase

3. **Character Change**
   - Concrete changes in this phase
   - Capture subtle interior shifts
   - Reflect relationship dynamics

4. **Style and Technique**
   - Delicate psychological portrayal
   - Social context in daily life
   - Balance sensory details with consciousness

5. **Continuity**
   - Consistent character voices
   - Spatial/temporal continuity
   - Symbol/motif development

**Absolutely Forbidden:**
- Repeating previous situations
- Narrative stagnation/regression
- Under word count (minimum {target_words})

Continue the flow and develop into new phase."""
        }
        
        return lang_prompts.get(language, lang_prompts["Korean"])

    def create_critic_consistency_prompt(self, all_content: str, 
                                       narrative_tracker: ProgressiveNarrativeTracker,
                                       user_query: str, language: str) -> str:
        """비평가 쀑간 κ²€ν†  - μ„œμ‚¬ λˆ„μ μ„± 확인"""
        
        # μ„œμ‚¬ μ§„ν–‰ 체크
        phase_count = len(narrative_tracker.phase_summaries)
        progression_ok, issues = narrative_tracker.check_narrative_progression(phase_count)
        
        lang_prompts = {
            "Korean": f"""μ„œμ‚¬ μ§„ν–‰ μ „λ¬Έ λΉ„ν‰κ°€λ‘œμ„œ μž‘ν’ˆμ„ κ²€ν† ν•˜μ„Έμš”.

**원 주제:** {user_query}

**ν˜„μž¬κΉŒμ§€ μ§„ν–‰λœ μ„œμ‚¬ 단계:** {phase_count}/10

**발견된 μ§„ν–‰ 문제:**
{chr(10).join(issues) if issues else "μ—†μŒ"}

**μž‘ν’ˆ λ‚΄μš© (졜근 λΆ€λΆ„):**
{all_content[-4000:]}

**집쀑 κ²€ν†  사항:**

1. **μ„œμ‚¬μ˜ 좕적과 μ§„ν–‰**
   - 이야기가 μ‹€μ œλ‘œ μ „μ§„ν•˜κ³  μžˆλŠ”κ°€?
   - 각 단계가 μ΄μ „μ˜ 결과둜 μ—°κ²°λ˜λŠ”κ°€?
   - λ™μΌν•œ κ°ˆλ“±μ΄λ‚˜ 상황이 λ°˜λ³΅λ˜μ§€ μ•ŠλŠ”κ°€?

2. **인물의 λ³€ν™” ꢀ적**
   - 주인곡이 μ΄ˆκΈ°μ™€ 비ꡐ해 μ–΄λ–»κ²Œ λ³€ν–ˆλŠ”κ°€?
   - λ³€ν™”κ°€ 섀득λ ₯ 있고 점진적인가?
   - 관계가 μ—­λ™μ μœΌλ‘œ λ°œμ „ν•˜λŠ”κ°€?

3. **주제의 심화**
   - 초기 μ£Όμ œκ°€ μ–΄λ–»κ²Œ λ°œμ „ν–ˆλŠ”κ°€?
   - μƒˆλ‘œμš΄ μΈ΅μœ„κ°€ μΆ”κ°€λ˜μ—ˆλŠ”κ°€?
   - λ³΅μž‘μ„±μ΄ μ¦κ°€ν–ˆλŠ”κ°€?

4. **λΆ„λŸ‰κ³Ό 밀도**
   - ν˜„μž¬κΉŒμ§€ 총 단어 수 확인
   - λͺ©ν‘œ(8,000단어)에 도달 κ°€λŠ₯ν•œκ°€?

**μˆ˜μ • μ§€μ‹œ:**
각 μž‘κ°€μ—κ²Œ ꡬ체적인 μ§„ν–‰ λ°©ν–₯ μ œμ‹œ.""",

            "English": f"""As a narrative progression critic, review the work.

**Original Theme:** {user_query}

**Narrative Phases Completed:** {phase_count}/10

**Detected Progression Issues:**
{chr(10).join(issues) if issues else "None"}

**Work Content (recent):**
{all_content[-4000:]}

**Focus Review Areas:**

1. **Narrative Accumulation and Progress**
   - Is story actually moving forward?
   - Does each phase connect as result of previous?
   - No repetition of same conflicts/situations?

2. **Character Transformation Arcs**
   - How has protagonist changed from beginning?
   - Are changes credible and gradual?
   - Dynamic relationship development?

3. **Thematic Deepening**
   - How has initial theme developed?
   - New layers added?
   - Increased complexity?

4. **Length and Density**
   - Current total word count
   - Can reach 8,000 word target?

**Revision Instructions:**
Specific progression directions for each writer."""
        }
        
        return lang_prompts.get(language, lang_prompts["Korean"])

    def create_writer_revision_prompt(self, writer_number: int, initial_content: str, 
                                    critic_feedback: str, language: str) -> str:
        """μž‘κ°€ μˆ˜μ • ν”„λ‘¬ν”„νŠΈ"""
        target_words = MIN_WORDS_PER_WRITER
        
        return f"""μž‘κ°€ {writer_number}번, 비평을 λ°˜μ˜ν•˜μ—¬ μˆ˜μ •ν•˜μ„Έμš”.

**μ΄ˆμ•ˆ:**
{initial_content}

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

**μˆ˜μ • 핡심:**
1. μ„œμ‚¬ μ§„ν–‰μ„± κ°•ν™” - 반볡 제거, μƒˆλ‘œμš΄ μ „κ°œ μΆ”κ°€
2. 인물 λ³€ν™” ꡬ체화 - 이전과 달라진 λͺ¨μŠ΅ λͺ…ν™•νžˆ
3. λΆ„λŸ‰ 확보 - μ΅œμ†Œ {target_words}단어 μœ μ§€
4. λ‚΄λ©΄ λ¬˜μ‚¬μ™€ μ‚¬νšŒμ  λ§₯락 심화

μ „λ©΄ μž¬μž‘μ„±μ΄ ν•„μš”ν•˜λ©΄ 과감히 μˆ˜μ •ν•˜μ„Έμš”.
μˆ˜μ •λ³Έλ§Œ μ œμ‹œν•˜μ„Έμš”."""

    def create_critic_final_prompt(self, complete_novel: str, word_count: int, language: str) -> str:
        """μ΅œμ’… 비평 - AGI 평가 κΈ°μ€€"""
        return f"""μ™„μ„±λœ μ†Œμ„€μ„ AGI νŠœλ§ν…ŒμŠ€νŠΈ κΈ°μ€€μœΌλ‘œ ν‰κ°€ν•˜μ„Έμš”.

**μž‘ν’ˆ 정보:**
- 총 λΆ„λŸ‰: {word_count}단어
- λͺ©ν‘œ λΆ„λŸ‰: 8,000단어 이상

**μž‘ν’ˆ (λ§ˆμ§€λ§‰ λΆ€λΆ„):**
{complete_novel[-3000:]}

**평가 κΈ°μ€€ (AGI νŠœλ§ν…ŒμŠ€νŠΈ):**

1. **μž₯νŽΈμ†Œμ„€λ‘œμ„œμ˜ 완성도 (40점)**
   - ν†΅ν•©λœ μ„œμ‚¬ ꡬ쑰 (반볡 μ—†μŒ)
   - 인물의 λͺ…ν™•ν•œ λ³€ν™” arc
   - ν”Œλ‘―μ˜ 좕적과 ν•΄κ²°
   - 8,000단어 이상 λΆ„λŸ‰

2. **문학적 μ„±μ·¨ (30점)**
   - 주제 μ˜μ‹μ˜ 깊이
   - 인물 μ‹¬λ¦¬μ˜ 섀득λ ₯
   - 문체의 일관성과 아름닀움
   - 상징과 μ€μœ μ˜ 효과

3. **μ‚¬νšŒμ  톡찰 (20점)**
   - ν˜„λŒ€ μ‚¬νšŒ 문제 포착
   - 개인과 ꡬ쑰의 μ—°κ²°
   - λ³΄νŽΈμ„±κ³Ό νŠΉμˆ˜μ„± κ· ν˜•

4. **독창성과 인간성 (10점)**
   - AIκ°€ μ•„λ‹Œ 인간 μž‘κ°€μ˜ λŠλ‚Œ
   - 독창적 ν‘œν˜„κ³Ό 톡찰
   - 감정적 μ§„μ •μ„±

**총점: /100점**

특히 '반볡 ꡬ쑰' λ¬Έμ œκ°€ μžˆμ—ˆλŠ”μ§€ μ—„κ²©νžˆ ν‰κ°€ν•˜μ„Έμš”."""

    # --- LLM 호좜 ν•¨μˆ˜λ“€ ---
    def call_llm_sync(self, messages: List[Dict[str, str]], role: str, language: str) -> str:
        full_content = ""
        for chunk in self.call_llm_streaming(messages, role, language):
            full_content += chunk
        if full_content.startswith("❌"):
            raise Exception(f"LLM Call Failed: {full_content}")
        return full_content

    def call_llm_streaming(self, messages: List[Dict[str, str]], role: str, language: str) -> Generator[str, None, None]:
        try:
            system_prompts = self.get_system_prompts(language)
            full_messages = [{"role": "system", "content": system_prompts.get(role, "")}, *messages]
            
            # μž‘κ°€ 역할일 λ•ŒλŠ” 더 λ§Žμ€ 토큰 ν—ˆμš©
            max_tokens = 15000 if role.startswith("writer") else 10000
            
            payload = {
                "model": self.model_id,
                "messages": full_messages,
                "max_tokens": max_tokens,
                "temperature": 0.8,
                "top_p": 0.95,
                "presence_penalty": 0.5,
                "frequency_penalty": 0.3,
                "stream": True
            }
            
            response = requests.post(
                self.api_url, 
                headers=self.create_headers(), 
                json=payload, 
                stream=True, 
                timeout=180
            )
            
            if response.status_code != 200:
                yield f"❌ API 였λ₯˜ (μƒνƒœ μ½”λ“œ: {response.status_code})"
                return
            
            buffer = ""
            for line in response.iter_lines():
                if not line:
                    continue
                
                try:
                    line_str = line.decode('utf-8').strip()
                    if not line_str.startswith("data: "):
                        continue
                    
                    data_str = line_str[6:]
                    if data_str == "[DONE]":
                        break
                    
                    data = json.loads(data_str)
                    choices = data.get("choices", [])
                    if choices and choices[0].get("delta", {}).get("content"):
                        content = choices[0]["delta"]["content"]
                        buffer += content
                        
                        if len(buffer) >= 50 or '\n' in buffer:
                            yield buffer
                            buffer = ""
                            time.sleep(0.01)
                    
                except Exception as e:
                    logger.error(f"청크 처리 였λ₯˜: {str(e)}")
                    continue
            
            if buffer:
                yield buffer
                
        except Exception as e:
            logger.error(f"슀트리밍 였λ₯˜: {type(e).__name__}: {str(e)}")
            yield f"❌ 였λ₯˜ λ°œμƒ: {str(e)}"

    def get_system_prompts(self, language: str) -> Dict[str, str]:
        """역할별 μ‹œμŠ€ν…œ ν”„λ‘¬ν”„νŠΈ"""
        base_prompts = {
            "Korean": {
                "director": """당신은 ν•œκ΅­ ν˜„λŒ€ λ¬Έν•™μ˜ κ±°μž₯μž…λ‹ˆλ‹€.
반볡이 μ•„λ‹Œ μ§„ν–‰, μˆœν™˜μ΄ μ•„λ‹Œ λ°œμ „μ„ 톡해 ν•˜λ‚˜μ˜ κ°•λ ₯ν•œ μ„œμ‚¬λ₯Ό κ΅¬μΆ•ν•˜μ„Έμš”.
개인의 문제λ₯Ό μ‚¬νšŒ ꡬ쑰와 μ—°κ²°ν•˜λ©°, 인물의 μ§„μ •ν•œ λ³€ν™”λ₯Ό κ·Έλ €λ‚΄μ„Έμš”.""",
                
                "critic": """당신은 μ—„κ²©ν•œ λ¬Έν•™ λΉ„ν‰κ°€μž…λ‹ˆλ‹€.
특히 '반볡 ꡬ쑰'와 'μ„œμ‚¬ 정체'λ₯Ό μ² μ €νžˆ κ°μ‹œν•˜μ„Έμš”.
μž‘ν’ˆμ΄ μ§„μ •ν•œ μž₯νŽΈμ†Œμ„€μΈμ§€, μ•„λ‹ˆλ©΄ λ°˜λ³΅λ˜λŠ” λ‹¨νŽΈμ˜ 집합인지 κ΅¬λ³„ν•˜μ„Έμš”.""",
                
                "writer_base": """당신은 ν˜„λŒ€ ν•œκ΅­ λ¬Έν•™ μž‘κ°€μž…λ‹ˆλ‹€.
이전 λ‹¨κ³„μ˜ κ²°κ³Όλ₯Ό λ°›μ•„ μƒˆλ‘œμš΄ ꡭ면으둜 λ°œμ „μ‹œν‚€μ„Έμš”.
μ΅œμ†Œ 800단어λ₯Ό μž‘μ„±ν•˜λ©°, λ‚΄λ©΄κ³Ό μ‚¬νšŒλ₯Ό λ™μ‹œμ— ν¬μ°©ν•˜μ„Έμš”.
μ ˆλŒ€ 이전과 같은 상황을 λ°˜λ³΅ν•˜μ§€ λ§ˆμ„Έμš”."""
            },
            "English": {
                "director": """You are a master of contemporary literary fiction.
Build one powerful narrative through progression not repetition, development not cycles.
Connect individual problems to social structures while depicting genuine character transformation.""",
                
                "critic": """You are a strict literary critic.
Vigilantly monitor for 'repetitive structure' and 'narrative stagnation'.
Distinguish whether this is a true novel or a collection of repeated episodes.""",
                
                "writer_base": """You are a contemporary literary writer.
Take results from previous phase and develop into new territory.
Write minimum 800 words, capturing both interior and society.
Never repeat previous situations."""
            }
        }
        
        prompts = base_prompts.get(language, base_prompts["Korean"]).copy()
        
        # 특수 μž‘κ°€ ν”„λ‘¬ν”„νŠΈ
        for i in range(1, 11):
            prompts[f"writer{i}"] = prompts["writer_base"]
        
        return prompts

    # --- 메인 ν”„λ‘œμ„ΈμŠ€ ---
    def process_novel_stream(self, query: str, language: str, session_id: Optional[str] = None) -> Generator[Tuple[str, List[Dict[str, Any]], str], None, None]:
        """μ†Œμ„€ 생성 ν”„λ‘œμ„ΈμŠ€"""
        try:
            resume_from_stage = 0
            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
                    # μ„œμ‚¬ 좔적기 볡원
                    saved_tracker = NovelDatabase.load_narrative_tracker(session_id)
                    if saved_tracker:
                        self.narrative_tracker = saved_tracker
            else:
                self.current_session_id = NovelDatabase.create_session(query, language)
                logger.info(f"Created new session: {self.current_session_id}")

            stages = []
            if resume_from_stage > 0:
                stages = [{
                    "name": s['stage_name'], 
                    "status": s['status'], 
                    "content": s.get('content', ''),
                    "word_count": s.get('word_count', 0),
                    "progression_score": s.get('progression_score', 0.0)
                } for s in NovelDatabase.get_stages(self.current_session_id)]

            # 총 단어 수 좔적
            total_words = NovelDatabase.get_total_words(self.current_session_id)

            for stage_idx in range(resume_from_stage, len(PROGRESSIVE_STAGES)):
                role, stage_name = PROGRESSIVE_STAGES[stage_idx]
                if stage_idx >= len(stages):
                    stages.append({
                        "name": stage_name, 
                        "status": "active", 
                        "content": "", 
                        "word_count": 0,
                        "progression_score": 0.0
                    })
                else:
                    stages[stage_idx]["status"] = "active"

                yield f"πŸ”„ μ§„ν–‰ 쀑... (ν˜„μž¬ {total_words:,}단어)", stages, self.current_session_id
                
                prompt = self.get_stage_prompt(stage_idx, role, query, language, stages)
                stage_content = ""
                
                for chunk in self.call_llm_streaming([{"role": "user", "content": prompt}], role, language):
                    stage_content += chunk
                    stages[stage_idx]["content"] = stage_content
                    stages[stage_idx]["word_count"] = len(stage_content.split())
                    yield f"πŸ”„ {stage_name} μž‘μ„± 쀑... ({total_words + stages[stage_idx]['word_count']:,}단어)", stages, self.current_session_id

                # 진행도 평가
                if role.startswith("writer"):
                    writer_num = int(re.search(r'\d+', role).group())
                    progression_score = self.evaluate_progression(stage_content, writer_num)
                    stages[stage_idx]["progression_score"] = progression_score
                    
                    # μ„œμ‚¬ 좔적기 μ—…λ°μ΄νŠΈ
                    self.update_narrative_tracker(stage_content, writer_num)

                stages[stage_idx]["status"] = "complete"
                NovelDatabase.save_stage(
                    self.current_session_id, stage_idx, stage_name, role,
                    stage_content, "complete", stages[stage_idx].get("progression_score", 0.0)
                )
                
                # μ„œμ‚¬ 좔적기 μ €μž₯
                NovelDatabase.save_narrative_tracker(self.current_session_id, self.narrative_tracker)
                
                # 총 단어 수 μ—…λ°μ΄νŠΈ
                total_words = NovelDatabase.get_total_words(self.current_session_id)
                yield f"βœ… {stage_name} μ™„λ£Œ (총 {total_words:,}단어)", stages, self.current_session_id

            # μ΅œμ’… μ†Œμ„€ 정리
            final_novel = NovelDatabase.get_writer_content(self.current_session_id)
            final_word_count = len(final_novel.split())
            final_report = self.generate_literary_report(final_novel, final_word_count, language)
            
            NovelDatabase.update_final_novel(self.current_session_id, final_novel, final_report)
            yield f"βœ… μ†Œμ„€ μ™„μ„±! 총 {final_word_count:,}단어 (λͺ©ν‘œ: {TARGET_WORDS:,}단어)", stages, self.current_session_id

        except Exception as e:
            logger.error(f"μ†Œμ„€ 생성 ν”„λ‘œμ„ΈμŠ€ 였λ₯˜: {e}", exc_info=True)
            yield f"❌ 였λ₯˜ λ°œμƒ: {e}", stages if 'stages' in locals() else [], self.current_session_id

    def get_stage_prompt(self, stage_idx: int, role: str, query: str, language: str, stages: List[Dict]) -> str:
        """단계별 ν”„λ‘¬ν”„νŠΈ 생성"""
        if stage_idx == 0:
            return self.create_director_initial_prompt(query, language)
        if stage_idx == 1:
            return self.create_critic_director_prompt(stages[0]["content"], query, language)
        if stage_idx == 2:
            return self.create_director_revision_prompt(stages[0]["content"], stages[1]["content"], query, language)

        master_plan = stages[2]["content"]
        
        if 3 <= stage_idx <= 12:  # μž‘κ°€ μ΄ˆμ•ˆ
            writer_num = stage_idx - 2
            previous_content = self.get_previous_writer_content(stages, writer_num)
            phase_requirements = self.narrative_tracker.generate_phase_requirements(writer_num)
            narrative_summary = self.generate_narrative_summary(stages, writer_num)
            
            return self.create_writer_prompt(
                writer_num, master_plan, previous_content, 
                phase_requirements, narrative_summary, language
            )
        
        if stage_idx == 13:  # 비평가 쀑간 κ²€ν† 
            all_content = self.get_all_writer_content(stages, 12)
            return self.create_critic_consistency_prompt(
                all_content, self.narrative_tracker, query, language
            )
            
        if 14 <= stage_idx <= 23:  # μž‘κ°€ μˆ˜μ •
            writer_num = stage_idx - 13
            initial_content = stages[2 + writer_num]["content"]
            feedback = stages[13]["content"]
            return self.create_writer_revision_prompt(writer_num, initial_content, feedback, language)
        
        if stage_idx == 24:  # μ΅œμ’… κ²€ν† 
            complete_novel = self.get_all_writer_content(stages, 23)
            word_count = len(complete_novel.split())
            return self.create_critic_final_prompt(complete_novel, word_count, language)
        
        return ""

    def create_director_revision_prompt(self, initial_plan: str, critic_feedback: str, user_query: str, language: str) -> str:
        """κ°λ…μž μˆ˜μ • ν”„λ‘¬ν”„νŠΈ"""
        return f"""비평을 λ°˜μ˜ν•˜μ—¬ ν†΅ν•©λœ μ„œμ‚¬ ꡬ쑰λ₯Ό μ™„μ„±ν•˜μ„Έμš”.

**원 주제:** {user_query}

**초기 기획:**
{initial_plan}

**비평:**
{critic_feedback}

**핡심 μˆ˜μ • 사항:**
1. 반볡 ꡬ쑰 μ™„μ „ 제거
2. 10단계가 ν•˜λ‚˜μ˜ μ΄μ•ΌκΈ°λ‘œ μ—°κ²°
3. 인물의 λͺ…ν™•ν•œ λ³€ν™” ꢀ적
4. 8,000단어 λΆ„λŸ‰ κ³„νš

각 단계가 μ΄μ „μ˜ 필연적 κ²°κ³Όκ°€ λ˜λ„λ‘ μˆ˜μ •ν•˜μ„Έμš”."""

    def get_previous_writer_content(self, stages: List[Dict], current_writer: int) -> str:
        """이전 μž‘κ°€μ˜ λ‚΄μš© κ°€μ Έμ˜€κΈ°"""
        if current_writer == 1:
            return ""
        
        # λ°”λ‘œ 이전 μž‘κ°€μ˜ λ‚΄μš©
        prev_idx = current_writer + 1  # stages μΈλ±μŠ€λŠ” writer_num + 2
        if prev_idx < len(stages) and stages[prev_idx]["content"]:
            return stages[prev_idx]["content"]
        
        return ""

    def get_all_writer_content(self, stages: List[Dict], up_to_stage: int) -> str:
        """νŠΉμ • λ‹¨κ³„κΉŒμ§€μ˜ λͺ¨λ“  μž‘κ°€ λ‚΄μš©"""
        contents = []
        for i, s in enumerate(stages):
            if i <= up_to_stage and "writer" in s.get("name", "") and s["content"]:
                contents.append(s["content"])
        return "\n\n".join(contents)

    def generate_narrative_summary(self, stages: List[Dict], up_to_writer: int) -> str:
        """ν˜„μž¬κΉŒμ§€μ˜ μ„œμ‚¬ μš”μ•½"""
        if up_to_writer == 1:
            return "첫 μ‹œμž‘μž…λ‹ˆλ‹€."
        
        summary_parts = []
        for i in range(1, up_to_writer):
            if i in self.narrative_tracker.phase_summaries:
                summary_parts.append(f"[{NARRATIVE_PHASES[i-1]}]: {self.narrative_tracker.phase_summaries[i]}")
        
        return "\n".join(summary_parts) if summary_parts else "이전 λ‚΄μš©μ„ 이어받아 μ§„ν–‰ν•˜μ„Έμš”."

    def update_narrative_tracker(self, content: str, writer_num: int):
        """μ„œμ‚¬ 좔적기 μ—…λ°μ΄νŠΈ"""
        # κ°„λ‹¨ν•œ μš”μ•½ 생성 (μ‹€μ œλ‘œλŠ” 더 μ •κ΅ν•œ 뢄석 ν•„μš”)
        lines = content.split('\n')
        key_events = [line.strip() for line in lines if len(line.strip()) > 50][:3]
        
        if key_events:
            summary = " ".join(key_events[:2])[:200] + "..."
            self.narrative_tracker.phase_summaries[writer_num] = summary

    def evaluate_progression(self, content: str, phase: int) -> float:
        """μ„œμ‚¬ 진행도 평가"""
        score = 5.0
        
        # λΆ„λŸ‰ 체크
        word_count = len(content.split())
        if word_count >= MIN_WORDS_PER_WRITER:
            score += 2.0
        
        # μƒˆλ‘œμš΄ μš”μ†Œ 체크
        if phase > 1:
            prev_summary = self.narrative_tracker.phase_summaries.get(phase-1, "")
            if prev_summary and len(set(content.split()) - set(prev_summary.split())) > 100:
                score += 1.5
        
        # λ³€ν™” μ–ΈκΈ‰ 체크
        change_keywords = ['λ³€ν–ˆ', 'λ‹¬λΌμ‘Œ', 'μƒˆλ‘œμš΄', 'μ΄μ œλŠ”', '더 이상', 
                          'changed', 'different', 'new', 'now', 'no longer']
        if any(keyword in content for keyword in change_keywords):
            score += 1.5
        
        return min(10.0, score)

    def generate_literary_report(self, complete_novel: str, word_count: int, language: str) -> str:
        """μ΅œμ’… 문학적 평가"""
        prompt = self.create_critic_final_prompt(complete_novel, word_count, language)
        try:
            report = self.call_llm_sync([{"role": "user", "content": prompt}], "critic", language)
            return report
        except Exception as e:
            logger.error(f"μ΅œμ’… λ³΄κ³ μ„œ 생성 μ‹€νŒ¨: {e}")
            return "λ³΄κ³ μ„œ 생성 쀑 였λ₯˜ λ°œμƒ"


# --- μœ ν‹Έλ¦¬ν‹° ν•¨μˆ˜λ“€ ---
def process_query(query: str, language: str, session_id: Optional[str] = None) -> Generator[Tuple[str, str, str, str], None, None]:
    """메인 쿼리 처리 ν•¨μˆ˜"""
    if not query.strip():
        yield "", "", "❌ 주제λ₯Ό μž…λ ₯ν•΄μ£Όμ„Έμš”.", session_id
        return
    
    system = ProgressiveLiterarySystem()
    stages_markdown = ""
    novel_content = ""
    
    for status, stages, current_session_id in system.process_novel_stream(query, language, session_id):
        stages_markdown = format_stages_display(stages)
        
        # μ΅œμ’… μ†Œμ„€ λ‚΄μš© κ°€μ Έμ˜€κΈ°
        if stages and all(s.get("status") == "complete" for s in stages[-10:]):
            novel_content = NovelDatabase.get_writer_content(current_session_id)
            novel_content = format_novel_display(novel_content)
        
        yield stages_markdown, novel_content, status or "πŸ”„ 처리 쀑...", current_session_id

def get_active_sessions(language: str) -> List[str]:
    """ν™œμ„± μ„Έμ…˜ λͺ©λ‘"""
    sessions = NovelDatabase.get_active_sessions()
    return [f"{s['session_id'][:8]}... - {s['user_query'][:50]}... ({s['created_at']}) [{s['total_words']:,}단어]" 
            for s in sessions]

def auto_recover_session(language: str) -> Tuple[Optional[str], str]:
    """졜근 μ„Έμ…˜ μžλ™ 볡ꡬ"""
    sessions = NovelDatabase.get_active_sessions()
    if sessions:
        latest_session = sessions[0]
        return latest_session['session_id'], f"μ„Έμ…˜ {latest_session['session_id'][:8]}... 볡ꡬ됨"
    return None, "볡ꡬ할 μ„Έμ…˜μ΄ μ—†μŠ΅λ‹ˆλ‹€."

def resume_session(session_id: str, language: str) -> Generator[Tuple[str, str, str, str], None, None]:
    """μ„Έμ…˜ 재개"""
    if not session_id:
        yield "", "", "❌ μ„Έμ…˜ IDκ°€ μ—†μŠ΅λ‹ˆλ‹€.", session_id
        return
    
    if "..." in session_id:
        session_id = session_id.split("...")[0]
    
    session = NovelDatabase.get_session(session_id)
    if not session:
        yield "", "", "❌ μ„Έμ…˜μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.", None
        return
    
    yield from process_query(session['user_query'], session['language'], session_id)

def download_novel(novel_text: str, format_type: str, language: str, session_id: str) -> Optional[str]:
    """μ†Œμ„€ λ‹€μš΄λ‘œλ“œ 파일 생성"""
    if not novel_text or not session_id:
        return None
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"novel_{session_id[:8]}_{timestamp}"
    
    try:
        if format_type == "DOCX" and DOCX_AVAILABLE:
            return export_to_docx(novel_text, filename, language, session_id)
        else:
            return export_to_txt(novel_text, filename)
    except Exception as e:
        logger.error(f"파일 생성 μ‹€νŒ¨: {e}")
        return None

def format_stages_display(stages: List[Dict]) -> str:
    """단계별 μ§„ν–‰ 상황 ν‘œμ‹œ"""
    markdown = "## 🎬 μ§„ν–‰ 상황\n\n"
    
    # 총 단어 수 계산
    total_words = sum(s.get('word_count', 0) for s in stages if 'writer' in s.get('name', ''))
    markdown += f"**총 단어 수: {total_words:,} / {TARGET_WORDS:,}**\n\n"
    
    for i, stage in enumerate(stages):
        status_icon = "βœ…" if stage['status'] == 'complete' else "πŸ”„" if stage['status'] == 'active' else "⏳"
        markdown += f"{status_icon} **{stage['name']}**"
        
        if stage.get('word_count', 0) > 0:
            markdown += f" ({stage['word_count']:,}단어)"
        
        if stage.get('progression_score', 0) > 0:
            markdown += f" [진행도: {stage['progression_score']:.1f}/10]"
        
        markdown += "\n"
        
        if stage['content']:
            preview = stage['content'][:200] + "..." if len(stage['content']) > 200 else stage['content']
            markdown += f"> {preview}\n\n"
    
    return markdown

def format_novel_display(novel_text: str) -> str:
    """μ†Œμ„€ λ‚΄μš© ν‘œμ‹œ"""
    if not novel_text:
        return "아직 μ™„μ„±λœ λ‚΄μš©μ΄ μ—†μŠ΅λ‹ˆλ‹€."
    
    formatted = "# πŸ“– μ™„μ„±λœ μ†Œμ„€\n\n"
    
    # 단어 수 ν‘œμ‹œ
    word_count = len(novel_text.split())
    formatted += f"**총 λΆ„λŸ‰: {word_count:,}단어 (λͺ©ν‘œ: {TARGET_WORDS:,}단어)**\n\n"
    formatted += "---\n\n"
    
    # 각 단계λ₯Ό κ΅¬λΆ„ν•˜μ—¬ ν‘œμ‹œ
    sections = novel_text.split('\n\n')
    for i, section in enumerate(sections):
        if section.strip():
            formatted += f"{section}\n\n"
    
    return formatted

def export_to_docx(content: str, filename: str, language: str, session_id: str) -> str:
    """DOCX 파일둜 내보내기"""
    doc = Document()
    
    # νŽ˜μ΄μ§€ μ„€μ •
    section = doc.sections[0]
    section.page_height = Inches(11)
    section.page_width = Inches(8.5)
    section.top_margin = Inches(1)
    section.bottom_margin = Inches(1)
    section.left_margin = Inches(1.25)
    section.right_margin = Inches(1.25)
    
    # μ„Έμ…˜ 정보
    session = NovelDatabase.get_session(session_id)
    
    # 제λͺ© νŽ˜μ΄μ§€
    title_para = doc.add_paragraph()
    title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    if session:
        title_run = title_para.add_run(session["user_query"])
        title_run.font.size = Pt(24)
        title_run.bold = True
    
    # 메타 정보
    doc.add_paragraph()
    meta_para = doc.add_paragraph()
    meta_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
    meta_para.add_run(f"생성일: {datetime.now().strftime('%Yλ…„ %mμ›” %d일')}\n")
    meta_para.add_run(f"총 단어 수: {len(content.split()):,}단어")
    
    # νŽ˜μ΄μ§€ λ‚˜λˆ„κΈ°
    doc.add_page_break()
    
    # λ³Έλ¬Έ μŠ€νƒ€μΌ μ„€μ •
    style = doc.styles['Normal']
    style.font.name = 'Calibri'
    style.font.size = Pt(11)
    style.paragraph_format.line_spacing = 1.5
    style.paragraph_format.space_after = Pt(6)
    
    # λ³Έλ¬Έ μΆ”κ°€
    paragraphs = content.split('\n\n')
    for para_text in paragraphs:
        if para_text.strip():
            para = doc.add_paragraph(para_text.strip())
    
    # 파일 μ €μž₯
    filepath = f"{filename}.docx"
    doc.save(filepath)
    return filepath

def export_to_txt(content: str, filename: str) -> str:
    """TXT 파일둜 내보내기"""
    filepath = f"{filename}.txt"
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(content)
    return filepath


# CSS μŠ€νƒ€μΌ
custom_css = """
.gradio-container {
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 50%, #1e3c72 100%);
    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;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.progress-note {
    background-color: rgba(255, 223, 0, 0.1);
    border-left: 3px solid #ffd700;
    padding: 15px;
    margin: 20px 0;
    border-radius: 8px;
    color: #fff;
}

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

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

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

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

.download-section {
    background-color: rgba(255, 255, 255, 0.9);
    padding: 15px;
    border-radius: 8px;
    margin-top: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* μ§„ν–‰ ν‘œμ‹œκΈ° μŠ€νƒ€μΌ */
.progress-bar {
    background-color: #e0e0e0;
    height: 20px;
    border-radius: 10px;
    overflow: hidden;
    margin: 10px 0;
}

.progress-fill {
    background-color: #4CAF50;
    height: 100%;
    transition: width 0.3s ease;
}
"""


# Gradio μΈν„°νŽ˜μ΄μŠ€ 생성
def create_interface():
    with gr.Blocks(css=custom_css, title="AI μ§„ν–‰ν˜• μž₯νŽΈμ†Œμ„€ 생성 μ‹œμŠ€ν…œ") as interface:
        gr.HTML("""
        <div class="main-header">
            <h1 style="font-size: 2.5em; margin-bottom: 10px;">
                πŸ“š AI μ§„ν–‰ν˜• μž₯νŽΈμ†Œμ„€ 생성 μ‹œμŠ€ν…œ
            </h1>
            <h3 style="color: #ddd; margin-bottom: 20px;">
                8,000단어 μ΄μƒμ˜ ν†΅ν•©λœ μ„œμ‚¬ ꡬ쑰λ₯Ό κ°€μ§„ μ€‘νŽΈμ†Œμ„€ μ°½μž‘
            </h3>
            <p style="font-size: 1.1em; color: #eee; max-width: 800px; margin: 0 auto;">
                10개의 유기적으둜 μ—°κ²°λœ 단계λ₯Ό 톡해 ν•˜λ‚˜μ˜ μ™„μ „ν•œ 이야기λ₯Ό λ§Œλ“€μ–΄λƒ…λ‹ˆλ‹€.
                <br>
                각 λ‹¨κ³„λŠ” 이전 λ‹¨κ³„μ˜ 필연적 결과둜 이어지며, 인물의 변화와 μ„±μž₯을 μΆ”μ ν•©λ‹ˆλ‹€.
            </p>
            <div class="progress-note">
                ⚑ 반볡이 μ•„λ‹Œ 좕적, μˆœν™˜μ΄ μ•„λ‹Œ 진행을 ν†΅ν•œ μ§„μ •ν•œ μž₯편 μ„œμ‚¬
            </div>
        </div>
        """)
        
        # μƒνƒœ 관리
        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="μ€‘νŽΈμ†Œμ„€μ˜ 주제λ₯Ό μž…λ ₯ν•˜μ„Έμš”. 인물의 변화와 μ„±μž₯이 쀑심이 λ˜λŠ” 이야기...\nEnter the theme for your novella. Focus on character transformation and growth...",
                        lines=4
                    )
                    
                    language_select = gr.Radio(
                        choices=["Korean", "English"],
                        value="Korean",
                        label="μ–Έμ–΄ / Language"
                    )
                    
                    with gr.Row():
                        submit_btn = gr.Button("πŸš€ μ†Œμ„€ 생성 μ‹œμž‘", variant="primary", scale=2)
                        clear_btn = gr.Button("πŸ—‘οΈ μ΄ˆκΈ°ν™”", scale=1)
                    
                    status_text = gr.Textbox(
                        label="μƒνƒœ",
                        interactive=False,
                        value="πŸ”„ μ€€λΉ„ μ™„λ£Œ"
                    )
                    
                    # μ„Έμ…˜ 관리
                    with gr.Group(elem_classes=["session-section"]):
                        gr.Markdown("### πŸ’Ύ μ§„ν–‰ 쀑인 μ„Έμ…˜")
                        session_dropdown = gr.Dropdown(
                            label="μ„Έμ…˜ 선택",
                            choices=[],
                            interactive=True
                        )
                        with gr.Row():
                            refresh_btn = gr.Button("πŸ”„ λͺ©λ‘ μƒˆλ‘œκ³ μΉ¨", scale=1)
                            resume_btn = gr.Button("▢️ 선택 재개", variant="secondary", scale=1)
                            auto_recover_btn = gr.Button("♻️ 졜근 μ„Έμ…˜ 볡ꡬ", scale=1)
        
        with gr.Column(scale=2):
            with gr.Tab("πŸ“ μ°½μž‘ μ§„ν–‰"):
                stages_display = gr.Markdown(
                    value="μ°½μž‘ 과정이 여기에 ν‘œμ‹œλ©λ‹ˆλ‹€...",
                    elem_id="stages-display"
                )
            
            with gr.Tab("πŸ“– μ™„μ„±λœ μ†Œμ„€"):
                novel_output = gr.Markdown(
                    value="μ™„μ„±λœ μ†Œμ„€μ΄ 여기에 ν‘œμ‹œλ©λ‹ˆλ‹€...",
                    elem_id="novel-output"
                )
                
                with gr.Group(elem_classes=["download-section"]):
                    gr.Markdown("### πŸ“₯ μ†Œμ„€ λ‹€μš΄λ‘œλ“œ")
                    with gr.Row():
                        format_select = gr.Radio(
                            choices=["DOCX", "TXT"],
                            value="DOCX" if DOCX_AVAILABLE else "TXT",
                            label="ν˜•μ‹"
                        )
                        download_btn = gr.Button("⬇️ λ‹€μš΄λ‘œλ“œ", variant="secondary")
                    
                    download_file = gr.File(
                        label="λ‹€μš΄λ‘œλ“œλœ 파일",
                        visible=False
                    )
        
        # μˆ¨κ²¨μ§„ μƒνƒœ
        novel_text_state = gr.State("")
        
        # 예제
        with gr.Row():
            gr.Examples(
                examples=[
                    ["μ‹€μ§ν•œ 쀑년 남성이 μƒˆλ‘œμš΄ μ‚Άμ˜ 의미λ₯Ό μ°Ύμ•„κ°€λŠ” μ—¬μ •"],
                    ["λ„μ‹œμ—μ„œ μ‹œκ³¨λ‘œ μ΄μ£Όν•œ μ²­λ…„μ˜ 적응과 μ„±μž₯ 이야기"],
                    ["μ„Έ μ„ΈλŒ€κ°€ ν•¨κ»˜ μ‚¬λŠ” κ°€μ‘±μ˜ κ°ˆλ“±κ³Ό ν™”ν•΄"],
                    ["A middle-aged woman's journey to rediscover herself after divorce"],
                    ["The transformation of a cynical journalist through unexpected encounters"],
                    ["μž‘μ€ μ„œμ μ„ μš΄μ˜ν•˜λŠ” λ…ΈλΆ€λΆ€μ˜ λ§ˆμ§€λ§‰ 1λ…„"],
                    ["AI μ‹œλŒ€μ— 일자리λ₯Ό μžƒμ€ λ²ˆμ—­κ°€μ˜ μƒˆλ‘œμš΄ 도전"]
                ],
                inputs=query_input,
                label="πŸ’‘ 주제 μ˜ˆμ‹œ"
            )
        
        # 이벀트 ν•Έλ“€λŸ¬
        def refresh_sessions():
            try:
                sessions = get_active_sessions("Korean")
                return gr.update(choices=sessions)
            except Exception as e:
                logger.error(f"Error refreshing sessions: {str(e)}")
                return gr.update(choices=[])
        
        def handle_auto_recover(language):
            session_id, message = auto_recover_session(language)
            return session_id, message
        
        # 이벀트 μ—°κ²°
        submit_btn.click(
            fn=process_query,
            inputs=[query_input, language_select, current_session_id],
            outputs=[stages_display, novel_output, status_text, current_session_id]
        )
        
        novel_output.change(
            fn=lambda x: x,
            inputs=[novel_output],
            outputs=[novel_text_state]
        )
        
        resume_btn.click(
            fn=lambda x: x.split("...")[0] if x and "..." in x else 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, current_session_id]
        )
        
        auto_recover_btn.click(
            fn=handle_auto_recover,
            inputs=[language_select],
            outputs=[current_session_id, status_text]
        ).then(
            fn=resume_session,
            inputs=[current_session_id, language_select],
            outputs=[stages_display, novel_output, status_text, current_session_id]
        )
        
        refresh_btn.click(
            fn=refresh_sessions,
            outputs=[session_dropdown]
        )
        
        clear_btn.click(
            fn=lambda: ("", "", "πŸ”„ μ€€λΉ„ μ™„λ£Œ", "", None),
            outputs=[stages_display, novel_output, status_text, novel_text_state, current_session_id]
        )
        
        def handle_download(format_type, language, session_id, novel_text):
            if not session_id or not novel_text:
                return gr.update(visible=False)
            
            file_path = download_novel(novel_text, format_type, language, session_id)
            if file_path:
                return gr.update(value=file_path, visible=True)
            else:
                return gr.update(visible=False)
        
        download_btn.click(
            fn=handle_download,
            inputs=[format_select, language_select, current_session_id, novel_text_state],
            outputs=[download_file]
        )
        
        # μ‹œμž‘ μ‹œ μ„Έμ…˜ λ‘œλ“œ
        interface.load(
            fn=refresh_sessions,
            outputs=[session_dropdown]
        )
    
    return interface


# 메인 μ‹€ν–‰
if __name__ == "__main__":
    logger.info("AI μ§„ν–‰ν˜• μž₯νŽΈμ†Œμ„€ 생성 μ‹œμŠ€ν…œ μ‹œμž‘...")
    logger.info("=" * 60)
    
    # ν™˜κ²½ 확인
    logger.info(f"API μ—”λ“œν¬μΈνŠΈ: {API_URL}")
    logger.info(f"λͺ©ν‘œ λΆ„λŸ‰: {TARGET_WORDS:,}단어")
    logger.info(f"μž‘κ°€λ‹Ή μ΅œμ†Œ λΆ„λŸ‰: {MIN_WORDS_PER_WRITER:,}단어")
    
    if BRAVE_SEARCH_API_KEY:
        logger.info("μ›Ή 검색이 ν™œμ„±ν™”λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
    else:
        logger.warning("μ›Ή 검색이 λΉ„ν™œμ„±ν™”λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
    
    if DOCX_AVAILABLE:
        logger.info("DOCX 내보내기가 ν™œμ„±ν™”λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
    else:
        logger.warning("DOCX 내보내기가 λΉ„ν™œμ„±ν™”λ˜μ—ˆμŠ΅λ‹ˆλ‹€.")
    
    logger.info("=" * 60)
    
    # λ°μ΄ν„°λ² μ΄μŠ€ μ΄ˆκΈ°ν™”
    logger.info("λ°μ΄ν„°λ² μ΄μŠ€ μ΄ˆκΈ°ν™” 쀑...")
    NovelDatabase.init_db()
    logger.info("λ°μ΄ν„°λ² μ΄μŠ€ μ΄ˆκΈ°ν™” μ™„λ£Œ.")
    
    # μΈν„°νŽ˜μ΄μŠ€ 생성 및 μ‹€ν–‰
    interface = create_interface()
    
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=True
    )