File size: 101,422 Bytes
625078a
 
 
 
 
 
0456cf4
625078a
 
 
 
f1a53c8
 
 
 
0456cf4
c6411d9
625078a
aa177b7
 
625078a
 
aa177b7
6604393
 
 
 
 
0456cf4
 
6604393
 
 
 
 
aa177b7
81b2ada
a81bc54
6604393
 
5ae25f1
cf2c020
 
 
 
6604393
aa177b7
bcc5d0c
 
aa177b7
81b2ada
a81bc54
 
 
aa177b7
6604393
 
cf2c020
 
 
 
 
 
 
 
 
 
 
 
 
 
5ae25f1
cf2c020
 
 
bcc5d0c
 
cf2c020
bcc5d0c
 
cf2c020
bcc5d0c
cf2c020
bcc5d0c
 
5ae25f1
0456cf4
bcc5d0c
81b2ada
c6411d9
aa177b7
c6411d9
cf2c020
 
c6411d9
cf2c020
 
 
 
 
c6411d9
cf2c020
 
 
 
 
 
 
 
c6411d9
bcc5d0c
cf2c020
 
 
 
 
 
bcc5d0c
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc5d0c
aa177b7
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf2c020
 
c6411d9
cf2c020
 
 
 
 
 
5ae25f1
 
 
 
 
 
0456cf4
cf2c020
 
 
5ae25f1
cf2c020
0456cf4
cf2c020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0456cf4
cf2c020
 
 
 
 
 
 
0456cf4
 
cf2c020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0456cf4
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf2c020
1c836be
cf2c020
 
 
 
 
 
 
 
5ae25f1
 
 
 
 
 
cf2c020
 
 
 
5ae25f1
cf2c020
 
 
5ae25f1
0456cf4
cf2c020
5ae25f1
cf2c020
 
 
5ae25f1
cf2c020
 
5ae25f1
cf2c020
 
 
5ae25f1
cf2c020
 
5ae25f1
cf2c020
 
 
5ae25f1
cf2c020
 
5ae25f1
cf2c020
 
 
5ae25f1
1c836be
5ae25f1
1c836be
 
 
5ae25f1
 
cf2c020
 
 
 
 
 
5ae25f1
 
 
 
 
 
 
 
 
cf2c020
 
1c836be
5ae25f1
 
 
 
 
 
 
a81bc54
c6411d9
f1a53c8
0456cf4
f1a53c8
 
 
81b2ada
f1a53c8
0456cf4
5ae25f1
f1a53c8
 
 
 
 
81b2ada
 
f1a53c8
 
c6411d9
0456cf4
cf2c020
 
f1a53c8
 
0456cf4
f1a53c8
 
 
 
 
 
 
 
61ae973
f1a53c8
cf2c020
5ae25f1
81b2ada
596c9c5
81b2ada
 
f1a53c8
 
0456cf4
c6411d9
cf2c020
0456cf4
 
cf2c020
 
 
 
a81bc54
 
 
 
0456cf4
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a53c8
aa177b7
0456cf4
f1a53c8
 
 
 
81b2ada
f1a53c8
 
 
 
 
aa177b7
f1a53c8
 
 
 
aa177b7
 
 
 
f1a53c8
 
aa177b7
f1a53c8
aa177b7
 
5ae25f1
61ae973
f1a53c8
 
 
5ae25f1
 
aa177b7
5ae25f1
 
 
cf2c020
 
 
 
 
 
 
 
 
 
 
 
 
 
f1a53c8
aa177b7
f1a53c8
0456cf4
cf2c020
f1a53c8
0456cf4
 
cf2c020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0456cf4
cf2c020
 
0456cf4
aa177b7
cf2c020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ae25f1
 
 
 
 
cf2c020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ae25f1
 
 
 
 
 
 
 
 
 
cf2c020
 
 
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
61ae973
0456cf4
61ae973
0456cf4
bcc5d0c
aa177b7
f1a53c8
 
 
aa177b7
 
 
f1a53c8
0456cf4
f1a53c8
aa177b7
0456cf4
 
aa177b7
f1a53c8
aa177b7
f1a53c8
 
 
aa177b7
cf2c020
aa177b7
 
c6411d9
f1a53c8
0456cf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf2c020
 
625078a
 
 
 
cf2c020
a81bc54
bcc5d0c
f1a53c8
aa177b7
625078a
aa177b7
625078a
cf2c020
aa177b7
cf2c020
aa177b7
 
5ae25f1
 
1c836be
5ae25f1
 
 
 
1c836be
 
5ae25f1
 
 
 
 
 
 
1c836be
aa177b7
5ae25f1
d313101
0456cf4
cf2c020
0456cf4
 
 
 
cf2c020
 
 
 
 
 
5ae25f1
cf2c020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ae25f1
cf2c020
 
 
 
5ae25f1
cf2c020
 
5ae25f1
cf2c020
0456cf4
cf2c020
 
 
0456cf4
5ae25f1
 
 
 
 
 
cf2c020
 
 
 
 
5ae25f1
0456cf4
cf2c020
 
 
 
0456cf4
cf2c020
0456cf4
5ae25f1
cf2c020
0456cf4
cf2c020
0456cf4
cf2c020
 
0456cf4
cf2c020
 
 
 
 
 
5ae25f1
cf2c020
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ae25f1
cf2c020
 
 
 
5ae25f1
cf2c020
 
5ae25f1
cf2c020
0456cf4
cf2c020
 
 
 
5ae25f1
 
 
 
 
 
cf2c020
 
 
 
 
5ae25f1
0456cf4
cf2c020
 
 
 
 
 
aa177b7
1c836be
0456cf4
aa177b7
 
cf2c020
aa177b7
cf2c020
 
625078a
0456cf4
 
 
 
 
cf2c020
 
 
 
 
 
 
 
 
 
 
5ae25f1
0456cf4
cf2c020
 
 
 
0456cf4
cf2c020
 
 
0456cf4
5ae25f1
 
 
 
cf2c020
 
 
0456cf4
 
cf2c020
 
 
0456cf4
 
 
 
 
 
cf2c020
0456cf4
cf2c020
 
 
 
0456cf4
cf2c020
 
 
 
5ae25f1
0456cf4
cf2c020
 
 
 
 
 
 
 
 
5ae25f1
 
 
 
cf2c020
 
 
0456cf4
 
 
aa177b7
0456cf4
 
5ae25f1
 
 
 
 
cf2c020
 
 
625078a
aa177b7
cf2c020
 
0456cf4
cf2c020
0456cf4
 
cf2c020
 
 
 
 
 
 
 
0456cf4
5ae25f1
 
 
0456cf4
 
cf2c020
 
 
0456cf4
cf2c020
 
 
 
5ae25f1
0456cf4
cf2c020
 
 
 
5ae25f1
0456cf4
cf2c020
 
 
 
0456cf4
cf2c020
 
 
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0456cf4
cf2c020
 
 
 
5ae25f1
 
0456cf4
cf2c020
0456cf4
cf2c020
 
 
 
0456cf4
 
cf2c020
 
 
 
 
 
 
 
0456cf4
5ae25f1
 
 
0456cf4
 
cf2c020
 
 
0456cf4
cf2c020
 
 
 
5ae25f1
0456cf4
cf2c020
 
 
 
5ae25f1
0456cf4
cf2c020
 
 
 
0456cf4
cf2c020
 
 
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0456cf4
cf2c020
 
 
5ae25f1
 
 
0456cf4
cf2c020
aa177b7
bcc5d0c
0456cf4
625078a
5ae25f1
 
 
 
 
 
cf2c020
 
5ae25f1
 
 
 
 
 
 
 
cf2c020
 
5ae25f1
625078a
0456cf4
625078a
cf2c020
 
 
 
 
5ae25f1
 
 
0456cf4
cf2c020
 
5ae25f1
cf2c020
5ae25f1
 
 
 
 
cf2c020
5ae25f1
 
 
 
 
625078a
5ae25f1
 
 
 
0456cf4
cf2c020
 
 
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
cf2c020
5ae25f1
 
cf2c020
5ae25f1
cf2c020
 
0456cf4
cf2c020
0456cf4
cf2c020
 
0456cf4
5ae25f1
 
 
cf2c020
 
 
5ae25f1
cf2c020
5ae25f1
 
 
 
 
cf2c020
5ae25f1
 
 
 
 
cf2c020
5ae25f1
 
 
 
cf2c020
 
 
 
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
cf2c020
5ae25f1
 
cf2c020
5ae25f1
cf2c020
0456cf4
5ae25f1
0456cf4
5ae25f1
 
 
 
 
0456cf4
 
 
aa177b7
cf2c020
0456cf4
aa177b7
cf2c020
 
 
 
 
5ae25f1
 
 
 
 
 
 
 
 
0456cf4
cf2c020
0456cf4
aa177b7
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf2c020
5ae25f1
 
 
 
0456cf4
cf2c020
 
 
aa177b7
cf2c020
 
aa177b7
cf2c020
0456cf4
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf2c020
 
5ae25f1
 
 
 
 
 
 
 
 
 
0456cf4
 
 
5ae25f1
 
 
1c836be
5ae25f1
1c836be
 
 
 
 
 
 
 
 
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c836be
 
5ae25f1
 
 
 
 
 
 
 
 
 
1c836be
 
 
5ae25f1
 
 
 
 
 
aa177b7
5ae25f1
aa177b7
5ae25f1
 
 
 
 
 
aa177b7
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
625078a
5ae25f1
 
 
 
 
 
 
 
cf2c020
5ae25f1
 
 
cf2c020
5ae25f1
 
 
 
 
 
 
 
 
cf2c020
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf2c020
5ae25f1
 
 
cf2c020
5ae25f1
 
 
 
 
 
 
 
 
cf2c020
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
0456cf4
5ae25f1
 
0456cf4
 
 
 
 
 
 
 
 
cf2c020
 
 
 
 
5ae25f1
 
 
 
0456cf4
cf2c020
aa177b7
cf2c020
5ae25f1
 
 
 
 
 
 
 
 
 
aa177b7
cf2c020
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
0456cf4
cf2c020
5ae25f1
 
 
 
 
 
 
 
 
 
cf2c020
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf2c020
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
cf2c020
5ae25f1
 
 
 
 
 
 
 
625078a
c6411d9
aa177b7
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6411d9
aa177b7
5ae25f1
 
 
 
f1a53c8
aa177b7
5ae25f1
 
 
 
 
 
c6411d9
bcc5d0c
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
 
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
0456cf4
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa177b7
 
5ae25f1
 
 
 
 
625078a
c6411d9
cf2c020
625078a
 
5ae25f1
 
625078a
 
 
5ae25f1
 
 
 
 
 
 
 
0456cf4
 
cf2c020
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
625078a
 
 
5ae25f1
 
 
 
 
 
625078a
 
f1a53c8
5ae25f1
 
 
 
 
 
 
f1a53c8
 
7651773
5ae25f1
 
 
 
 
 
6d93c4e
 
7651773
5ae25f1
 
 
 
 
 
6d93c4e
 
7651773
5ae25f1
 
 
 
 
0456cf4
 
cf2c020
 
5ae25f1
 
 
 
 
0456cf4
 
cf2c020
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d93c4e
6604393
 
c6411d9
bcc5d0c
625078a
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
625078a
c6411d9
bcc5d0c
625078a
5ae25f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
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_v6.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)
] + [
    ("editor", "βœ‚οΈ νŽΈμ§‘μž: 반볡 제거 및 μ„œμ‚¬ μž¬κ΅¬μ„±"),
    ("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

@dataclass
class CharacterConsistency:
    """캐릭터 일관성 관리"""
    primary_names: Dict[str, str] = field(default_factory=dict)  # role -> canonical name
    aliases: Dict[str, List[str]] = field(default_factory=dict)  # canonical -> aliases
    name_history: List[Tuple[int, str, str]] = field(default_factory=list)  # (phase, role, used_name)
    
    def validate_name(self, phase: int, role: str, name: str) -> bool:
        """이름 일관성 검증"""
        if role in self.primary_names:
            canonical = self.primary_names[role]
            if name != canonical and name not in self.aliases.get(canonical, []):
                return False
        return True
    
    def register_name(self, phase: int, role: str, name: str):
        """이름 등둝"""
        if role not in self.primary_names:
            self.primary_names[role] = name
        self.name_history.append((phase, role, name))


# --- 핡심 둜직 클래슀 ---
class ContentDeduplicator:
    """쀑볡 μ½˜ν…μΈ  감지 및 제거"""
    def __init__(self):
        self.seen_paragraphs = set()
        self.seen_key_phrases = set()
        self.similarity_threshold = 0.85
        
    def check_similarity(self, text1: str, text2: str) -> float:
        """두 ν…μŠ€νŠΈμ˜ μœ μ‚¬λ„ μΈ‘μ •"""
        # κ°„λ‹¨ν•œ Jaccard μœ μ‚¬λ„ κ΅¬ν˜„
        words1 = set(text1.lower().split())
        words2 = set(text2.lower().split())
        
        intersection = words1.intersection(words2)
        union = words1.union(words2)
        
        return len(intersection) / len(union) if union else 0
    
    def extract_key_phrases(self, text: str) -> List[str]:
        """핡심 문ꡬ μΆ”μΆœ"""
        # 20자 μ΄μƒμ˜ λ¬Έμž₯듀을 핡심 문ꡬ둜 κ°„μ£Ό
        sentences = [s.strip() for s in re.split(r'[.!?]', text) if len(s.strip()) > 20]
        return sentences[:5]  # μƒμœ„ 5개만
    
    def is_duplicate(self, paragraph: str) -> bool:
        """쀑볡 문단 감지"""
        # 핡심 문ꡬ 체크
        key_phrases = self.extract_key_phrases(paragraph)
        for phrase in key_phrases:
            if phrase in self.seen_key_phrases:
                return True
                
        # 전체 문단 μœ μ‚¬λ„ 체크
        for seen in self.seen_paragraphs:
            if self.check_similarity(paragraph, seen) > self.similarity_threshold:
                return True
                
        # 쀑볡이 μ•„λ‹ˆλ©΄ μ €μž₯
        self.seen_paragraphs.add(paragraph)
        self.seen_key_phrases.update(key_phrases)
        return False
    
    def get_used_elements(self) -> List[str]:
        """μ‚¬μš©λœ 핡심 μš”μ†Œ λ°˜ν™˜"""
        return list(self.seen_key_phrases)[:10]  # 졜근 10개
    
    def count_repetitions(self, content: str) -> int:
        """ν…μŠ€νŠΈ λ‚΄μ˜ 반볡 횟수 계산"""
        paragraphs = content.split('\n\n')
        repetitions = 0
        
        for i, para1 in enumerate(paragraphs):
            for para2 in paragraphs[i+1:]:
                if self.check_similarity(para1, para2) > 0.7:
                    repetitions += 1
                    
        return repetitions


class ProgressionMonitor:
    """μ‹€μ‹œκ°„ μ„œμ‚¬ μ§„ν–‰ λͺ¨λ‹ˆν„°λ§"""
    def __init__(self):
        self.phase_keywords = {}
        self.locations = set()
        self.characters = set()
        
    def count_new_characters(self, content: str, phase: int) -> int:
        """μƒˆλ‘œμš΄ 인물 λ“±μž₯ 횟수"""
        # κ°„λ‹¨ν•œ 고유λͺ…사 μΆ”μΆœ (λŒ€λ¬Έμžλ‘œ μ‹œμž‘ν•˜λŠ” 단어)
        potential_names = re.findall(r'\b[A-Zκ°€-힣][a-zκ°€-힣]+\b', content)
        new_chars = set(potential_names) - self.characters
        self.characters.update(new_chars)
        return len(new_chars)
    
    def count_new_locations(self, content: str, phase: int) -> int:
        """μƒˆλ‘œμš΄ μž₯μ†Œ λ“±μž₯ 횟수"""
        # μž₯μ†Œ κ΄€λ ¨ ν‚€μ›Œλ“œ
        location_markers = ['μ—μ„œ', '으둜', '에', '의', 'at', 'in', 'to']
        new_locs = 0
        
        for marker in location_markers:
            matches = re.findall(rf'(\S+)\s*{marker}', content)
            for match in matches:
                if match not in self.locations and len(match) > 2:
                    self.locations.add(match)
                    new_locs += 1
                    
        return new_locs
    
    def calculate_content_difference(self, current_phase: int, content: str, previous_content: str) -> float:
        """이전 λ‹¨κ³„μ™€μ˜ λ‚΄μš© 차이 λΉ„μœ¨"""
        if not previous_content:
            return 1.0
            
        dedup = ContentDeduplicator()
        return 1.0 - dedup.check_similarity(content, previous_content)
    
    def count_repetitions(self, content: str) -> int:
        """반볡 횟수 계산"""
        paragraphs = content.split('\n\n')
        repetitions = 0
        
        for i, para1 in enumerate(paragraphs):
            for para2 in paragraphs[i+1:]:
                similarity = ContentDeduplicator().check_similarity(para1, para2)
                if similarity > 0.7:
                    repetitions += 1
                    
        return repetitions
    
    def calculate_progression_score(self, current_phase: int, content: str, previous_content: str = "") -> Dict[str, float]:
        """진행도 점수 계산"""
        
        scores = {
            "new_elements": 0.0,  # μƒˆλ‘œμš΄ μš”μ†Œ
            "character_growth": 0.0,  # 인물 μ„±μž₯
            "plot_advancement": 0.0,  # ν”Œλ‘― μ§„μ „
            "no_repetition": 0.0  # 반볡 μ—†μŒ
        }
        
        # μƒˆλ‘œμš΄ μš”μ†Œ 체크
        new_characters = self.count_new_characters(content, current_phase)
        new_locations = self.count_new_locations(content, current_phase)
        scores["new_elements"] = min(10, (new_characters * 3 + new_locations * 2))
        
        # μ„±μž₯ κ΄€λ ¨ ν‚€μ›Œλ“œ
        growth_keywords = ["κΉ¨λ‹¬μ•˜λ‹€", "μ΄μ œλŠ”", "λ‹¬λΌμ‘Œλ‹€", "μƒˆλ‘­κ²Œ", "λΉ„λ‘œμ†Œ", "λ³€ν–ˆλ‹€", "더 이상"]
        growth_count = sum(1 for k in growth_keywords if k in content)
        scores["character_growth"] = min(10, growth_count * 2)
        
        # ν”Œλ‘― μ§„μ „ (이전 λ‹¨κ³„μ™€μ˜ 차이)
        if current_phase > 1 and previous_content:
            diff_ratio = self.calculate_content_difference(current_phase, content, previous_content)
            scores["plot_advancement"] = min(10, diff_ratio * 10)
        else:
            scores["plot_advancement"] = 8.0  # 첫 λ‹¨κ³„λŠ” κΈ°λ³Έ 점수
        
        # 반볡 체크 (μ—­μ‚°)
        repetition_count = self.count_repetitions(content)
        scores["no_repetition"] = max(0, 10 - repetition_count * 2)
        
        return scores


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] = []
        self.philosophical_insights: List[str] = []  # 철학적 톡찰 좔적
        self.literary_devices: Dict[int, List[str]] = {}  # 문학적 기법 μ‚¬μš© 좔적
        self.character_consistency = CharacterConsistency()  # 캐릭터 일관성 μΆ”κ°€
        self.content_deduplicator = ContentDeduplicator()  # 쀑볡 감지기 μΆ”κ°€
        self.progression_monitor = ProgressionMonitor()  # 진행도 λͺ¨λ‹ˆν„° μΆ”κ°€
        self.used_expressions: Set[str] = set()  # μ‚¬μš©λœ ν‘œν˜„ 좔적
        
    def register_character_arc(self, name: str, initial_state: Dict[str, Any]):
        """캐릭터 아크 등둝"""
        self.character_arcs[name] = CharacterArc(name=name, initial_state=initial_state)
        self.character_consistency.register_name(0, "protagonist", name)
        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)}")
            
        # 4. 철학적 깊이 확인
        if len(self.philosophical_insights) < current_phase // 2:
            issues.append("철학적 μ„±μ°°κ³Ό 인간에 λŒ€ν•œ 톡찰이 λΆ€μ‘±ν•©λ‹ˆλ‹€")
            
        # 5. 문학적 기법 λ‹€μ–‘μ„±
        unique_devices = set()
        for devices in self.literary_devices.values():
            unique_devices.update(devices)
        if len(unique_devices) < 5:
            issues.append("문학적 기법이 λ‹¨μ‘°λ‘­μŠ΅λ‹ˆλ‹€. 더 λ‹€μ–‘ν•œ ν‘œν˜„ 기법이 ν•„μš”ν•©λ‹ˆλ‹€")
            
        # 6. 캐릭터 이름 일관성
        name_issues = []
        for phase, role, name in self.character_consistency.name_history:
            if not self.character_consistency.validate_name(phase, role, name):
                name_issues.append(f"Phase {phase}: {role} 이름 뢈일치 ({name})")
        if name_issues:
            issues.extend(name_issues)
            
        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]}")
            
        # μ‚¬μš©λœ ν‘œν˜„ λͺ©λ‘
        if self.used_expressions:
            requirements.append("\n❌ λ‹€μŒ ν‘œν˜„/상황은 이미 μ‚¬μš©λ¨ (μž¬μ‚¬μš© κΈˆμ§€):")
            for expr in list(self.used_expressions)[-10:]:  # 졜근 10개
                requirements.append(f"- {expr[:50]}...")
            
        # 단계별 특수 μš”κ΅¬μ‚¬ν•­
        phase_name = NARRATIVE_PHASES[phase-1] if phase <= 10 else "μˆ˜μ •"
        
        if "λ„μž…" in phase_name:
            requirements.append("\nβœ… ν•„μˆ˜ 포함:")
            requirements.append("- μΌμƒμ˜ 균열을 λ³΄μ—¬μ£Όλ˜, 큰 사건이 μ•„λ‹Œ λ―Έλ¬˜ν•œ λ³€ν™”λ‘œ μ‹œμž‘")
            requirements.append("- μ£Όμš” μΈλ¬Όλ“€μ˜ 초기 μƒνƒœμ™€ 관계 μ„€μ •")
            requirements.append("- 핡심 상징 λ„μž… (μžμ—°μŠ€λŸ½κ²Œ)")
            requirements.append("- 주인곡 이름 λͺ…ν™•νžˆ μ„€μ •")
            
        elif "λ°œμ „" in phase_name:
            requirements.append("\nβœ… ν•„μˆ˜ 포함:")
            requirements.append("- 이전 λ‹¨κ³„μ˜ κ· μ—΄/κ°ˆλ“±μ΄ κ΅¬μ²΄ν™”λ˜κ³  심화")
            requirements.append("- μƒˆλ‘œμš΄ μ‚¬κ±΄μ΄λ‚˜ 인식이 μΆ”κ°€λ˜μ–΄ λ³΅μž‘μ„± 증가")
            requirements.append("- 인물 κ°„ κ΄€κ³„μ˜ λ―Έλ¬˜ν•œ λ³€ν™”")
            requirements.append("- μƒˆλ‘œμš΄ κ³΅κ°„μ΄λ‚˜ μ‹œκ°„λŒ€ 탐색")
            
        elif "μ ˆμ •" in phase_name:
            requirements.append("\nβœ… ν•„μˆ˜ 포함:")
            requirements.append("- μΆ•μ λœ κ°ˆλ“±μ΄ μž„κ³„μ μ— 도달")
            requirements.append("- 인물의 내적 μ„ νƒμ΄λ‚˜ μΈμ‹μ˜ μ „ν™˜μ ")
            requirements.append("- μƒμ§•μ˜ μ˜λ―Έκ°€ μ „λ³΅λ˜κ±°λ‚˜ 심화")
            requirements.append("- μ΄μ „κ³ΌλŠ” λ‹€λ₯Έ ν–‰λ™μ΄λ‚˜ κ²°μ •")
            
        elif "ν•˜κ°•" in phase_name:
            requirements.append("\nβœ… ν•„μˆ˜ 포함:")
            requirements.append("- μ ˆμ •μ˜ μ—¬νŒŒμ™€ 그둜 μΈν•œ λ³€ν™”")
            requirements.append("- μƒˆλ‘œμš΄ κ· ν˜•μ μ„ μ°Ύμ•„κ°€λŠ” κ³Όμ •")
            requirements.append("- μΈλ¬Όλ“€μ˜ λ³€ν™”λœ 관계와 인식")
            requirements.append("- νšŒλ³΅μ΄λ‚˜ μƒμ‹€μ˜ ꡬ체적 λ¬˜μ‚¬")
            
        elif "결말" in phase_name:
            requirements.append("\nβœ… ν•„μˆ˜ 포함:")
            requirements.append("- λ³€ν™”λœ μΌμƒμ˜ λͺ¨μŠ΅")
            requirements.append("- ν•΄κ²°λ˜μ§€ μ•Šμ€ μ§ˆλ¬Έλ“€")
            requirements.append("- μ—¬μš΄κ³Ό μ„±μ°°μ˜ μ—¬μ§€")
            requirements.append("- 처음과 λŒ€λΉ„λ˜λŠ” λ§ˆμ§€λ§‰")
        
        # 철학·인간애 κ°•ν™” 체크리슀트
        requirements.append("\nπŸ“Œ ν•„μˆ˜ 포함 μš”μ†Œ:")
        requirements.append("- 쑴재의 μ˜λ―Έλ‚˜ μ‚Άμ˜ λ³Έμ§ˆμ— λŒ€ν•œ 성찰이 λ‹΄κΈ΄ 1문단 이상")
        requirements.append("- νƒ€μΈμ˜ 고톡에 λŒ€ν•œ κ³΅κ°μ΄λ‚˜ 연민을 λ³΄μ—¬μ£ΌλŠ” ꡬ체적 μž₯λ©΄ 1개 이상")
        requirements.append("- '보여주기(showing)' 기법: 직접 μ„€λͺ… λŒ€μ‹  감각적 λ¬˜μ‚¬μ™€ ν–‰λ™μœΌλ‘œ ν‘œν˜„")
        requirements.append("- 이 λ‹¨κ³„λ§Œμ˜ λ…νŠΉν•œ 문학적 μž₯μΉ˜λ‚˜ μ€μœ  1개 이상")
            
        # 반볡 λ°©μ§€ μš”κ΅¬μ‚¬ν•­
        requirements.append("\n⚠️ μ ˆλŒ€ κΈˆμ§€μ‚¬ν•­:")
        requirements.append("- 이전 단계와 λ™μΌν•œ μ‚¬κ±΄μ΄λ‚˜ κ°ˆλ“± 반볡")
        requirements.append("- 인물이 같은 μƒκ°μ΄λ‚˜ 감정에 머무λ₯΄κΈ°")
        requirements.append("- ν”Œλ‘―μ΄ μ œμžλ¦¬κ±ΈμŒν•˜κΈ°")
        requirements.append("- '~을 λŠκΌˆλ‹€', '~μ˜€λ‹€'와 같은 직접적 μ„€λͺ…")
        requirements.append("- 이미 얻은 κΉ¨λ‹¬μŒμ„ 잊고 λ‹€μ‹œ μ‹œμž‘ν•˜κΈ°")
        
        # μ§„ν–‰ 체크리슀트
        requirements.append("\nβ˜‘οΈ μ§„ν–‰ 체크리슀트:")
        requirements.append("β–‘ 이전 λ‹¨κ³„μ˜ κ²°κ³Όκ°€ 이번 λ‹¨κ³„μ˜ 원인이 λ˜λŠ”κ°€?")
        requirements.append("β–‘ 주인곡의 내적 λ³€ν™”κ°€ ꡬ체적으둜 λ“œλŸ¬λ‚˜λŠ”κ°€?")
        requirements.append("β–‘ ν”Œλ‘―μ΄ μ‹€μ œλ‘œ μ „μ§„ν•˜λŠ”κ°€?")
        requirements.append("β–‘ μƒˆλ‘œμš΄ 정보/사건이 μΆ”κ°€λ˜λŠ”κ°€?")
        
        return "\n".join(requirements)
    
    def extract_used_elements(self, content: str):
        """μ‚¬μš©λœ 핡심 ν‘œν˜„ μΆ”μΆœ 및 μ €μž₯"""
        # 20자 μ΄μƒμ˜ νŠΉμ§•μ μΈ λ¬Έμž₯λ“€ μΆ”μΆœ
        sentences = re.findall(r'[^.!?]+[.!?]', content)
        for sent in sentences:
            if len(sent) > 20 and len(sent) < 100:
                self.used_expressions.add(sent.strip())


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,
                    repetition_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)
                )
            ''')
            
            # μƒˆλ‘œμš΄ ν…Œμ΄λΈ”: 쀑볡 감지 기둝
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS duplicate_detection (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    session_id TEXT NOT NULL,
                    phase INTEGER NOT NULL,
                    duplicate_content TEXT,
                    original_phase INTEGER,
                    similarity_score REAL,
                    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, repetition_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, repetition_score)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON CONFLICT(session_id, stage_number)
                DO UPDATE SET content=?, word_count=?, status=?, stage_name=?, progression_score=?, repetition_score=?, updated_at=datetime('now')
            ''', (session_id, stage_number, stage_name, role, content, word_count, status, progression_score, repetition_score,
                  content, word_count, status, stage_name, progression_score, repetition_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,
                'philosophical_insights': tracker.philosophical_insights,
                'literary_devices': tracker.literary_devices,
                'character_consistency': asdict(tracker.character_consistency),
                'used_expressions': list(tracker.used_expressions)
            })
            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', [])
                tracker.philosophical_insights = data.get('philosophical_insights', [])
                tracker.literary_devices = data.get('literary_devices', {})
                
                # 캐릭터 일관성 볡원
                if 'character_consistency' in data:
                    tracker.character_consistency = CharacterConsistency(**data['character_consistency'])
                    
                # μ‚¬μš©λœ ν‘œν˜„ 볡원
                if 'used_expressions' in data:
                    tracker.used_expressions = set(data['used_expressions'])
                
                return tracker
        return None

    @staticmethod
    def save_duplicate_detection(session_id: str, phase: int, duplicate_content: str, 
                                original_phase: int, similarity_score: float):
        """쀑볡 감지 기둝 μ €μž₯"""
        with NovelDatabase.get_db() as conn:
            conn.cursor().execute('''
                INSERT INTO duplicate_detection 
                (session_id, phase, duplicate_content, original_phase, similarity_score)
                VALUES (?, ?, ?, ?, ?)
            ''', (session_id, phase, duplicate_content, original_phase, similarity_score))
            conn.commit()

    @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:
            # 철학적 ν‚€μ›Œλ“œ μΆ”κ°€ (쿼리 길이 μ œν•œ)
            short_query = user_query[:50] if len(user_query) > 50 else user_query
            queries = [
                f"{short_query} 철학적 의미",  # 철학적 관점
                f"인간 쑴재 의미 {short_query}",  # 싀쑴적 주제
                f"{short_query} λ¬Έν•™ μž‘ν’ˆ",
                f"{short_query} ν˜„λŒ€ μ‚¬νšŒ"
            ]
            for q in queries[:3]:  # 3κ°œκΉŒμ§€λ§Œ 검색
                try:
                    results = self.web_search.search(q, count=2, language=language)
                    if results:
                        search_results_str += self.web_search.extract_relevant_info(results) + "\n"
                except Exception as e:
                    logger.warning(f"검색 쿼리 μ‹€νŒ¨: {q[:50]}... - {str(e)}")
                    continue
    
        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. **μ‚¬νšŒμ  λ§₯락**
   - 개인의 λ¬Έμ œκ°€ μ‚¬νšŒ ꡬ쑰와 μ—°κ²°
   - ꡬ체적인 ν•œκ΅­ μ‚¬νšŒμ˜ ν˜„μ‹€ 반영

6. **철학적 κΉŠμ΄μ™€ 인간애**
   - 보편적 인간 쑰건에 λŒ€ν•œ μ„±μ°°
   - νƒ€μΈμ˜ 고톡에 λŒ€ν•œ 곡감과 μ—°λ―Ό
   - 싀쑴적 질문과 그에 λŒ€ν•œ 탐ꡬ
   - "μ™œ μ‚΄μ•„μ•Ό ν•˜λŠ”κ°€"에 λŒ€ν•œ λ‚˜λ¦„μ˜ λ‹΅

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

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

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

            "English": f"""You are a Nobel Prize-winning 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
   - Protagonist name clearly established from beginning
   
   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
   - Specify how characters change in each phase

3. **Plot Threads** (2-3)
   - Main plot: Core conflict throughout
   - Subplots: Connected and deepening themes
   - Specify which phase each plot starts/develops/resolves

4. **Symbolic Evolution**
   - 1-2 core symbols (like 'frog eggs' - intense and multilayered)
   - Meaning transforms across phases

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

6. **Philosophical Depth and Humanity**
   - Reflection on universal human condition
   - Empathy and compassion for others' suffering
   - Existential questions and exploration
   - Personal answer to "why should we live?"

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

**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λ‹¨μ–΄μ˜ 밀도λ₯Ό κ°€μ§ˆ 수 μžˆλŠ”κ°€?

5. **철학적 깊이**
   - 인간 μ‘΄μž¬μ— λŒ€ν•œ 톡찰이 κ³„νšλ˜μ–΄ μžˆλŠ”κ°€?
   - λ‹¨μˆœν•œ 사건 λ‚˜μ—΄μ΄ μ•„λ‹Œ 의미의 탐ꡬ가 μžˆλŠ”κ°€?

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

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

            "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?
   - Consistent protagonist naming?

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?

5. **Philosophical Depth**
   - Insights into human existence planned?
   - Exploration of meaning, not just events?

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

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

    def create_writer_prompt_enhanced(self, writer_number: int, director_plan: str, 
                                    previous_content: str, phase_requirements: str,
                                    narrative_summary: str, language: str,
                                    used_elements: List[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}

**❌ μ ˆλŒ€ μ‚¬μš© κΈˆμ§€ ν‘œν˜„/상황 (이미 μ‚¬μš©λ¨):**
{chr(10).join(f"- {elem[:80]}..." for elem in used_elements[-15:])}

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

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

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

3. **인물의 λ³€ν™”**
   - 이 λ‹¨κ³„μ—μ„œ 인물이 κ²ͺλŠ” ꡬ체적 λ³€ν™” λ¬˜μ‚¬
   - λ‚΄λ©΄μ˜ λ―Έλ¬˜ν•œ 변화도 포착
   - κ΄€κ³„μ˜ μ—­ν•™ λ³€ν™” 반영
   - 이전 단계보닀 μ„±μž₯ν•œ λͺ¨μŠ΅ 보여주기

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

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

6. **문학적 기법 ν•„μˆ˜ μ‚¬μš©**
   - "보여주기(showing)" 기법: 직접 μ„€λͺ… λŒ€μ‹  감각적 λ¬˜μ‚¬
   - μ€μœ μ™€ 상징: ꡬ체적 사물을 ν†΅ν•œ 좔상적 의미 전달
   - λŒ€ν™”λ₯Ό ν†΅ν•œ 성격 λ“œλŸ¬λ‚΄κΈ°
   - 내적 독백과 μ˜μ‹μ˜ 흐름 기법
   
7. **철학적 μ„±μ°° 포함**
   - 각 λ‹¨κ³„λ§ˆλ‹€ 인간 μ‘΄μž¬μ— λŒ€ν•œ μƒˆλ‘œμš΄ 톡찰 1개 이상
   - ꡬ체적 사건 μ†μ—μ„œ 보편적 진리 발견

8. **μƒˆλ‘œμš΄ μš”μ†Œ ν•„μˆ˜**
   - μƒˆλ‘œμš΄ 인물, μž₯μ†Œ, λ˜λŠ” 상황 쀑 μ΅œμ†Œ 1개
   - 이전과 λ‹€λ₯Έ μ‹œκ°„λŒ€λ‚˜ 곡간
   - κ°ˆλ“±μ˜ μƒˆλ‘œμš΄ μΈ‘λ©΄ λ“œλŸ¬λ‚΄κΈ°

**βœ… μ§„ν–‰ 체크리슀트:**
β–‘ 이전 λ‹¨κ³„μ˜ κ²°κ³Όκ°€ λͺ…ν™•νžˆ λ“œλŸ¬λ‚˜λŠ”κ°€?
β–‘ ν”Œλ‘―μ΄ μ‹€μ œλ‘œ μ „μ§„ν•˜λŠ”κ°€?
β–‘ 인물의 λ³€ν™”κ°€ ꡬ체적인가?
β–‘ μƒˆλ‘œμš΄ μš”μ†Œκ°€ μΆ”κ°€λ˜μ—ˆλŠ”κ°€?
β–‘ λ°˜λ³΅λ˜λŠ” 상황이 μ—†λŠ”κ°€?

**μ ˆλŒ€ κΈˆμ§€:**
- 이전과 λ™μΌν•œ 상황 반볡
- μ„œμ‚¬μ˜ μ •μ²΄λ‚˜ 후퇴
- λΆ„λŸ‰ 미달 (μ΅œμ†Œ {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}

**❌ Absolutely Forbidden Expressions/Situations (already used):**
{chr(10).join(f"- {elem[:80]}..." for elem in used_elements[-15:])}

**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
   - Accumulated insights, not reset

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

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
   - Consistent protagonist naming

6. **Literary Techniques Required**
   - "Showing" not telling
   - Metaphors and symbols
   - Character through dialogue
   - Stream of consciousness
   
7. **Philosophical Reflection**
   - New insights about human existence
   - Universal truths in specific events

8. **New Elements Required**
   - At least 1 new character, location, or situation
   - Different time/space from before
   - New aspect of conflict

**βœ… Progress Checklist:**
β–‘ Clear results from previous phase?
β–‘ Plot actually advancing?
β–‘ Concrete character changes?
β–‘ New elements added?
β–‘ No repeated situations?

**Absolutely Forbidden:**
- Repeating previous situations
- Narrative stagnation/regression
- Under word count
- Direct explanations
- Forgetting gained insights

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

    def create_critic_consistency_prompt_enhanced(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)
    
    # 쀑볡 감지
        duplicates = []
        paragraphs = all_content.split('\n\n')
        for i, para1 in enumerate(paragraphs[:20]):  # 졜근 20개 문단
            for j, para2 in enumerate(paragraphs[i+1:i+21]):
                if narrative_tracker.content_deduplicator.check_similarity(para1, para2) > 0.7:
                    duplicates.append(f"문단 {i+1}κ³Ό 문단 {i+j+2} μœ μ‚¬")
        
        lang_prompts = {
            "Korean": f"""μ„œμ‚¬ μ§„ν–‰ μ „λ¬Έ λΉ„ν‰κ°€λ‘œμ„œ μž‘ν’ˆμ„ μ—„κ²©νžˆ κ²€ν† ν•˜μ„Έμš”.

**원 주제:** {user_query}

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

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

**발견된 쀑볡:**
{chr(10).join(duplicates) if duplicates else "μ—†μŒ"}

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

**ν•„μˆ˜ 검증 ν•­λͺ©:**

1. **반볡 κ²€μΆœ (μ΅œμš°μ„ )**
   - 동일/μœ μ‚¬ λ¬Έμž₯이 2회 이상 λ‚˜νƒ€λ‚˜λŠ”κ°€?
   - 같은 상황이 λ³€μ£Όλ§Œ 달리해 λ°˜λ³΅λ˜λŠ”κ°€?
   - 각 λ‹¨κ³„λ³„λ‘œ μ‹€μ œλ‘œ μƒˆλ‘œμš΄ λ‚΄μš©μ΄ μΆ”κ°€λ˜μ—ˆλŠ”κ°€?
   - "μŠ΅κΈ°κ°€ μ°¬ μ•„μΉ¨", "λ‚˜λΌλ―Έ μ–΄ν”Œ", "43λ§Œμ›" λ“± 반볡 ν‘œν˜„?

2. **μ„œμ‚¬ 진행도 μΈ‘μ •**
   - 1단계와 ν˜„μž¬ λ‹¨κ³„μ˜ 상황이 λͺ…ν™•νžˆ λ‹€λ₯Έκ°€?
   - 주인곡의 심리/인식이 λ³€ν™”ν–ˆλŠ”κ°€?
   - κ°ˆλ“±μ΄ 심화/μ „ν™˜/ν•΄κ²° λ°©ν–₯으둜 μ›€μ§μ˜€λŠ”κ°€?
   - 주인곡의 κΉ¨λ‹¬μŒμ΄ λ¦¬μ…‹λ˜μ§€ μ•Šκ³  μΆ•μ λ˜λŠ”κ°€?

3. **μ„€μ • 일관성**
   - λͺ¨λ“  캐릭터 이름이 μΌκ΄€λ˜λŠ”κ°€? (특히 주인곡)
   - μ‹œκ³΅κ°„ 섀정이 논리적인가?
   - 섀정이 쀑간에 λ°”λ€Œμ§€ μ•ŠλŠ”κ°€?

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

5. **문학적 완성도**
   - '보여주기' 기법이 잘 μ‚¬μš©λ˜κ³  μžˆλŠ”κ°€?
   - 철학적 톡찰이 μžμ—°μŠ€λŸ½κ²Œ λ…Ήμ•„μžˆλŠ”κ°€?
   - μ€μœ μ™€ 상징이 νš¨κ³Όμ μΈκ°€?

**λΆˆν•©κ²© κΈ°μ€€:**
- 2개 이상 λ‹¨κ³„μ—μ„œ μœ μ‚¬ λ‚΄μš© 발견 μ‹œ
- μ„œμ‚¬κ°€ μ œμžλ¦¬κ±ΈμŒν•˜λŠ” ꡬ간 2개 이상
- 캐릭터 이름/μ„€μ • 였λ₯˜ 발견 μ‹œ
- 주인곡 κΉ¨λ‹¬μŒμ˜ 반볡적 리셋

**μˆ˜μ • μ§€μ‹œ:**
각 μž‘κ°€μ—κ²Œ ꡬ체적인 μ§„ν–‰ λ°©ν–₯κ³Ό κΈˆμ§€μ‚¬ν•­ μ œμ‹œ.
발견된 λ°˜λ³΅μ€ λͺ¨λ‘ μ œκ±°ν•˜λ„λ‘ λͺ…μ‹œ.""",

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

**Original Theme:** {user_query}

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

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

**Detected Duplications:**
{chr(10).join(duplicates) if duplicates else "None"}

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

**Mandatory Verification Items:**

1. **Duplication Detection (Top Priority)**
   - Same/similar sentences appearing 2+ times?
   - Same situations with only variations?
   - Actually new content in each phase?
   - Repeated expressions like specific phrases?

2. **Narrative Progression Measurement**
   - Clear difference between phase 1 and current?
   - Protagonist's psychology/perception changed?
   - Conflict deepening/turning/resolving?
   - Insights accumulating, not resetting?

3. **Setting Consistency**
   - All character names consistent? (especially protagonist)
   - Logical space/time settings?
   - Settings not changing mid-story?

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

5. **Literary Completion**
   - "Showing" technique well used?
   - Philosophical insights naturally integrated?
   - Effective metaphors and symbols?

**Failure Criteria:**
- Similar content in 2+ phases
- 2+ sections of narrative stagnation
- Character name/setting errors
- Repeated resetting of insights

**Revision Instructions:**
Specific progression directions and prohibitions for each writer.
All detected repetitions must be removed."""
        }
    
        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. λ‚΄λ©΄ λ¬˜μ‚¬μ™€ μ‚¬νšŒμ  λ§₯락 심화
5. '보여주기' 기법 κ°•ν™” - 직접 μ„€λͺ…을 감각적 λ¬˜μ‚¬λ‘œ λŒ€μ²΄
6. 철학적 톡찰 μžμ—°μŠ€λŸ½κ²Œ 포함
7. 반볡된 ν‘œν˜„/상황 μ™„μ „ 제거
8. 주인곡 이름 일관성 확인

**νŠΉλ³„ μ£Όμ˜μ‚¬ν•­:**
- 이미 μ‚¬μš©λœ "μŠ΅κΈ°κ°€ μ°¬ μ•„μΉ¨", "λ‚˜λΌλ―Έ μ–΄ν”Œ", "43λ§Œμ›" λ“±μ˜ ν‘œν˜„ λ³€κ²½
- 주인곡의 κΉ¨λ‹¬μŒμ΄ 이전보닀 λ°œμ „λœ ν˜•νƒœλ‘œ ν‘œν˜„
- μƒˆλ‘œμš΄ λ””ν…ŒμΌκ³Ό 감각적 λ¬˜μ‚¬ μΆ”κ°€

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

    def create_editor_prompt(self, complete_novel: str, issues: List[str], language: str) -> str:
       """νŽΈμ§‘μž ν”„λ‘¬ν”„νŠΈ - 반볡 제거 μ „λ¬Έ"""
       
       lang_prompts = {
           "Korean": f"""당신은 μ „λ¬Έ νŽΈμ§‘μžμž…λ‹ˆλ‹€. 
μ™„μ„±λœ μ›κ³ μ—μ„œ λ°˜λ³΅μ„ μ œκ±°ν•˜κ³  μ„œμ‚¬λ₯Ό λ§€λ„λŸ½κ²Œ μ—°κ²°ν•˜μ„Έμš”.

**발견된 문제:**
{chr(10).join(issues)}

**νŽΈμ§‘ μ§€μΉ¨:**

1. **반볡 제거 (μ΅œμš°μ„ )**
  - λ™μΌν•˜κ±°λ‚˜ μœ μ‚¬ν•œ 문단은 κ°€μž₯ 효과적인 것 ν•˜λ‚˜λ§Œ 남기고 μ‚­μ œ
  - "μŠ΅κΈ°κ°€ μ°¬ μ•„μΉ¨", "λ‚˜λΌλ―Έ μ–΄ν”Œ 43λ§Œμ›" λ“± 반볡 ν‘œν˜„ 쀑 ν•˜λ‚˜λ§Œ μœ μ§€
  - λΉ„μŠ·ν•œ μž₯λ©΄(μ—°λͺ» μ‘μ‹œ, κ³„λž€ λ˜μ§€κΈ° λ“±)은 κ°€μž₯ κ°•λ ¬ν•œ κ²ƒλ§Œ 선택

2. **μ„œμ‚¬ μž¬κ΅¬μ„±**
  - 남은 μž₯면듀을 인과관계에 따라 μž¬λ°°μ—΄
  - μ‹œκ°„ μˆœμ„œμ™€ κ°μ •μ˜ 흐름이 μžμ—°μŠ€λŸ½κ²Œ μ—°κ²°λ˜λ„λ‘
  - ν•„μš”μ‹œ 짧은 μ „ν™˜ 문단 μΆ”κ°€ (2-3λ¬Έμž₯)

3. **캐릭터 일관성**
  - 주인곡 이름을 'λ‚˜λΌλ―Έ'둜 톡일
  - λ‹€λ₯Έ μΈλ¬Όλ“€μ˜ 이름도 일관성 확인
  - 인물의 성격과 말투 일관성 μœ μ§€

4. **κΉ¨λ‹¬μŒμ˜ λˆ„μ **
  - 주인곡의 각 κΉ¨λ‹¬μŒμ΄ 이전보닀 λ°œμ „λœ ν˜•νƒœλ‘œ ν‘œν˜„λ˜λ„λ‘
  - λ™μΌν•œ μˆ˜μ€€μ˜ 인식 반볡 제거
  - λ§ˆμ§€λ§‰μœΌλ‘œ 갈수둝 더 κΉŠμ€ 톡찰이 λ˜λ„λ‘

5. **λΆ„λŸ‰ μ‘°μ •**
  - 반볡 제거 후에도 8,000단어 이상 μœ μ§€
  - ν•„μš”μ‹œ 남은 μž₯면듀을 μ•½κ°„ ν™•μž₯ (λ¬˜μ‚¬ μΆ”κ°€)

**νŽΈμ§‘ κ·œμΉ™:**
- μž‘κ°€μ˜ 원문 μŠ€νƒ€μΌκ³Ό λ¬Έμ²΄λŠ” μ΅œλŒ€ν•œ 보쑴
- μƒˆλ‘œμš΄ μ‚¬κ±΄μ΄λ‚˜ 인물 μΆ”κ°€ κΈˆμ§€
- 핡심 상징과 주제 손상 κΈˆμ§€
- μ›λ¬Έμ˜ 철학적 깊이 μœ μ§€

**κ²°κ³Όλ¬Ό:**
반볡이 μ™„μ „νžˆ 제거되고 μžμ—°μŠ€λŸ½κ²Œ 흐λ₯΄λŠ” μ΅œμ’… 원고λ₯Ό μ œμ‹œν•˜μ„Έμš”.
νŽΈμ§‘ μ „ν›„μ˜ μ£Όμš” 변경사항도 κ°„λ‹¨νžˆ μš”μ•½ν•˜μ„Έμš”.""",

           "English": f"""You are a professional editor.
Remove repetitions and smooth narrative connections in the completed manuscript.

**Identified Issues:**
{chr(10).join(issues)}

**Editing Guidelines:**

1. **Repetition Removal (Top Priority)**
  - Keep only most effective version of similar paragraphs
  - Retain only one instance of repeated expressions
  - Select most powerful version of similar scenes

2. **Narrative Reconstruction**
  - Rearrange remaining scenes by causality
  - Natural flow of time and emotion
  - Add brief transitions if needed (2-3 sentences)

3. **Character Consistency**
  - Unify protagonist name
  - Check other character name consistency
  - Maintain character personality/voice

4. **Insight Accumulation**
  - Each insight more developed than previous
  - Remove same-level recognition repetitions
  - Deeper insights toward the end

5. **Length Adjustment**
  - Maintain 8,000+ words after cuts
  - Slightly expand remaining scenes if needed

**Editing Rules:**
- Preserve original style and voice
- No new events or characters
- Protect core symbols and themes
- Maintain philosophical depth

**Output:**
Present final manuscript with repetitions removed and natural flow.
Briefly summarize major changes."""
       }
       
       return lang_prompts.get(language, lang_prompts["Korean"])

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

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

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

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

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

2. **문학적 μ„±μ·¨ (35점)**
  - 주제 μ˜μ‹μ˜ 깊이
  - 인물 μ‹¬λ¦¬μ˜ 섀득λ ₯
  - 문체의 일관성과 아름닀움
  - 상징과 μ€μœ μ˜ 효과
  - '보여주기' κΈ°λ²•μ˜ ν™œμš©λ„

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

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

**νŠΉλ³„ 감점 μš”μΈ:**
- λ‚΄μš©/λ¬Έμž₯ 반볡 (-5점 per μ€‘λŒ€ 반볡)
- 캐릭터 이름 뢈일치 (-3점)
- μ„œμ‚¬ 정체/μˆœν™˜ (-5점)
- κΉ¨λ‹¬μŒ 리셋 ν˜„μƒ (-3점)

**총점: /100점**

특히 '반볡 ꡬ쑰' λ¬Έμ œκ°€ μžˆμ—ˆλŠ”μ§€ μ—„κ²©νžˆ ν‰κ°€ν•˜μ„Έμš”.
'κ°œκ΅¬λ¦¬μ•Œ' 같은 κ°•λ ¬ν•œ 쀑심 상징이 μžˆλŠ”μ§€ ν™•μΈν•˜μ„Έμš”.
νŽΈμ§‘ 후에도 남은 반볡이 μžˆλŠ”μ§€ μ„Έλ°€νžˆ κ²€ν† ν•˜μ„Έμš”.""",

           "English": f"""Evaluate the completed novel by AGI Turing Test standards.

**Work Information:**
- Total length: {word_count} words
- Target length: 8,000+ words

**Work (final portion):**
{complete_novel[-3000:]}

**Evaluation Criteria (AGI Turing Test):**

1. **Completion as Novel (30 points)**
  - Integrated narrative structure (no repetition)
  - Clear character transformation arcs
  - Plot accumulation and resolution
  - 8,000+ word length
  - Setting consistency (especially names)

2. **Literary Achievement (35 points)**
  - Depth of thematic consciousness
  - Persuasiveness of character psychology
  - Consistency and beauty of style
  - Effectiveness of symbols and metaphors
  - Use of "showing" technique

3. **Social Insight (25 points)**
  - Capturing contemporary social issues
  - Connection between individual and structure
  - Balance of universality and specificity
  - Insights into human condition

4. **Originality and Humanity (10 points)**
  - Feeling of human author, not AI
  - Original expressions and insights
  - Emotional authenticity
  - Philosophical depth

**Special Deductions:**
- Content/sentence repetition (-5 points per major repetition)
- Character name inconsistency (-3 points)
- Narrative stagnation/cycling (-5 points)
- Insight reset phenomenon (-3 points)

**Total Score: /100 points**

Strictly evaluate whether there are 'repetitive structure' issues.
Check for powerful central symbols like 'frog eggs'.
Carefully review for any remaining repetitions after editing."""
       }
   
       return lang_prompts.get(language, lang_prompts["Korean"])

   # --- 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") or role == "editor" 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단어λ₯Ό μž‘μ„±ν•˜λ©°, λ‚΄λ©΄κ³Ό μ‚¬νšŒλ₯Ό λ™μ‹œμ— ν¬μ°©ν•˜μ„Έμš”.
μ ˆλŒ€ 이전과 같은 상황을 λ°˜λ³΅ν•˜μ§€ λ§ˆμ„Έμš”.
주인곡의 이름과 섀정을 μΌκ΄€λ˜κ²Œ μœ μ§€ν•˜μ„Έμš”.
이미 얻은 κΉ¨λ‹¬μŒμ„ μžŠμ§€ 말고 λ°œμ „μ‹œν‚€μ„Έμš”.""",
               
               "editor": """당신은 κ²½ν—˜μ΄ ν’λΆ€ν•œ λ¬Έν•™ νŽΈμ§‘μžμž…λ‹ˆλ‹€.
λ°˜λ³΅μ„ μ² μ €νžˆ μ œκ±°ν•˜κ³  μ„œμ‚¬μ˜ 흐름을 λ§€λ„λŸ½κ²Œ λ§Œλ“œμ„Έμš”.
μ›μž‘μ˜ 문체와 μ£Όμ œλŠ” λ³΄μ‘΄ν•˜λ©΄μ„œ ꡬ쑰적 문제λ₯Ό ν•΄κ²°ν•˜μ„Έμš”.
캐릭터 이름과 μ„€μ •μ˜ 일관성을 ν™•λ³΄ν•˜μ„Έμš”.
κΉ¨λ‹¬μŒμ΄ λˆ„μ λ˜κ³  λ°œμ „ν•˜λ„λ‘ νŽΈμ§‘ν•˜μ„Έμš”."""
           },
           "English": {
               "director": """You are a Nobel Prize-winning master of contemporary literary fiction.
Capture both universal human condition and specific social realities.
Create intense, multilayered central symbols like 'frog eggs'.
Pursue both philosophical depth and literary beauty.
Build one powerful narrative through progression not repetition, development not cycles.
Establish protagonist's name and settings clearly with consistency.""",
               
               "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.
Evaluate effectiveness of literary techniques and philosophical depth.
Always check character name and setting consistency.
Never tolerate repetition of same sentences or situations.""",
               
               "writer_base": """You are a contemporary literary writer.
Use 'showing' technique to stimulate reader's imagination.
Convey emotions through sensory description and action rather than explanation.
Include new insights about human existence in each scene.
Take results from previous phase and develop into new territory.
Write minimum 800 words, capturing both interior and society.
Never repeat previous situations.
Maintain protagonist's name and settings consistently.
Don't forget gained insights, develop them further.""",
               
               "editor": """You are an experienced literary editor.
Thoroughly remove repetitions and smooth narrative flow.
Preserve original style and themes while solving structural issues.
Ensure character name and setting consistency.
Edit so insights accumulate and develop."""
           }
       }
       
       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),
                   "repetition_score": s.get('repetition_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,
                       "repetition_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())
                   previous_content = self.get_previous_writer_content(stages, writer_num)
                   
                   # 진행도 점수 계산
                   progression_scores = self.narrative_tracker.progression_monitor.calculate_progression_score(
                       writer_num, stage_content, previous_content
                   )
                   progression_score = sum(progression_scores.values()) / len(progression_scores)
                   stages[stage_idx]["progression_score"] = progression_score
                   
                   # λ°˜λ³΅λ„ 점수 계산
                   repetition_score = 10.0 - self.narrative_tracker.progression_monitor.count_repetitions(stage_content)
                   stages[stage_idx]["repetition_score"] = max(0, repetition_score)
                   
                   # μ„œμ‚¬ 좔적기 μ—…λ°μ΄νŠΈ
                   self.update_narrative_tracker(stage_content, writer_num)
                   self.narrative_tracker.extract_used_elements(stage_content)

               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),
                   stages[stage_idx].get("repetition_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)
           
           # νŽΈμ§‘μžκ°€ μ²˜λ¦¬ν•œ λ‚΄μš©μ΄ 있으면 그것을 μ‚¬μš©
           edited_content = self.get_edited_content(stages)
           if edited_content:
               final_novel = edited_content
               
           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)
           used_elements = list(self.narrative_tracker.used_expressions)
           
           return self.create_writer_prompt_enhanced(
               writer_num, master_plan, previous_content, 
               phase_requirements, narrative_summary, language, used_elements
           )
       
       if stage_idx == 13:  # 비평가 쀑간 κ²€ν† 
           all_content = self.get_all_writer_content(stages, 12)
           return self.create_critic_consistency_prompt_enhanced(
               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)
           issues = self.detect_issues(complete_novel)
           return self.create_editor_prompt(complete_novel, issues, language)
           
       if stage_idx == 25:  # μ΅œμ’… κ²€ν† 
           edited_novel = stages[24]["content"] if stages[24]["content"] else self.get_all_writer_content(stages, 23)
           word_count = len(edited_novel.split())
           return self.create_critic_final_prompt(edited_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단어 λΆ„λŸ‰ κ³„νš
5. μˆ˜λ™νƒœ μ‚¬μš©κΈˆμ§€
6. 철학적 κΉŠμ΄μ™€ 인간애 포함
7. κ°•λ ¬ν•œ 쀑심 상징 μ°½μ‘°
8. 주인곡 이름 λͺ…ν™•νžˆ μ„€μ • (일관성 μœ μ§€)

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

    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 get_edited_content(self, stages: List[Dict]) -> str:
       """νŽΈμ§‘λœ λ‚΄μš© κ°€μ Έμ˜€κΈ°"""
       for s in stages:
           if "νŽΈμ§‘μž" in s.get("name", "") and s["content"]:
               return s["content"]
       return ""

    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
           
       # 철학적 톡찰 μΆ”μΆœ (κ°„λ‹¨ν•œ ν‚€μ›Œλ“œ 기반)
       philosophical_keywords = ['쑴재', '의미', 'μ‚Ά', '죽음', '인간', '고톡', '희망', 'μ‚¬λž‘', 
                                'existence', 'meaning', 'life', 'death', 'human', 'suffering', 'hope', 'love']
       for keyword in philosophical_keywords:
           if keyword in content:
               self.narrative_tracker.philosophical_insights.append(f"Phase {writer_num}: {keyword} 탐ꡬ")
               break
               
       # 문학적 기법 감지
       literary_devices = []
       if '처럼' in content or 'like' in content or 'as if' in content:
           literary_devices.append('λΉ„μœ ')
       if '...' in content or 'β€”' in content:
           literary_devices.append('μ˜μ‹μ˜ 흐름')
       if content.count('"') > 4:
           literary_devices.append('λŒ€ν™”')
       
       if literary_devices:
           self.narrative_tracker.literary_devices[writer_num] = literary_devices

    def detect_issues(self, content: str) -> List[str]:
       """문제점 감지"""
       issues = []
       
       # 반볡 감지
       duplicates = self.narrative_tracker.content_deduplicator.count_repetitions(content)
       if duplicates > 0:
           issues.append(f"{duplicates}개의 반볡된 문단 발견")
           
       # νŠΉμ • 반볡 ν‘œν˜„ 감지
       repetitive_phrases = ["μŠ΅κΈ°κ°€ μ°¬ μ•„μΉ¨", "λ‚˜λΌλ―Έ μ–΄ν”Œ", "43λ§Œμ›", "κ°œκ΅¬λ¦¬μ•Œμ„ λ°”λΌλ³΄μ•˜λ‹€"]
       for phrase in repetitive_phrases:
           count = content.count(phrase)
           if count > 2:
               issues.append(f"'{phrase}' ν‘œν˜„μ΄ {count}회 반볡됨")
               
       # 캐릭터 이름 일관성
       name_variations = ["λ‚˜λΌλ―Έ", "μ•ˆμ •", "λ‚˜"]
       found_names = [name for name in name_variations if name in content]
       if len(found_names) > 1:
           issues.append(f"주인곡 이름 뢈일치: {', '.join(found_names)}")
           
       return issues

    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
           
       # 철학적 깊이 체크
       philosophical_keywords = ['쑴재', '의미', 'μ‚Άμ˜', 'μΈκ°„μ˜', 'μ™œ', 'existence', 'meaning', 'life', 'human', 'why']
       if any(keyword in content for keyword in philosophical_keywords):
           score += 0.5
           
       # 문학적 기법 체크
       if not any(phrase in content for phrase in ['λŠκΌˆλ‹€', 'μ˜€λ‹€', 'felt', 'was']):
           score += 0.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)
           # νŽΈμ§‘λœ λ‚΄μš©μ΄ 있으면 그것을 μ‚¬μš©
           edited = system.get_edited_content(stages)
           if edited:
               novel_content = edited
           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]"
       if stage.get('repetition_score', 0) > 0:
           markdown += f" [λ°˜λ³΅λ„: {stage['repetition_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;
}

.improvement-note {
   background-color: rgba(0, 255, 127, 0.1);
   border-left: 3px solid #00ff7f;
   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;
}

/* 점수 ν‘œμ‹œ μŠ€νƒ€μΌ */
.score-badge {
   display: inline-block;
   padding: 2px 8px;
   border-radius: 12px;
   font-size: 0.9em;
   font-weight: bold;
   margin-left: 5px;
}

.score-high {
   background-color: #4CAF50;
   color: white;
}

.score-medium {
   background-color: #FF9800;
   color: white;
}

.score-low {
   background-color: #F44336;
   color: white;
}
"""


# Gradio μΈν„°νŽ˜μ΄μŠ€ 생성
def create_interface():
   with gr.Blocks(css=custom_css, title="AI μ§„ν–‰ν˜• μž₯νŽΈμ†Œμ„€ 생성 μ‹œμŠ€ν…œ v2") as interface:
       gr.HTML("""
       <div class="main-header">
           <h1 style="font-size: 2.5em; margin-bottom: 10px;">
               πŸ“š AI μ§„ν–‰ν˜• μž₯νŽΈμ†Œμ„€ 생성 μ‹œμŠ€ν…œ v2.0
           </h1>
           <h3 style="color: #ddd; margin-bottom: 20px;">
               반볡 μ—†λŠ” μ§„μ •ν•œ μž₯편 μ„œμ‚¬ ꡬ쑰 μ‹€ν˜„
           </h3>
           <p style="font-size: 1.1em; color: #eee; max-width: 800px; margin: 0 auto;">
               10개의 유기적으둜 μ—°κ²°λœ 단계λ₯Ό 톡해 ν•˜λ‚˜μ˜ μ™„μ „ν•œ 이야기λ₯Ό λ§Œλ“€μ–΄λƒ…λ‹ˆλ‹€.
               <br>
               각 λ‹¨κ³„λŠ” 이전 λ‹¨κ³„μ˜ 필연적 결과둜 이어지며, 인물의 변화와 μ„±μž₯을 μΆ”μ ν•©λ‹ˆλ‹€.
           </p>
           <div class="progress-note">
               ⚑ 반볡이 μ•„λ‹Œ 좕적, μˆœν™˜μ΄ μ•„λ‹Œ 진행을 ν†΅ν•œ μ§„μ •ν•œ μž₯편 μ„œμ‚¬
           </div>
           <div class="improvement-note">
               πŸ†• v2.0 κ°œμ„ μ‚¬ν•­: κ°•ν™”λœ 반볡 감지 μ‹œμŠ€ν…œ, νŽΈμ§‘μž 단계 μΆ”κ°€, μ‹€μ‹œκ°„ 진행도 λͺ¨λ‹ˆν„°λ§
           </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 μ§„ν–‰ν˜• μž₯νŽΈμ†Œμ„€ 생성 μ‹œμŠ€ν…œ v2.0 μ‹œμž‘...")
   logger.info("=" * 60)
   
   # ν™˜κ²½ 확인
   logger.info(f"API μ—”λ“œν¬μΈνŠΈ: {API_URL}")
   logger.info(f"λͺ©ν‘œ λΆ„λŸ‰: {TARGET_WORDS:,}단어")
   logger.info(f"μž‘κ°€λ‹Ή μ΅œμ†Œ λΆ„λŸ‰: {MIN_WORDS_PER_WRITER:,}단어")
   logger.info("μ£Όμš” κ°œμ„ μ‚¬ν•­: 반볡 감지 κ°•ν™”, νŽΈμ§‘μž 단계 μΆ”κ°€, 진행도 λͺ¨λ‹ˆν„°λ§")
   
   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
   )