File size: 62,935 Bytes
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f4c1f
6f2099e
 
 
 
d6f4c1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f98b09c
135f2e5
 
b480c20
 
995f254
 
 
 
135f2e5
 
 
 
f98b09c
 
 
 
 
 
 
 
 
 
 
6f2099e
 
 
775de68
6f2099e
 
 
775de68
6f2099e
 
 
 
775de68
 
 
 
 
 
 
 
 
 
 
 
6f2099e
 
 
 
 
b480c20
 
 
 
 
 
 
 
 
995f254
b480c20
6f2099e
995f254
 
b480c20
 
135f2e5
 
b480c20
 
4f58976
 
 
 
995f254
 
 
 
 
 
135f2e5
 
 
 
 
 
 
 
 
f98b09c
6f2099e
f98b09c
 
 
 
 
 
 
 
6f2099e
f98b09c
 
6f2099e
 
f98b09c
 
 
 
 
6f2099e
f98b09c
6f2099e
135f2e5
 
6f2099e
 
775de68
 
 
 
 
 
6f2099e
 
 
775de68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f2099e
 
 
775de68
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b480c20
 
 
995f254
 
 
 
 
 
f98b09c
b480c20
 
 
 
 
 
 
 
995f254
f98b09c
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
e996b5b
 
 
 
 
 
 
 
 
 
6f2099e
 
 
 
f98b09c
e996b5b
 
6f2099e
 
 
135f2e5
 
 
b480c20
995f254
 
 
 
135f2e5
 
 
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f4c1f
6f2099e
d6f4c1f
 
6f2099e
135f2e5
6f2099e
d6f4c1f
 
 
 
 
 
 
6f2099e
135f2e5
6f2099e
 
 
d6f4c1f
 
 
6f2099e
 
 
d6f4c1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135f2e5
6f2099e
d6f4c1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
 
135f2e5
6f2099e
 
 
 
 
 
 
 
 
 
 
d6f4c1f
6f2099e
 
 
 
 
 
d6f4c1f
 
 
 
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f4c1f
6f2099e
d6f4c1f
6f2099e
f98b09c
d6f4c1f
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f4c1f
6f2099e
f98b09c
 
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135f2e5
 
d6f4c1f
 
6f2099e
 
 
 
 
 
 
 
 
 
d6f4c1f
 
 
 
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f4c1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e996b5b
 
d6f4c1f
 
 
 
 
e996b5b
 
d6f4c1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b480c20
 
 
d6f4c1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995f254
 
 
 
e996b5b
d6f4c1f
 
 
 
 
 
 
 
 
 
 
e996b5b
 
 
 
d6f4c1f
 
 
6f2099e
 
 
d6f4c1f
6f2099e
 
d6f4c1f
 
6f2099e
d6f4c1f
6f2099e
 
 
 
 
 
 
 
 
 
 
995f254
 
 
e996b5b
995f254
e996b5b
 
 
 
 
 
995f254
 
 
 
 
e996b5b
 
 
 
 
 
995f254
 
 
 
 
 
 
 
 
 
 
4f58976
 
 
995f254
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e996b5b
 
 
 
 
 
 
 
 
995f254
 
 
d538006
995f254
 
 
 
e996b5b
 
d538006
995f254
 
 
e996b5b
995f254
 
e996b5b
 
995f254
 
 
 
 
 
 
 
 
 
 
 
 
e996b5b
 
995f254
 
 
 
 
 
 
 
 
 
e996b5b
995f254
d538006
995f254
d538006
995f254
e996b5b
 
 
 
 
 
995f254
 
d538006
 
 
 
 
 
 
 
 
 
995f254
 
 
 
6f2099e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Universal Document-to-Deck Ingestion Parser (`ingest_parser.py`)
Supports:
  - PowerPoint (.pptx)  β€” Slides, bullets, tables, speaker notes
  - Word (.docx)        β€” Headings, paragraphs, bullet lists, quotes, tables
  - Markdown (.md/.txt) β€” #, ##, -, >, tables
  - HTML (.html/.htm)   β€” Reveal.js <section>, .slide, or <h1>/<h2>/<ul>/<p>/<blockquote>
  - JSON (.json)        β€” Direct DeckSpec schema

Maps every extracted slide into one of 5 visual motion archetypes:
  1. `arc_cards`      β€” 3D cylindrical card carousel + glowing big counter
  2. `mockup_steps`   β€” Left app/slide list mockup + Right 3-card sequential focus glow
  3. `book_quote`     β€” 3D perspective open manual/book spread + cyan highlighter sweep
  4. `terminal_flow`  β€” Dark glass CLI/code window typing + glowing node flow diagram
  5. `metric_summary` β€” 3 neon glass pillars + final takeaway callout badge
"""

from __future__ import annotations
import json
import re
import zipfile
from pathlib import Path
from typing import Any


class DRMProtectedFileError(RuntimeError):
    """Raised when an OpenXML (.pptx/.docx) file is encrypted by enterprise DRM or Office protection."""

    def __init__(self, file_path: Path, reason: str = "") -> None:
        self.file_path = file_path
        self.reason = reason
        super().__init__(f"DRM or encrypted document detected: {file_path} ({reason})")


AGENT_HANDOFF_JSON_SCHEMA_EXAMPLE = """{
  "title": "2026 사내 AI λ„μž… μ „λž΅ λ³΄κ³ μ„œ",
  "slides": [
    {
      "title": "μΆ”μ§„ λ°°κ²½ 및 핡심 과제 5κ°€μ§€",
      "chapter": "01 μΆ”μ§„ λ°°κ²½",
      "bullets": [
        "λ¬Έμ„œ λ³΄μ•ˆ μ€€μˆ˜ | 사내 DRM μ—΄λžŒ μŠ€ν‚¬κ³Ό νŒŒμ΄ν”„λΌμΈ μ•ˆμ „ 연동",
        "생산성 ν–₯상 | λ³΄κ³ μ„œ λΈŒλ¦¬ν•‘ μ˜μƒ μ œμž‘ μ‹œκ°„ 90% 단좕",
        "ν‘œμ€€ν™” | 16μ’… λͺ¨μ…˜ κ·Έλž˜ν”½ λ ˆμ΄μ•„μ›ƒ μžλ™ λ§€ν•‘"
      ],
      "notes": "사내 DRM μŠ€ν‚¬λ‘œ 읽은 λ°œν‘œμž λ…ΈνŠΈ λ˜λŠ” μŠ¬λΌμ΄λ“œ 핡심 μ„€λͺ… λŒ€λ³Έμž…λ‹ˆλ‹€. λ°œν‘œμž λ…ΈνŠΈκ°€ μ—†λŠ” μž₯ν‘œλŠ” μ—μ΄μ „νŠΈκ°€ μŠ¬λΌμ΄λ“œ λ‚΄μš©μ„ λ°”νƒ•μœΌλ‘œ μžμ—°μŠ€λŸ¬μš΄ 2~3λ¬Έμž₯ ꡬ어체 λ‚΄λ ˆμ΄μ…˜μ„ μž‘μ„±ν•΄ λ„£μœΌμ„Έμš”."
    },
    {
      "title": "κΈ°μ‘΄ 방식 vs λͺ¨μ…˜ νŒŒμ΄ν”„λΌμΈ 비ꡐ",
      "chapter": "02 λ„μž… 효과",
      "table": [
        ["비ꡐ ν•­λͺ©", "λ‹¨μˆœ μŠ¬λΌμ΄λ“œ 캑처", "Deck2Video λͺ¨μ…˜ μ—”μ§„"],
        ["μ‹œκ° λͺ°μž…도", "βœ•", "βœ“"],
        ["단어 ν•˜μ΄λΌμ΄νŠΈ μžλ§‰", "βœ•", "βœ“"],
        ["사내 폐쇄망 지원", "β–³", "βœ“"]
      ],
      "notes": "ν‘œ 데이터도 table λ°°μ—΄λ‘œ μ „λ‹¬ν•˜λ©΄ λ„€μ˜¨ 비ꡐ λ§€νŠΈλ¦­μŠ€λ‚˜ 데이터 차트 λͺ¨μ…˜μœΌλ‘œ μžλ™ λ³€ν™˜λ©λ‹ˆλ‹€."
    }
  ]
}"""


def check_openxml_drm(file_path: Path) -> None:
    """Verify whether a .pptx/.docx file is a valid OpenXML ZIP or encrypted by corporate DRM."""
    try:
        header = file_path.read_bytes()[:64]
    except Exception as exc:
        raise DRMProtectedFileError(file_path, f"file read blocked: {exc}") from exc

    if not header:
        raise DRMProtectedFileError(file_path, "empty file (0 bytes)")

    # Standard OpenXML (.pptx, .docx, .xlsx) starts with ZIP magic bytes PK\x03\x04 (or PK\x05\x06 / PK\x07\x08)
    if header[:2] == b"PK" and zipfile.is_zipfile(file_path):
        return

    upper_hdr = header.upper()
    vendor = "Corporate DRM / Encrypted Container"
    if b"FASOO" in upper_hdr or b"FSN" in upper_hdr:
        vendor = "Fasoo DRM (νŒŒμˆ˜λ‹·μ»΄ λ¬Έμ„œλ³΄μ•ˆ)"
    elif b"MARKANY" in upper_hdr or b"DOCUMENT SAFER" in upper_hdr:
        vendor = "MarkAny DRM (λ§ˆν¬μ• λ‹ˆ λ¬Έμ„œλ³΄μ•ˆ)"
    elif b"SOFTCAMP" in upper_hdr or b"SCDSA" in upper_hdr:
        vendor = "Softcamp DRM (μ†Œν”„νŠΈμΊ ν”„ λ¬Έμ„œλ³΄μ•ˆ)"
    elif header[:8] == b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1":
        vendor = "OLE2 Encrypted Package (MS Purview AIP / Office μ•”ν˜Έν™” λ˜λŠ” κ΅¬ν˜• .ppt/.doc λ°”μ΄λ„ˆλ¦¬)"

    raise DRMProtectedFileError(
        file_path,
        f"{vendor} β€” magic={header[:12]!r} (python-pptx/python-docx cannot open encrypted binary directly)",
    )


ARCHETYPES = [
    "hero_3d_briefing",
    "media_showcase_split",
    "cinema_broll_fullscreen",
    "dossier_stamp_card",
    "archify_architecture",
    "anatomy_mechanic",
    "anime_svg_chart",
    "custom_viz_stage",
    "changelog_vertical",
    "mission_staircase",
    "swarm_network",
    "pricing_matrix",
    "arc_cards",
    "bento_grid",
    "mockup_steps",
    "vs_comparison",
    "book_quote",
    "data_bars",
    "notebook_flip",
    "process_timeline",
    "terminal_flow",
    "metric_summary",
]


def _split_sentences(text: str) -> list[str]:
    """Splits paragraph text ONLY at true terminal sentence punctuation (never mid-clause on words like '보닀 ')."""
    text = re.sub(r"\s+", " ", text.strip())
    if not text:
        return []
    parts = re.split(r"(?<=[.!?β€¦γ€‚γ€‚οΌοΌŸ])\s+(?![0-9])", text)
    cleaned = [p.strip() for p in parts if p.strip()]
    return cleaned if cleaned else [text]


def _is_unfinished_clause(line: str) -> bool:
    """Returns True if a note line ends mid-sentence (e.g., '온천물이 μ†Ÿμ•„', 'λ–¨μ–΄μ§„ 곀좩이', '사라지면,') and should flow into the next line."""
    s = line.strip()
    if not s or "||" in s:
        return False
    if s[-1] in ".!?β€¦γ€‚γ€‚οΌοΌŸ":
        return False
    if s.endswith(("λ‹€", "μš”", "μ£ ", "까", "λ„€", "음", "함", "됨", "μž„")):
        return False
    return True


def _clean_chapter_label(raw_ch: str) -> str:
    cleaned = re.sub(r"^\d+\s*[.Β·\-:]?\s*", "", raw_ch.strip()).strip()
    return (cleaned or raw_ch.strip())[:16]


def _infer_archetype(
    idx: int,
    total: int,
    title: str,
    bullets: list[str],
    notes: str,
    has_media: bool = False,
    has_stamp: bool = False,
    has_broll: bool = False,
    has_custom_viz: bool = False,
) -> str:
    combined = f"{title} {' '.join(bullets)} {notes}".lower()
    if has_custom_viz:
        return "custom_viz_stage"
    if has_broll:
        return "cinema_broll_fullscreen"
    if has_media:
        return "media_showcase_split"
    if has_stamp or any(k in combined for k in ["νŠΉν—ˆ", "곡식 ν•΄λͺ…", "곡식 μž…μž₯", "판결", "곡문", "μ„±λͺ…μ„œ", "patent", "official statement"]):
        return "dossier_stamp_card"
    if any(k in combined for k in ["μˆ˜μ‹¬", "단면", "μž μˆ˜μ •", "ν•΄λ°œ", "μ§€μΈ΅", "칼데라", "심해", "μ§€ν•˜", "고도"]):
        return "depth_cross_section"
    if any(k in combined for k in ["음ν–₯ 츑심", "λ“±κ³ μ„ ", "λ°”λ‹₯ 지도", "탐지", "μ†Œλ‚˜", "κ΄΄λ¬Ό νŒμ •", "ν˜„μž₯ 검증", "흔적 검증"]):
        return "sonar_factcheck_map"
    if any(k in combined for k in ["μ•„ν‚€ν…μ²˜", "μ‹œμŠ€ν…œ ꡬ쑰", "계측 ꡬ쑰", "데이터 νŒŒμ΄ν”„λΌμΈ", "κ²Œμ΄νŠΈμ›¨μ΄", "λ§ˆμ΄ν¬λ‘œμ„œλΉ„μŠ€", "architecture"]):
        return "archify_architecture"
    if any(k in combined for k in ["μž‘λ™ 원리", "λ‚΄λΆ€ 원리", "λ©”μ»€λ‹ˆμ¦˜", "기계", "κΈ°μ–΄", "밸브", "잠금", "ν•΄λΆ€", "anatomy", "mechanism"]):
        return "anatomy_mechanic"
    if any(k in combined for k in ["좔이", "μ„±μž₯ 곑선", "νŠΈλ Œλ“œ κ·Έλž˜ν”„", "μ‹œκ³„μ—΄", "λ³€ν™” μΆ”μ„Έ", "예츑 곑선"]):
        return "anime_svg_chart"
    if any(k in combined for k in ["μš”κΈˆ", "ν”Œλžœ", "κ°€κ²©ν‘œ", "ν• λ‹ΉλŸ‰", "무료", "유료", "pricing"]) and any("|" in b for b in bullets):
        return "pricing_matrix"
    date_bullets = sum(1 for b in bullets if re.match(r"^(?:\d{1,2}\.\d{1,2}|20\d{2}|v\d+\.\d+)", b.strip(), re.I))
    if date_bullets >= 2 or any(k in combined for k in ["λ³€κ²½ 기둝", "changelog", "μ—°ν˜", "νžˆμŠ€ν† λ¦¬", "릴리즈 λ…ΈνŠΈ"]):
        return "changelog_vertical"
    if sum(1 for b in bullets if "mission" in b.lower() or "λ―Έμ…˜" in b.lower()) >= 2 or "λ―Έμ…˜" in title.lower():
        return "mission_staircase"
    if any(k in combined for k in ["/swarm", "μŠ€μ›œ", "λ©€ν‹° μ—μ΄μ „νŠΈ", "코디넀이터", "μ§€νœ˜μž", "ꡰ체 λ„€νŠΈμ›Œν¬"]):
        return "swarm_network"
    if idx == 0 and (re.search(r"\d+", title) or len(bullets) >= 6):
        return "arc_cards"
    if idx == total - 1 and total >= 3 and any(k in combined for k in ["μš”μ•½", "정리", "κ²°λ‘ ", "마무리", "summary"]):
        return "metric_summary"
    if any(k in combined for k in [" vs ", "비ꡐ", "μ „ν›„", "as-is", "to-be", "차이점", "λŒ€λΉ„"]):
        return "vs_comparison"
    numeric_bullets = sum(1 for b in bullets if re.search(r"\d+\s*(%|λ°°|λΆ„|초|μ‹œκ°„|건|개|μ’…|점|만|μ–΅|x)", b.lower()))
    if numeric_bullets >= 2 or any(k in combined for k in ["μ§€ν‘œ", "μ„±κ³Ό", "톡계", "차트", "κ·Έλž˜ν”„", "데이터 비ꡐ"]):
        return "data_bars"
    if any(k in combined for k in ["λͺ…λ Ήμ–΄", "μ½”λ“œ", "cli", "터미널", "μ‹€ν–‰", "command", "python", "μ„€μΉ˜"]):
        return "terminal_flow"
    if any(k in combined for k in ["체크리슀트", "λ…ΈνŠΈ", "μ‹€μŠ΅", "μ κ²€ν‘œ", "μ‹€μ²œ 팁", "κ°€μ΄λ“œλΆ"]):
        return "notebook_flip"
    if any(k in combined for k in ["원칙", "μ±…", "맀뉴얼", "μ •μ˜", "인용", "핡심 λ¬Έμž₯", "chapter", "법칙", "μ² ν•™"]):
        return "book_quote"
    if any(k in combined for k in ["λ‘œλ“œλ§΅", "ν”„λ‘œμ„ΈμŠ€", "절차", "흐름도", "μˆœμ„œ", "νƒ€μž„λΌμΈ"]):
        return "process_timeline"
    if len(bullets) == 4 or any(k in combined for k in ["ꡬ성", "κΈ°λŠ₯", "νŠΉμ§•", "λ²€ν† ", "λͺ¨λ“ˆ", "μš”μ†Œ"]):
        return "bento_grid"
    if any(k in combined for k in ["μš”μ•½", "정리", "κ²°λ‘ ", "3κ°€μ§€"]):
        return "metric_summary"
    if len(bullets) >= 6:
        return "arc_cards"
    fallback_cycle = ["bento_grid", "mockup_steps", "book_quote", "process_timeline", "metric_summary"]
    return fallback_cycle[idx % len(fallback_cycle)]


def _parse_notes_into_beats(title: str, bullets: list[str], notes_lines: list[str]) -> list[dict[str, Any]]:
    beats: list[dict[str, Any]] = []
    cleaned_lines = [ln.strip() for ln in notes_lines if ln.strip()]
    idx = 0
    while idx < len(cleaned_lines):
        ln = cleaned_lines[idx]
        if "||" in ln:
            ko_part, en_part = [x.strip() for x in ln.split("||", 1)]
            beats.append({"narration": ko_part, "sub_ko": ko_part, "sub_en": en_part})
            idx += 1
            continue

        # Merge consecutive continuation clauses into ONE continuous narration sentence while keeping explicit visual subtitle cues!
        merged_cues = [ln]
        while _is_unfinished_clause(merged_cues[-1]) and (idx + 1) < len(cleaned_lines) and ("||" not in cleaned_lines[idx + 1]):
            idx += 1
            merged_cues.append(cleaned_lines[idx])

        if len(merged_cues) > 1:
            joined_narr = " ".join(merged_cues)
            beats.append({
                "narration": joined_narr,
                "sub_ko": joined_narr,
                "sub_en": "",
                "sub_cues": merged_cues,
            })
        else:
            for sent in _split_sentences(ln):
                beats.append({"narration": sent, "sub_ko": sent, "sub_en": ""})
        idx += 1

    if not beats:
        intro_sent = title if title.endswith(("λ‹€.", "μš”.", "μ£ .", "?")) else f"{title}에 λŒ€ν•΄ ν•΅μ‹¬λ§Œ μ§šμ–΄λ³΄κ² μŠ΅λ‹ˆλ‹€."
        beats.append({"narration": intro_sent, "sub_ko": title, "sub_en": ""})
        for b in bullets[:3]:
            display_b = b.replace("|", " Β· ").strip()
            spoken_b = b.replace("|", ", ").replace("β†’", "μ—μ„œ ").strip()
            if not spoken_b.endswith(("λ‹€.", "μš”.", "μ£ .", "!", "?")):
                spoken_b = f"{spoken_b}μž…λ‹ˆλ‹€."
            beats.append({"narration": spoken_b, "sub_ko": display_b, "sub_en": ""})
    return beats


def _compile_raw_slides_to_spec(deck_title: str, raw_slides: list[dict[str, Any]]) -> dict[str, Any]:
    if not raw_slides:
        raw_slides = [{
            "title": deck_title,
            "bullets": ["핡심 λ‚΄μš© μš”μ•½ | μžλ™ 생성 μŠ¬λΌμ΄λ“œ"],
            "notes_lines": [f"{deck_title} ν”„λ ˆμ  ν…Œμ΄μ…˜μ„ μ‹œμž‘ν•©λ‹ˆλ‹€."],
            "meta": {},
        }]

    chapters: list[dict[str, str]] = []
    seen_chapters: dict[str, int] = {}
    for item in raw_slides:
        raw_ch = item.get("meta", {}).get("CHAPTER") or item.get("chapter") or item["title"]
        ch_label = _clean_chapter_label(raw_ch)
        if ch_label not in seen_chapters and len(chapters) < 6:
            seen_chapters[ch_label] = len(chapters)
            chapters.append({
                "num": f"{len(chapters) + 1:02d}",
                "label": ch_label,
            })

    slides_spec: list[dict[str, Any]] = []
    for s_idx, item in enumerate(raw_slides):
        meta = item.get("meta", {})
        raw_ch = meta.get("CHAPTER") or item.get("chapter") or item["title"]
        ch_label = _clean_chapter_label(raw_ch)
        ch_idx = seen_chapters.get(ch_label, min(s_idx, max(len(chapters) - 1, 0)))

        bullets = item.get("bullets") or [item["title"]]
        notes_lines = item.get("notes_lines", [])
        broll_src = meta.get("BROLL") or ""
        media_src = broll_src or meta.get("MEDIA") or item.get("media_src", "")
        stamp_text = meta.get("STAMP") or ""
        custom_svg = meta.get("CUSTOM_SVG") or item.get("custom_svg", "")
        custom_html = meta.get("CUSTOM_HTML") or item.get("custom_html", "")
        archify_json = meta.get("ARCHIFY_JSON") or item.get("archify_json", "")
        custom_anime_js = item.get("custom_anime_js", "")
        has_custom_viz = bool(custom_svg or custom_html or archify_json)

        archetype = meta.get("ARCHETYPE") or _infer_archetype(
            s_idx,
            len(raw_slides),
            item["title"],
            bullets,
            " ".join(notes_lines),
            has_media=bool(media_src) and not bool(broll_src),
            has_stamp=bool(stamp_text),
            has_broll=bool(broll_src),
            has_custom_viz=has_custom_viz,
        )
        beats = _parse_notes_into_beats(item["title"], bullets, notes_lines)

        num_match = re.search(r"^(.*?)\s*(\d+)\s*([^\d]*)$", item["title"])
        stat_prefix = meta.get("STAT_PREFIX", item["title"][:16])
        stat_number = (
            int(meta["STAT_NUM"])
            if "STAT_NUM" in meta and str(meta["STAT_NUM"]).isdigit()
            else (int(num_match.group(2)) if num_match else len(bullets))
        )
        stat_suffix = meta.get("STAT_SUFFIX", num_match.group(3).strip()[:6] if num_match else "핡심")
        if num_match and "STAT_PREFIX" not in meta and num_match.group(1).strip():
            stat_prefix = num_match.group(1).strip()

        pronounce_tag = meta.get("PRONOUNCE") or meta.get("LEXICON") or meta.get("GLOSSARY") or ""
        slide_pronounce: dict[str, str] = {}
        if pronounce_tag:
            from deck_video_pipeline.pronunciation_engine import parse_inline_pronounce_tag
            slide_pronounce.update(parse_inline_pronounce_tag(pronounce_tag))
        if isinstance(item.get("pronounce"), dict):
            for pk, pv in item["pronounce"].items():
                if pk and pv:
                    slide_pronounce[str(pk)] = str(pv)

        slides_spec.append({
            "id": f"slide_{s_idx + 1:02d}",
            "chapter_index": ch_idx,
            "archetype": archetype,
            "bg_preset": meta.get("BG", ""),
            "lang": meta.get("LANG", ""),
            "pronounce_map": slide_pronounce,
            "badge": meta.get("BADGE", f"SECTION {s_idx + 1:02d}"),
            "title": item["title"],
            "subtitle": meta.get("SUBTITLE", ""),
            "hero_word": meta.get("HERO_WORD", ""),
            "scramble_text": meta.get("SCRAMBLE", ""),
            "source_note": meta.get("SOURCE", ""),
            "stamp_text": stamp_text,
            "custom_svg": custom_svg,
            "custom_html": custom_html,
            "archify_json": archify_json,
            "custom_anime_js": custom_anime_js,
            "media_src": media_src,
            "media_caption": meta.get("MEDIA_CAPTION", ""),
            "plans": meta.get("PLANS", "무료 β‚©0 | Pro μ›” β‚©29,000 | Ultra μ›” β‚©119,000~"),
            "stat_prefix": stat_prefix,
            "stat_number": stat_number,
            "stat_suffix": stat_suffix,
            "bullets": bullets,
            "highlight_quote": meta.get("QUOTE") or item.get("quote") or (bullets[0] if bullets else item["title"]),
            "command": meta.get("COMMAND", "deck2video --input document.pptx --sfx on"),
            "flow_left": meta.get("FLOW_LEFT", "원본 κ΅μ•ˆ λ¬Έμ„œ"),
            "flow_left_sub": meta.get("FLOW_LEFT_SUB", "PPTX Β· DOCX Β· MD Β· HTML"),
            "flow_right": meta.get("FLOW_RIGHT", "1080p λͺ¨μ…˜ MP4"),
            "flow_right_sub": meta.get("FLOW_RIGHT_SUB", "HTML λ Œλ”λ§ + 효과음 싱크"),
            "beats": beats,
        })

    return {
        "title": deck_title,
        "voice": "ko-KR-InJoonNeural",
        "voice_rate": "+6%",
        "bgm_mood": "focused",
        "chapters": chapters,
        "slides": slides_spec,
    }


# ---------------------------------------------------------------------------
# 1. PowerPoint (.pptx) Parser (with GroupShape recursion & Logo Filter)
# ---------------------------------------------------------------------------
def parse_pptx_to_spec(pptx_path: Path, extract_images: bool = True) -> dict[str, Any]:
    check_openxml_drm(pptx_path)
    from pptx import Presentation
    from pptx.enum.shapes import MSO_SHAPE_TYPE

    try:
        prs = Presentation(str(pptx_path))
    except Exception as exc:
        raise DRMProtectedFileError(pptx_path, f"python-pptx open failed: {exc}") from exc

    slide_w = float(prs.slide_width or 9144000)
    slide_h = float(prs.slide_height or 5143500)
    raw_slides: list[dict[str, Any]] = []
    extracted_dir = pptx_path.parent / f".{pptx_path.stem}_extracted_media"

    for s_idx, slide in enumerate(prs.slides):
        title = ""
        title_shape = slide.shapes.title
        if title_shape and title_shape.text.strip():
            title = title_shape.text.strip().replace("\n", " ")

        bullets: list[str] = []
        meta_tags: dict[str, str] = {}
        candidate_images: list[tuple[float, bool, Any, int]] = []
        shape_counter = 0

        def _walk_shapes(shapes_iter: Any) -> None:
            nonlocal shape_counter
            for shape in shapes_iter:
                shape_counter += 1
                if shape == title_shape:
                    continue
                if shape.shape_type == MSO_SHAPE_TYPE.GROUP and hasattr(shape, "shapes"):
                    _walk_shapes(shape.shapes)
                    continue
                if extract_images and shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
                    w_ratio = float(getattr(shape, "width", 0) or 0) / slide_w
                    h_ratio = float(getattr(shape, "height", 0) or 0) / slide_h
                    area_ratio = w_ratio * h_ratio
                    is_full_wallpaper = (w_ratio >= 0.96 and h_ratio >= 0.96)
                    # Ignore tiny corner corporate logos / header icons (< 16% width or height)
                    if w_ratio >= 0.16 and h_ratio >= 0.16 and area_ratio >= 0.04:
                        candidate_images.append((area_ratio, is_full_wallpaper, shape, shape_counter))
                if getattr(shape, "has_text_frame", False):
                    for para in shape.text_frame.paragraphs:
                        line = para.text.strip()
                        if not line:
                            continue
                        m_tag = re.match(r"^\[([A-Z_]+):\s*(.+)\]$", line)
                        if m_tag:
                            meta_tags[m_tag.group(1).upper()] = m_tag.group(2).strip()
                        else:
                            bullets.append(line)
                elif getattr(shape, "has_table", False):
                    for r_idx, row in enumerate(shape.table.rows):
                        cells = [c.text.strip().replace("\n", " ") for c in row.cells if c.text.strip()]
                        if not cells:
                            continue
                        if r_idx == 0 and len(cells) >= 3 and "PLANS" not in meta_tags and any(
                            k in " ".join(cells).lower() for k in ["무료", "유료", "pro", "λͺ¨λ“œ", "방식", "ꡬ뢄", "μ˜΅μ…˜", "비ꡐ"]
                        ):
                            meta_tags["PLANS"] = " | ".join(cells[1:4])
                            continue
                        bullets.append(" | ".join(cells))

        _walk_shapes(slide.shapes)

        extracted_img_path = ""
        # Pick the most prominent content chart/screenshot while ignoring full-slide template wallpaper if text exists
        filtered_imgs = [
            item for item in candidate_images
            if not (item[1] and len(bullets) >= 2)
        ]
        if filtered_imgs:
            filtered_imgs.sort(key=lambda x: x[0], reverse=True)
            _, _, best_shape, best_idx = filtered_imgs[0]
            try:
                extracted_dir.mkdir(parents=True, exist_ok=True)
                ext = best_shape.image.ext or "png"
                img_file = extracted_dir / f"slide_{s_idx + 1:02d}_img_{best_idx}.{ext}"
                img_file.write_bytes(best_shape.image.blob)
                extracted_img_path = str(img_file.resolve())
            except Exception:
                pass

        if not title and bullets:
            title = bullets.pop(0)
        if not title:
            title = f"μŠ¬λΌμ΄λ“œ {s_idx + 1}"

        notes_lines: list[str] = []
        if slide.has_notes_slide and slide.notes_slide.notes_text_frame:
            raw_notes = slide.notes_slide.notes_text_frame.text.strip()
            notes_lines = [ln.strip() for ln in raw_notes.splitlines() if ln.strip()]

        raw_slides.append({
            "title": title,
            "bullets": bullets,
            "notes_lines": notes_lines,
            "media_src": extracted_img_path,
            "meta": meta_tags,
        })

    deck_title = raw_slides[0]["title"] if raw_slides else pptx_path.stem
    return _compile_raw_slides_to_spec(deck_title, raw_slides)


# ---------------------------------------------------------------------------
# 2. Microsoft Word (.docx) Parser
# ---------------------------------------------------------------------------
def parse_docx_to_spec(docx_path: Path) -> dict[str, Any]:
    check_openxml_drm(docx_path)
    from docx import Document
    from docx.oxml.table import CT_Tbl
    from docx.oxml.text.paragraph import CT_P
    from docx.table import Table
    from docx.text.paragraph import Paragraph

    try:
        doc = Document(str(docx_path))
    except Exception as exc:
        raise DRMProtectedFileError(docx_path, f"python-docx open failed: {exc}") from exc
    deck_title = docx_path.stem
    current_chapter = ""
    raw_slides: list[dict[str, Any]] = []
    cur_slide: dict[str, Any] | None = None

    def flush_slide() -> None:
        nonlocal cur_slide
        if cur_slide and (cur_slide["title"] or cur_slide["bullets"] or cur_slide["notes_lines"]):
            if not cur_slide["title"]:
                cur_slide["title"] = cur_slide["bullets"].pop(0) if cur_slide["bullets"] else f"μ„Ήμ…˜ {len(raw_slides) + 1}"
            raw_slides.append(cur_slide)
        cur_slide = None

    for child in doc.element.body.iterchildren():
        if isinstance(child, CT_P):
            para = Paragraph(child, doc)
            text = para.text.strip()
            if not text:
                continue
            style_name = (para.style.name if para.style else "").lower()

            if "title" in style_name and not raw_slides and cur_slide is None:
                deck_title = text
                continue

            if style_name.startswith("heading 1"):
                flush_slide()
                current_chapter = text
                cur_slide = {
                    "title": text,
                    "chapter": current_chapter,
                    "bullets": [],
                    "notes_lines": [],
                    "quote": "",
                    "meta": {},
                }
                continue

            if style_name.startswith(("heading 2", "heading 3")) or re.match(r"^(?:\d+\.|Step\s*\d+|μŠ¬λΌμ΄λ“œ\s*\d+)\s+\S+", text, re.I):
                # If cur_slide was just created from Heading 1 and still empty, adopt this Heading 2 as its title
                if cur_slide and not cur_slide["bullets"] and not cur_slide["notes_lines"] and cur_slide["title"] == current_chapter:
                    cur_slide["title"] = text
                else:
                    flush_slide()
                    cur_slide = {
                        "title": text,
                        "chapter": current_chapter or text,
                        "bullets": [],
                        "notes_lines": [],
                        "quote": "",
                        "meta": {},
                    }
                continue

            if cur_slide is None:
                cur_slide = {
                    "title": text if len(text) <= 36 else deck_title,
                    "chapter": current_chapter or deck_title,
                    "bullets": [] if len(text) <= 36 else [text],
                    "notes_lines": [],
                    "quote": "",
                    "meta": {},
                }
                continue

            m_tag = re.match(r"^\[([A-Z_]+):\s*(.+)\]$", text)
            if m_tag:
                cur_slide["meta"][m_tag.group(1).upper()] = m_tag.group(2).strip()
            elif "quote" in style_name or text.startswith((">", "πŸ’¬", "[λ°œν‘œλ…ΈνŠΈ]", "[λ‚΄λ ˆμ΄μ…˜]", "λ…ΈνŠΈ:")):
                cleaned_note = re.sub(r"^(?:>|πŸ’¬|\[λ°œν‘œλ…ΈνŠΈ\]|\[λ‚΄λ ˆμ΄μ…˜\]|λ…ΈνŠΈ:)\s*", "", text).strip()
                if "quote" in style_name and not cur_slide["quote"]:
                    cur_slide["quote"] = cleaned_note
                cur_slide["notes_lines"].append(cleaned_note)
            elif "list" in style_name or text.startswith(("- ", "β€’ ", "* ", "β–ͺ ")):
                cur_slide["bullets"].append(re.sub(r"^[-β€’*β–ͺ]\s*", "", text).strip())
            else:
                # Long prose sentence becomes spoken narration; concise phrase becomes bullet
                if len(text) > 52 and text.endswith(("λ‹€.", "μš”.", "μ£ .", "!", "?")):
                    cur_slide["notes_lines"].append(text)
                else:
                    cur_slide["bullets"].append(text)

            # Auto-chunk if a flat Word doc has too many bullets in one section
            if len(cur_slide["bullets"]) >= 7 and not current_chapter:
                flush_slide()

        elif isinstance(child, CT_Tbl):
            tbl = Table(child, doc)
            if cur_slide is None:
                cur_slide = {
                    "title": deck_title,
                    "chapter": current_chapter or deck_title,
                    "bullets": [],
                    "notes_lines": [],
                    "quote": "",
                    "meta": {},
                }
            for r_i, row in enumerate(tbl.rows):
                cells = [c.text.strip().replace("\n", " ") for c in row.cells if c.text.strip()]
                if not cells:
                    continue
                if r_i == 0 and any(h in cells[0].lower() for h in ["ꡬ뢄", "ν•­λͺ©", "단계", "λͺ¨λ“ˆ", "category", "step"]):
                    continue
                cur_slide["bullets"].append(" | ".join(cells[:2]) if len(cells) >= 2 else cells[0])

    flush_slide()
    if raw_slides and deck_title == docx_path.stem:
        deck_title = raw_slides[0]["title"]
    return _compile_raw_slides_to_spec(deck_title, raw_slides)


# ---------------------------------------------------------------------------
# 3. Markdown / Plain Text (.md / .txt / stdin) Parser
# ---------------------------------------------------------------------------
def parse_markdown_text_to_spec(text: str, default_title: str = "Presentation") -> dict[str, Any]:
    lines = text.splitlines()
    h1_count = sum(1 for l in lines if l.strip().startswith("# ") and not l.strip().startswith("## "))
    deck_title = default_title
    current_chapter = ""
    raw_slides: list[dict[str, Any]] = []
    cur_slide: dict[str, Any] | None = None

    def flush_slide() -> None:
        nonlocal cur_slide
        if cur_slide and (cur_slide["title"] or cur_slide["bullets"] or cur_slide["notes_lines"]):
            raw_slides.append(cur_slide)
        cur_slide = None

    for raw_ln in lines:
        ln = raw_ln.strip()
        if not ln or ln.startswith("---") or re.match(r"^\|[\s\-:|]+\|$", ln):
            continue

        if ln.startswith("# ") and not ln.startswith("## "):
            h1 = ln[2:].strip()
            if not raw_slides and cur_slide is None and deck_title == default_title:
                deck_title = h1
                if h1_count > 1:
                    current_chapter = h1
            else:
                flush_slide()
                current_chapter = h1
            continue

        if ln.startswith(("## ", "### ")):
            flush_slide()
            title = ln.lstrip("#").strip()
            cur_slide = {
                "title": title,
                "chapter": current_chapter or title,
                "bullets": [],
                "notes_lines": [],
                "quote": "",
                "meta": {},
            }
            continue

        if cur_slide is None:
            cur_slide = {
                "title": deck_title,
                "chapter": current_chapter or deck_title,
                "bullets": [],
                "notes_lines": [],
                "quote": "",
                "meta": {},
            }

        m_tag = re.match(r"^\[([A-Z_]+):\s*(.+)\]$", ln)
        if m_tag:
            cur_slide["meta"][m_tag.group(1).upper()] = m_tag.group(2).strip()
        elif ln.startswith(">"):
            cur_slide["notes_lines"].append(ln.lstrip("> ").strip())
        elif ln.startswith(("- ", "* ", "β€’ ")):
            cur_slide["bullets"].append(ln[2:].strip())
        elif ln.startswith("|") and ln.endswith("|"):
            cells = [c.strip() for c in ln.strip("|").split("|") if c.strip()]
            if cells and cells[0].lower() not in ("ꡬ뢄", "ν•­λͺ©", "μ˜΅μ…˜", "방식", "κΈ°λŠ₯"):
                cur_slide["bullets"].append(" | ".join(cells))
            elif len(cells) >= 3 and "PLANS" not in cur_slide["meta"]:
                cur_slide["meta"]["PLANS"] = " | ".join(cells[1:4])
        else:
            if len(ln) > 50 and ln.endswith(("λ‹€.", "μš”.", "μ£ .", "!", "?")):
                cur_slide["notes_lines"].append(ln)
            else:
                cur_slide["bullets"].append(ln)

    flush_slide()
    return _compile_raw_slides_to_spec(deck_title, raw_slides)


def parse_markdown_to_spec(md_path: Path) -> dict[str, Any]:
    return parse_markdown_text_to_spec(md_path.read_text(encoding="utf-8-sig"), default_title=md_path.stem)


# ---------------------------------------------------------------------------
# 4. HTML Presentation / Web Article (.html / .htm) Parser
# ---------------------------------------------------------------------------
def parse_html_to_spec(html_path: Path) -> dict[str, Any]:
    from bs4 import BeautifulSoup

    soup = BeautifulSoup(html_path.read_text(encoding="utf-8"), "html.parser")
    for tag in soup(["script", "style", "noscript", "svg", "nav", "footer"]):
        tag.decompose()

    deck_title = (soup.title.string.strip() if soup.title and soup.title.string else "") or html_path.stem
    h1_first = soup.find("h1")
    if h1_first and h1_first.get_text(strip=True):
        deck_title = h1_first.get_text(" ", strip=True)

    raw_slides: list[dict[str, Any]] = []

    # Case A: Slide-based HTML (<section>, .slide, [data-slide])
    slide_nodes = soup.select("section, div.slide, article.slide, [data-slide]")
    # Filter out outer wrapper sections that contain nested <section> slides (like Reveal.js vertical stacks)
    leaf_slides = [
        node for node in slide_nodes
        if not node.find(["section"]) and node.get_text(strip=True)
    ]

    if leaf_slides:
        for idx, node in enumerate(leaf_slides):
            heading = node.find(["h1", "h2", "h3", "h4"])
            title = heading.get_text(" ", strip=True) if heading else f"μŠ¬λΌμ΄λ“œ {idx + 1}"
            chapter = node.get("data-chapter") or title

            notes_lines: list[str] = []
            if node.get("data-notes"):
                notes_lines.append(str(node["data-notes"]).strip())
            for aside in node.select("aside.notes, .speaker-notes, [data-narration]"):
                nt = aside.get_text("\n", strip=True)
                if nt:
                    notes_lines.extend([x.strip() for x in nt.splitlines() if x.strip()])
                aside.decompose()

            quote_txt = ""
            for bq in node.find_all("blockquote"):
                qt = bq.get_text(" ", strip=True)
                if qt and not quote_txt:
                    quote_txt = qt
                bq.decompose()

            bullets: list[str] = []
            for li in node.find_all("li"):
                t = li.get_text(" ", strip=True)
                if t:
                    bullets.append(t)
            for tr in node.find_all("tr"):
                cells = [td.get_text(" ", strip=True) for td in tr.find_all(["td", "th"]) if td.get_text(strip=True)]
                if len(cells) >= 2 and tr.find("td"):
                    bullets.append(" | ".join(cells[:2]))
            if not bullets:
                for p in node.find_all("p"):
                    pt = p.get_text(" ", strip=True)
                    if pt and pt != title:
                        if len(pt) > 55:
                            notes_lines.append(pt)
                        else:
                            bullets.append(pt)

            meta = {}
            if node.get("data-archetype"):
                meta["ARCHETYPE"] = str(node["data-archetype"]).strip()
            if node.get("data-badge"):
                meta["BADGE"] = str(node["data-badge"]).strip()
            if node.get("data-command"):
                meta["COMMAND"] = str(node["data-command"]).strip()

            raw_slides.append({
                "title": title,
                "chapter": chapter,
                "bullets": bullets or [title],
                "notes_lines": notes_lines,
                "quote": quote_txt,
                "meta": meta,
            })
        return _compile_raw_slides_to_spec(deck_title, raw_slides)

    # Case B: General Web Document / Article HTML (<h2>/<h3> sections)
    current_chapter = deck_title
    cur_slide: dict[str, Any] | None = None

    def flush_html_slide() -> None:
        nonlocal cur_slide
        if cur_slide and (cur_slide["bullets"] or cur_slide["notes_lines"] or cur_slide["title"]):
            raw_slides.append(cur_slide)
        cur_slide = None

    body = soup.body or soup
    for el in body.find_all(["h1", "h2", "h3", "li", "p", "blockquote", "pre", "code"], recursive=True):
        txt = el.get_text(" ", strip=True)
        if not txt:
            continue
        if el.name == "h1":
            current_chapter = txt
        elif el.name in ("h2", "h3"):
            flush_html_slide()
            cur_slide = {
                "title": txt,
                "chapter": current_chapter,
                "bullets": [],
                "notes_lines": [],
                "quote": "",
                "meta": {},
            }
        else:
            if cur_slide is None:
                cur_slide = {
                    "title": deck_title,
                    "chapter": current_chapter,
                    "bullets": [],
                    "notes_lines": [],
                    "quote": "",
                    "meta": {},
                }
            if el.name == "blockquote":
                cur_slide["quote"] = cur_slide["quote"] or txt
                cur_slide["notes_lines"].append(txt)
            elif el.name in ("pre", "code") and len(txt) < 120:
                cur_slide["meta"]["COMMAND"] = txt.splitlines()[0]
                cur_slide["meta"].setdefault("ARCHETYPE", "terminal_flow")
            elif el.name == "li":
                if txt not in cur_slide["bullets"]:
                    cur_slide["bullets"].append(txt)
            elif el.name == "p" and not el.find_parent(["li", "blockquote"]):
                if len(txt) > 50:
                    cur_slide["notes_lines"].append(txt)
                elif txt not in cur_slide["bullets"]:
                    cur_slide["bullets"].append(txt)

    flush_html_slide()
    return _compile_raw_slides_to_spec(deck_title, raw_slides)


# ---------------------------------------------------------------------------
# 5. Agent Handoff / DRM Bridge JSON Parser (.json / --stdin-json)
# ---------------------------------------------------------------------------
def parse_agent_json_to_spec(payload: Any, default_title: str = "Presentation") -> dict[str, Any]:
    """
    Accepts EITHER:
      1. Already-compiled DeckSpec JSON (contains 'chapters' + slides with 'beats' & 'archetype')
      2. Simplified Agent-Extracted DRM JSON:
         {"title": "...", "slides": [{"title": "...", "bullets": [...], "table": [[...]], "notes": "..."}]}
         or even a bare list of slide dicts: [{"title": "...", "bullets": [...], "notes": "..."}]
    """
    if isinstance(payload, dict) and "chapters" in payload and isinstance(payload.get("slides"), list):
        slides_check = payload["slides"]
        if slides_check and all(isinstance(s, dict) and "beats" in s and "archetype" in s for s in slides_check):
            return payload

    if isinstance(payload, list):
        deck_title = default_title
        slides_in = payload
        top_voice = ""
        top_rate = ""
        top_lang = ""
        top_glossary: dict[str, str] = {}
    elif isinstance(payload, dict):
        deck_title = str(payload.get("title") or payload.get("deck_title") or default_title).strip()
        slides_in = payload.get("slides") or payload.get("pages") or payload.get("sections") or []
        top_voice = str(payload.get("voice") or "").strip()
        top_rate = str(payload.get("voice_rate") or payload.get("rate") or "").strip()
        top_lang = str(payload.get("lang") or payload.get("language") or "").strip()
        top_glossary = payload.get("glossary") if isinstance(payload.get("glossary"), dict) else {}
    else:
        raise ValueError("JSON input must be a JSON object {'title': ..., 'slides': [...]} or a list of slide objects.")

    raw_slides: list[dict[str, Any]] = []
    for idx, s in enumerate(slides_in):
        if not isinstance(s, dict):
            continue
        title = str(s.get("title") or s.get("heading") or s.get("name") or f"μŠ¬λΌμ΄λ“œ {idx + 1}").strip()
        chapter = str(s.get("chapter") or s.get("section") or title).strip()
        meta: dict[str, str] = {}
        if isinstance(s.get("meta"), dict):
            for mk, mv in s["meta"].items():
                if mv is not None and str(mv).strip():
                    meta[str(mk).upper()] = str(mv).strip()

        key_map = {
            "archetype": "ARCHETYPE",
            "bg": "BG",
            "bg_preset": "BG",
            "badge": "BADGE",
            "subtitle": "SUBTITLE",
            "hero_word": "HERO_WORD",
            "scramble": "SCRAMBLE",
            "scramble_text": "SCRAMBLE",
            "source": "SOURCE",
            "source_note": "SOURCE",
            "media_caption": "MEDIA_CAPTION",
            "plans": "PLANS",
            "command": "COMMAND",
            "stamp": "STAMP",
            "stamp_text": "STAMP",
            "broll": "BROLL",
        }
        for src_k, dst_k in key_map.items():
            val = s.get(src_k)
            if val and str(val).strip() and str(val).strip().lower() != "auto":
                meta[dst_k] = str(val).strip()

        raw_bullets = s.get("bullets") or s.get("items") or s.get("points") or s.get("body") or []
        if isinstance(raw_bullets, str):
            bullets = [re.sub(r"^[-β€’*β–ͺ]\s*", "", ln.strip()) for ln in raw_bullets.splitlines() if ln.strip()]
        elif isinstance(raw_bullets, list):
            bullets = [str(b).strip() for b in raw_bullets if str(b).strip()]
        else:
            bullets = []

        tbl = s.get("table") or s.get("rows")
        if isinstance(tbl, list) and tbl:
            for r_i, row in enumerate(tbl):
                if isinstance(row, list):
                    cells = [str(c).strip().replace("\n", " ") for c in row if str(c).strip()]
                elif isinstance(row, str):
                    cells = [c.strip() for c in row.strip("|").split("|") if c.strip()]
                else:
                    cells = []
                if not cells:
                    continue
                if r_i == 0 and len(cells) >= 3 and "PLANS" not in meta and any(
                    h in cells[0].lower() for h in ["ꡬ뢄", "ν•­λͺ©", "비ꡐ", "κΈ°λŠ₯", "μ˜΅μ…˜", "방식", "category", "feature"]
                ):
                    meta["PLANS"] = " | ".join(cells[1:4])
                    continue
                bullets.append(" | ".join(cells))

        raw_notes = (
            s.get("notes")
            or s.get("notes_lines")
            or s.get("narration")
            or s.get("speaker_notes")
            or s.get("script")
            or []
        )
        if isinstance(raw_notes, str):
            notes_lines = [ln.strip() for ln in raw_notes.splitlines() if ln.strip()]
        elif isinstance(raw_notes, list):
            notes_lines = [str(n).strip() for n in raw_notes if str(n).strip()]
        else:
            notes_lines = []

        # Also support pre-structured beats [{"narration": "...", "sub_ko": "...", "sub_en": "..."}]
        if not notes_lines and isinstance(s.get("beats"), list):
            for b_obj in s["beats"]:
                if isinstance(b_obj, dict) and b_obj.get("narration"):
                    narr = str(b_obj["narration"]).strip()
                    en = str(b_obj.get("sub_en") or "").strip()
                    notes_lines.append(f"{narr} || {en}" if en else narr)

        media_src = str(s.get("media_src") or s.get("media") or s.get("image") or "").strip()
        quote = str(s.get("quote") or s.get("highlight_quote") or "").strip()

        raw_slides.append({
            "title": title,
            "chapter": chapter,
            "bullets": bullets,
            "notes_lines": notes_lines,
            "media_src": media_src,
            "quote": quote,
            "custom_svg": str(s.get("custom_svg") or "").strip(),
            "custom_html": str(s.get("custom_html") or "").strip(),
            "archify_json": str(s.get("archify_json") or "").strip(),
            "custom_anime_js": str(s.get("custom_anime_js") or "").strip(),
            "pronounce": s.get("pronounce") if isinstance(s.get("pronounce"), dict) else {},
            "meta": meta,
        })

    if raw_slides and deck_title == default_title and isinstance(payload, list):
        deck_title = raw_slides[0]["title"]

    compiled = _compile_raw_slides_to_spec(deck_title, raw_slides)
    if top_voice:
        compiled["voice"] = top_voice
    if top_rate:
        compiled["voice_rate"] = top_rate
    if top_lang:
        compiled["lang"] = top_lang
    if top_glossary:
        compiled["glossary"] = top_glossary
    return compiled


# ---------------------------------------------------------------------------
# Unified Dispatcher
# ---------------------------------------------------------------------------
def load_input_to_spec(input_path: Path, extract_ppt_images: bool = True) -> dict[str, Any]:
    suffix = input_path.suffix.lower()
    if suffix == ".json":
        raw_text = input_path.read_text(encoding="utf-8-sig")
        return parse_agent_json_to_spec(json.loads(raw_text), default_title=input_path.stem)
    if suffix == ".pptx":
        return parse_pptx_to_spec(input_path, extract_images=extract_ppt_images)
    if suffix == ".docx":
        return parse_docx_to_spec(input_path)
    if suffix in (".md", ".markdown", ".txt"):
        return parse_markdown_to_spec(input_path)
    if suffix in (".html", ".htm"):
        return parse_html_to_spec(input_path)
    raise ValueError(
        f"Unsupported input format '{suffix}'. Supported: .pptx, .docx, .md, .txt, .html, .htm, .json"
    )


# ---------------------------------------------------------------------------
# Pre-Production Deck Analyzer & Style Recommender (--analyze)
# ---------------------------------------------------------------------------
def analyze_deck_spec(spec: dict[str, Any], lang: str = "auto", glossary_path: str = "") -> dict[str, Any]:
    from deck_video_pipeline.themes_and_presets import STYLE_PACKS
    from deck_video_pipeline.pronunciation_engine import (
        LANGUAGE_REGISTRY,
        load_custom_glossary,
        prepare_display_and_tts_text,
        resolve_language_code,
    )

    slides = spec.get("slides", [])
    full_blob = " ".join(
        f"{s.get('title', '')} {' '.join(s.get('bullets', []))} {' '.join(b.get('narration', '') for b in s.get('beats', []))}"
        for s in slides
    )
    resolved_lang = resolve_language_code(lang if lang and lang != "auto" else spec.get("lang", ""), full_blob)
    base_glossary = load_custom_glossary(glossary_path or None, lang=resolved_lang)
    if isinstance(spec.get("glossary"), dict):
        base_glossary.update({str(k): str(v) for k, v in spec["glossary"].items()})
    full_blob = full_blob.lower()

    # Score style packs dynamically so every deck receives context-matched recommendations
    scores: dict[str, int] = {k: 10 for k in STYLE_PACKS}
    if any(k in full_blob for k in ["보고", "싀적", "μ˜ˆμ‚°", "λΆ„κΈ°", "μž„μ›", "경영", "곡곡", "μ„±κ³Ό", "λŒ€ν•™"]):
        scores["executive_light"] += 35
        scores["apple_keynote"] += 15
    if any(k in full_blob for k in ["μ—…λ°μ΄νŠΈ", "릴리즈", "버전", "λͺ¨λΈ", "κΈ°λŠ₯", "μΆœμ‹œ", "api", "μ½”λ”©", "μ—μ΄μ „νŠΈ"]):
        scores["tech_deepdive"] += 32
        scores["interactive_creator"] += 24
    if any(k in full_blob for k in ["νŠΉν—ˆ", "λ…Όλž€", "μ‚¬νšŒ", "역사", "인간", "미래", "사건", "μŠ€ν† λ¦¬", "μ§„μ‹€", "μœ„ν—˜"]):
        scores["docu_storytelling"] += 38
    if any(k in full_blob for k in ["μˆ˜μ‹¬", "탐사", "κ³Όν•™", "μ§€μ§ˆ", "ν™”μ‚°", "팩트", "검증", "츑심", "λ―ΈμŠ€ν„°λ¦¬", "기둝", "λ°”λ‹₯"]):
        if "deepfact_docu" in scores:
            scores["deepfact_docu"] += 42
    if any(k in full_blob for k in ["μ•„ν‚€ν…μ²˜", "섀계", "νŒŒμ΄ν”„λΌμΈ", "원리", "인프라", "μ„œλ²„", "ν”„λ‘œν† μ½œ", "λ³΄μ•ˆ", "ꡬ쑰"]):
        scores["engineering_blueprint"] += 36
        scores["tech_deepdive"] += 18
    if any(k in full_blob for k in ["ꡐ윑", "κ°€μ΄λ“œ", "νŠœν† λ¦¬μ–Ό", "μ‹€μŠ΅", "μž…λ¬Έ", "μ˜¨λ³΄λ”©", "팁"]):
        scores["interactive_creator"] += 30
        scores["executive_light"] += 14
    if len(slides) <= 5 and sum(len(s.get("bullets", [])) for s in slides) <= 15:
        scores["apple_keynote"] += 22

    ranked_packs = sorted(STYLE_PACKS.items(), key=lambda kv: scores[kv[0]], reverse=True)

    slide_plans: list[dict[str, Any]] = []
    viz_candidates: list[dict[str, Any]] = []
    total_chars = 0

    for idx, s in enumerate(slides):
        s_txt = f"{s.get('title', '')} {' '.join(s.get('bullets', []))}".lower()
        narr_txt = " ".join(b.get("narration", "") for b in s.get("beats", []))
        total_chars += len(narr_txt)

        viz_suggestion = ""
        if any(k in s_txt for k in ["μ•„ν‚€ν…μ²˜", "ꡬ쑰", "νŒŒμ΄ν”„λΌμΈ", "연동", "흐름", "λ ˆμ΄μ–΄", "λ„€νŠΈμ›Œν¬", "μ‹œμŠ€ν…œ"]):
            viz_suggestion = "Archify μ‹œμŠ€ν…œ μ•„ν‚€ν…μ²˜ λ‹€μ΄μ–΄κ·Έλž¨ (viz_skills/archify λ˜λŠ” archify_architecture)"
        elif any(k in s_txt for k in ["원리", "μž‘λ™", "λ©”μ»€λ‹ˆμ¦˜", "μ—”μ§„", "검증", "잠금", "ν•„ν„°", "λ‚΄λΆ€"]):
            viz_suggestion = "Anatomy μ•„μ΄μ†Œλ©”νŠΈλ¦­ 기계 μž‘λ™ 도식 (viz_skills/anatomy λ˜λŠ” anatomy_mechanic)"
        elif any(k in s_txt for k in ["좔이", "μ„±μž₯", "μ§€ν‘œ", "%", "λ°°", "톡계", "비ꡐ", "단좕"]):
            viz_suggestion = "Anime.js μ‹€μ‹œκ°„ λ“œλ‘œμž‰ νŠΈλ Œλ“œ 차트 (anime_svg_chart)"

        if viz_suggestion:
            viz_candidates.append({
                "slide_num": idx + 1,
                "title": s.get("title", ""),
                "suggested_tool": viz_suggestion,
            })

        slide_gloss = dict(base_glossary)
        if isinstance(s.get("pronounce_map"), dict):
            slide_gloss.update(s["pronounce_map"])
        s_lang = resolve_language_code(s.get("lang") or resolved_lang, narr_txt)
        beat_pairs = []
        for b in s.get("beats", []):
            disp_b, tts_b = prepare_display_and_tts_text(b.get("narration", ""), lang=s_lang, custom_glossary=slide_gloss)
            beat_pairs.append({"display": disp_b, "tts_phonetic": tts_b})

        slide_plans.append({
            "slide_num": idx + 1,
            "title": s.get("title", ""),
            "bullets": s.get("bullets", []),
            "bullets_count": len(s.get("bullets", [])),
            "default_archetype": s.get("archetype", ""),
            "has_media": bool(s.get("media_src")),
            "viz_upgrade_hint": viz_suggestion,
            "full_narration_beats": [bp["display"] for bp in beat_pairs],
            "tts_phonetic_beats": [bp["tts_phonetic"] for bp in beat_pairs],
            "narration_preview": narr_txt,
        })

    est_sec = max(12, int(round(total_chars * 0.16 + len(slides) * 1.2)))
    lang_info = LANGUAGE_REGISTRY.get(resolved_lang, LANGUAGE_REGISTRY["ko"])
    return {
        "title": spec.get("title", "Presentation"),
        "lang_code": resolved_lang,
        "lang_label": f"{lang_info['name_ko']} ({lang_info['name_en']})",
        "slide_count": len(slides),
        "estimated_duration_sec": est_sec,
        "recommended_style_packs": [
            {"id": k, "score": scores[k], **v}
            for k, v in ranked_packs[:4]
        ],
        "viz_candidates": viz_candidates,
        "slides": slide_plans,
    }


def format_analysis_report_md(analysis: dict[str, Any]) -> str:
    lines = [
        f"# 🎬 ν”„λ¦¬ν”„λ‘œλ•μ…˜ 자료 뢄석 & λŒ€λ³Έ/발음 기획 리포트: {analysis['title']}",
        f"- **총 μŠ¬λΌμ΄λ“œ 수**: {analysis['slide_count']}μž₯ | **μ˜ˆμƒ μ˜μƒ 길이**: μ•½ {analysis['estimated_duration_sec']}초 | **감지/μ§€μ • μ–Έμ–΄**: `{analysis.get('lang_code', 'ko')}` ({analysis.get('lang_label', 'ν•œκ΅­μ–΄')})",
        "",
        "## 1. λ¬Έμ„œ λ‚΄μš© 기반 λ§žμΆ€ν˜• μΆ”μ²œ μŠ€νƒ€μΌ 팩 (Top 4)",
    ]
    for rank, sp in enumerate(analysis["recommended_style_packs"], 1):
        lines.append(
            f"{rank}. **`--style-pack {sp['id']}` ({sp['label']})**\n"
            f"   - ꡬ성: λ°°κ²½=`{sp['bg']}`, 상단HUD=`{sp['hud_style']}`, μžλ§‰=`{sp['caption_style']}`, μΆ”μ²œμ„±μš°=`{sp['voice']}`\n"
            f"   - νŠΉμ§•: {sp['desc']}"
        )

    lines.append("\n## 2. μŠ¬λΌμ΄λ“œλ³„ ν™”λ©΄ ꡬ성 & 전체 λŒ€μ‚¬/발음 λ³€ν™˜ μ΄ˆμ•ˆ (μ‚¬μš©μž κ²€μˆ˜μš© μ „λ¬Έ)")
    for sp in analysis["slides"]:
        viz_note = f" βž” πŸ’‘ **[μ‹œκ°ν™” μΆ”μ²œ: {sp['viz_upgrade_hint']}]**" if sp["viz_upgrade_hint"] else ""
        lines.append(
            f"- **Slide {sp['slide_num']:02d} [{sp['default_archetype']}]** `{sp['title']}` (ν™”λ©΄ ν•­λͺ© {sp['bullets_count']}개){viz_note}"
        )
        disp_list = sp.get("full_narration_beats", [])
        phon_list = sp.get("tts_phonetic_beats", [])
        for b_i, b_line in enumerate(disp_list, 1):
            lines.append(f"  - [μžλ§‰ ν‘œκΈ° {b_i}] \"{b_line}\"")
            if b_i <= len(phon_list) and phon_list[b_i - 1] != b_line:
                lines.append(f"    ↳ πŸ”Š [μ„±μš° μ‹€μ œ 발음 {b_i}] \"{phon_list[b_i - 1]}\"")

    lines.append(
        "\n## 3. [AI μ—μ΄μ „νŠΈ ν•„μˆ˜ μ•‘μ…˜] λ Œλ”λ§ μ „ μ‚¬μš©μž 확인 & 인터뷰 체크리슀트\n"
        "μœ„ 뢄석 κ²°κ³Όλ₯Ό λ°”νƒ•μœΌλ‘œ **μ ˆλŒ€ λ°”λ‘œ μ˜μƒμ„ λ Œλ”λ§ν•˜μ§€ 말고**, μ‚¬μš©μžμ—κ²Œ μ•„λž˜ 4κ°€μ§€λ₯Ό λ¨Όμ € ν™•μΈλ°›μœΌμ„Έμš”:\n"
        "1. **μ˜μƒ μŠ€νƒ€μΌ & λΆ„μœ„κΈ°**: μΆ”μ²œ μŠ€νƒ€μΌ 팩(1~4번) 쀑 μ–΄λ–€ λ””μžμΈμœΌλ‘œ μ œμž‘ν• κΉŒμš”?\n"
        "2. **λ‚΄λ ˆμ΄μ…˜(μŒμ„±) & μžλ§‰ ꡬ성 λͺ¨λ“œ**:\n"
        "   - β‘  μ„±μš° λ‚΄λ ˆμ΄μ…˜ + ν•˜λ‹¨ μžλ§‰ λͺ¨λ‘ 포함 (κΈ°λ³Έ)\n"
        "   - β‘‘ μ„±μš° λ‚΄λ ˆμ΄μ…˜λ§Œ 포함, ν•˜λ‹¨ μžλ§‰ μˆ¨κΉ€ (`--no-subtitles`)\n"
        "   - β‘’ μ„±μš° μŒμ„± 없이 μžλ§‰ + λ°°κ²½μŒμ•…/효과음만 포함 (`--no-voice`)\n"
        "   - β‘£ μŒμ„±Β·μžλ§‰ λͺ¨λ‘ 없이 순수 λͺ¨μ…˜ κ·Έλž˜ν”½ + λ°°κ²½μŒμ•…/효과음 쇼릴 (`--no-voice --no-subtitles`)\n"
        "3. **λŒ€μ‚¬/슀크립트 κ²€μˆ˜**: μœ„ 2번 μ„Ήμ…˜μ˜ μŠ¬λΌμ΄λ“œλ³„ λŒ€μ‚¬/μžλ§‰ μ „λ¬Έ 쀑 μˆ˜μ •ν•˜κ±°λ‚˜ 닀듬고 싢은 λ¬Έμž₯이 μžˆλ‚˜μš”? (μŒμ„± 포함 μ‹œ μ„±μš° `M1~M5` / `F1~F5` 선택 포함)\n"
        "4. **λ§žμΆ€ν˜• μ‹œκ°ν™” μΆ”κ°€ μ—¬λΆ€**: μΆ”μ²œλœ μŠ¬λΌμ΄λ“œμ— `Archify`(μ•„ν‚€ν…μ²˜), `Anatomy`(기계 단면도), `Anime.js`(μ‹€μ‹œκ°„ λ“œλ‘œμž‰ 차트) μ‹œκ°ν™”λ₯Ό μ œμž‘ν•΄ ν¬ν•¨ν• κΉŒμš”?"
    )
    return "\n".join(lines)


# ---------------------------------------------------------------------------
# Sample Template Generators (PPTX, DOCX, HTML)
# ---------------------------------------------------------------------------
def create_sample_pptx(output_pptx: Path) -> Path:
    from pptx import Presentation

    output_pptx.parent.mkdir(parents=True, exist_ok=True)
    prs = Presentation()
    layout = prs.slide_layouts[1]

    sample_slides = [
        {
            "title": "AI ꡐ윑 μ—μ΄μ „νŠΈ 9μ’…",
            "body": [
                "[CHAPTER: 01 μ—μ΄μ „νŠΈ ꡰ체]",
                "[ARCHETYPE: arc_cards]",
                "[BADGE: PPTX Γ— HyperFrames Engine]",
                "[STAT_PREFIX: AI μ œμž‘ λͺ¨λ“ˆ]",
                "[STAT_NUM: 9]",
                "[STAT_SUFFIX: μ’…]",
                "κ΅μ•ˆλΆ„μ„ | μŠ¬λΌμ΄λ“œ ꡬ쑰 μΆ”μΆœ",
                "λŒ€λ³Έμ„€κ³„ | λ°œν‘œ λ…ΈνŠΈ 호흑 λΆ„ν• ",
                "λͺ¨μ…˜μ—”μ§„ | HTML 3D μΊ”λ²„μŠ€ 생성",
                "μ„±μš°ν•©μ„± | μžμ—°μŠ€λŸ¬μš΄ λ‚΄λ ˆμ΄μ…˜",
                "νš¨κ³ΌμŒλ΄‡ | μ „ν™˜Β·νŒμ—… μ‚¬μš΄λ“œ 싱크",
                "μžλ§‰μ—”μ§„ | ν•œΒ·μ˜ 이쀑 μžλ§‰ μ •λ ¬",
                "차트λͺ¨λ“ˆ | 숫자 μΉ΄μš΄νŠΈμ—… μ—°μΆœ",
                "BGM덕킹 | λ°°κ²½μŒμ•… λ³Όλ₯¨ μžλ™μ‘°μ ˆ",
                "λ Œλ”λŸ¬ | 1080p 무손싀 MP4 μΆ”μΆœ",
            ],
            "notes": (
                "νŒŒμ›Œν¬μΈνŠΈ κ΅μ•ˆλ§Œ λ„£μœΌλ©΄ 아홉 개의 AI λͺ¨λ“ˆμ΄ λ™μ‹œμ— μ›€μ§μž…λ‹ˆλ‹€. || Put in a PowerPoint deck, and 9 AI modules spring into action.\n"
                "μ •μ§€λœ μŠ¬λΌμ΄λ“œλ₯Ό μ½”λ“œ 기반 λͺ¨μ…˜ μ˜μƒμœΌλ‘œ μžλ™ λ³€ν™˜ν•΄ μ£Όμ£ . || Turning static slides into code-rendered motion videos automatically."
            ),
        },
        {
            "title": "μ™œ κΈ°μ‘΄ κ°•μ˜ μ˜μƒ μ œμž‘μ€ 였래 κ±Έλ Έμ„κΉŒ",
            "body": [
                "[CHAPTER: 02 병λͺ© 진단]",
                "[ARCHETYPE: mockup_steps]",
                "[BADGE: Lecture Deck Analysis]",
                "μ •μ§€λœ PPT λ…Ήν™”μ˜ ν•œκ³„ | ν™”λ©΄ λ³€ν™”κ°€ μ—†μ–΄ 초반 μ‹œμ²­ 지속λ₯  급락",
                "μˆ˜λ™ μ˜μƒ νŽΈμ§‘μ˜ 병λͺ© | μžλ§‰κ³Ό 효과음 싱크λ₯Ό μ†μœΌλ‘œ λ§žμΆ”λŠλΌ μ‹œκ°„ μ†Œλͺ¨",
                "μ½”λ“œ 기반 SYNC μžλ™ν™” | λŒ€λ³Έ νƒ€μž„μŠ€νƒ¬ν”„μ— 맞좰 μΉ΄λ“œμ™€ μ‚¬μš΄λ“œκ°€ μ¦‰μ‹œ λ°˜μ‘",
            ],
            "notes": (
                "기쑴에 PPTλ₯Ό λ„μ›Œλ†“κ³  ν™”λ©΄λ§Œ λ…Ήν™”ν•˜λ©΄ μ‹œμ²­μžκ°€ 금방 μ§€λ£¨ν•΄μ§‘λ‹ˆλ‹€. || Recording static PPT slides quickly loses viewer attention.\n"
                "κ·Έλ ‡λ‹€κ³  ν”„λ¦¬λ―Έμ–΄λ‘œ μΉ΄λ“œμ™€ νš¨κ³ΌμŒμ„ 일일이 λ§žμΆ”λ©΄ νŽΈμ§‘ μ‹œκ°„μ΄ μ—΄ 배둜 λŠ˜μ–΄λ‚˜μ£ . || Yet syncing cards and SFX manually in Premiere takes 10x longer.\n"
                "해결책은 μŒμ„±κ³Ό ν™”λ©΄, νš¨κ³ΌμŒμ„ μ½”λ“œλ‘œ ν•œ λ²ˆμ— λ™κΈ°ν™”ν•˜λŠ” κ²ƒμž…λ‹ˆλ‹€. || The answer is syncing voice, visuals, and SFX together in code."
            ),
        },
        {
            "title": "λ°˜λ³΅λ˜λŠ” νŽΈμ§‘ κ·œμΉ™μ€ 맀뉴얼과 μ½”λ“œλ‘œ 남긴닀",
            "body": [
                "[CHAPTER: 03 SYNC 원칙]",
                "[ARCHETYPE: book_quote]",
                "[BADGE: CHAPTER 03 Β· DESIGN SYSTEM]",
                "[QUOTE: 같은 λ””μžμΈκ³Ό νŽΈμ§‘μ„ 두 번 λ°˜λ³΅ν–ˆλ‹€λ©΄, 이제 κ·Έ μž‘μ—…μ€ νƒ€μž„λΌμΈμ΄ μ•„λ‹ˆλΌ μ½”λ“œ ν…œν”Œλ¦Ώμ— μžˆμ–΄μ•Ό ν•œλ‹€.]",
                "상단 챕터 진행바와 ν•˜λ‹¨ 이쀑 μžλ§‰ λ ˆμ΄μ•„μ›ƒμ„ κ³ μ • κ·œμΉ™μœΌλ‘œ μžμ‚°ν™”",
                "κ΅μ•ˆ ν…μŠ€νŠΈλ§Œ λ°”λ€Œμ–΄λ„ μΌκ΄€λœ λΈŒλžœλ“œ ν†€μ•€λ§€λ„ˆμ™€ 가독성 100% μœ μ§€",
            ],
            "notes": (
                "맀번 같은 μŠ€νƒ€μΌμ˜ κ°•μ‘° νš¨κ³Όμ™€ μžλ§‰μ„ μ†μœΌλ‘œ 찍고 μžˆλ‹€λ©΄ λ°”κΏ”μ•Ό ν•©λ‹ˆλ‹€. || If you repeat the same highlights and captions by hand, change the workflow.\n"
                "λ””μžμΈ κ·œμΉ™κ³Ό 효과음 타이밍을 μ½”λ“œ ν…œν”Œλ¦ΏμœΌλ‘œ 남겨두면 κ΅μ•ˆλ§Œ λ°”κΏ” 계속 μ“Έ 수 μžˆμŠ΅λ‹ˆλ‹€. || Once baked into a code template, any new deck inherits the exact same polish."
            ),
        },
        {
            "title": "λͺ…λ Ήμ–΄ ν•œ μ€„λ‘œ λλ‚˜λŠ” PPTX μ˜μƒ λ³€ν™˜ νŒŒμ΄ν”„λΌμΈ",
            "body": [
                "[CHAPTER: 04 μžλ™ λ³€ν™˜]",
                "[ARCHETYPE: terminal_flow]",
                "[BADGE: Automated CLI Pipeline]",
                "[COMMAND: python3 produce_deck_video.py --input lecture.pptx --sfx on]",
                "[FLOW_LEFT: ꡐ윑자료 · PPTX]",
                "[FLOW_LEFT_SUB: μŠ¬λΌμ΄λ“œ Β· λ°œν‘œλ…ΈνŠΈ νŒŒμ‹±]",
                "[FLOW_RIGHT: 1080p λͺ¨μ…˜ MP4]",
                "[FLOW_RIGHT_SUB: HTML λ Œλ”λ§ + UI 효과음]",
                "μŠ¬λΌμ΄λ“œ 제λͺ©Β·λ³Έλ¬ΈΒ·λ°œν‘œμž λ…ΈνŠΈλ₯Ό 읽어 씬 λ ˆμ΄μ•„μ›ƒ μžλ™ λ°°μ •",
                "μ „ν™˜ μŠ€μš°μ‹œ, μΉ΄λ“œ 포컀슀 팝, 타이핑 μ‚¬μš΄λ“œλ₯Ό 0.01초 λ‹¨μœ„λ‘œ 배치",
            ],
            "notes": (
                "μ‹€μ œ μ‚¬μš©λ²•μ€ μ•„μ£Ό κ°„λ‹¨ν•©λ‹ˆλ‹€. κ΅μœ‘μžλ£Œλ‚˜ νŒŒμ›Œν¬μΈνŠΈ 파일 ν•˜λ‚˜λ§Œ μ§€μ •ν•΄ μ£Όμ„Έμš”. || Usage is simple: just point the pipeline at your PPTX or lesson file.\n"
                "엔진이 μŠ¬λΌμ΄λ“œ ꡬ쑰λ₯Ό 뢄석해 HTML λͺ¨μ…˜κ³Ό νš¨κ³ΌμŒκΉŒμ§€ μž…νžŒ MP4 μ˜μƒμ„ λ°”λ‘œ λ½‘μ•„λƒ…λ‹ˆλ‹€. || It parses your slides and renders an MP4 complete with HTML motion and UI SFX."
            ),
        },
        {
            "title": "μ•žμœΌλ‘œ ꡐ윑 μ˜μƒ μ œμž‘μ΄ λ°”λ€ŒλŠ” 3단계",
            "body": [
                "[CHAPTER: 05 핡심 μš”μ•½]",
                "[ARCHETYPE: metric_summary]",
                "[BADGE: Ready For Production]",
                "[SUBTITLE: 자료 μž…λ ₯λΆ€ν„° 효과음 λ§ˆμŠ€ν„°λ§κΉŒμ§€ μ›μŠ€ν†± μžλ™ν™”]",
                "κ΅μ•ˆ μž…λ ₯ | PPTX Β· μ›Œλ“œ Β· λ§ˆν¬λ‹€μš΄ Β· HTML 지원",
                "λͺ¨μ…˜Β·νš¨κ³ΌμŒ | 3D μ›¨μ΄λΈŒΒ·λ„€μ˜¨ μΉ΄λ“œΒ·μ‚¬μš΄λ“œ μžλ™ 싱크",
                "κ³ ν™”μ§ˆ λ Œλ”λ§ | λŠκΉ€ μ—†λŠ” 1080p MP4 μ˜μƒ μ¦‰μ‹œ μ™„μ„±",
            ],
            "notes": (
                "이제 νŒŒμ›Œν¬μΈνŠΈλ‚˜ μ›Œλ“œ κ΅μ•ˆλ§Œ μ€€λΉ„ν•˜μ‹œλ©΄ λͺ¨μ…˜ κ·Έλž˜ν”½κ³Ό νš¨κ³ΌμŒμ€ νŒŒμ΄ν”„λΌμΈμ΄ λ§‘μŠ΅λ‹ˆλ‹€. || Prepare your PPTX or Word docsβ€”the pipeline handles motion and SFX.\n"
                "μ–Έμ œλ“  μƒˆλ‘œμš΄ ꡐ윑자료λ₯Ό λ„£μ–΄ 같은 포맷의 κ³ ν’ˆμ§ˆ ν”„λ ˆμ  ν…Œμ΄μ…˜ μ˜μƒμ„ λ§Œλ“€μ–΄ λ³΄μ„Έμš”! || Feed in any future training deck to produce sleek presentation videos anytime!"
            ),
        },
    ]

    for s in sample_slides:
        slide = prs.slides.add_slide(layout)
        slide.shapes.title.text = s["title"]
        tf = slide.placeholders[1].text_frame
        tf.clear()
        for idx, line in enumerate(s["body"]):
            p = tf.paragraphs[0] if idx == 0 else tf.add_paragraph()
            p.text = line
        slide.notes_slide.notes_text_frame.text = s["notes"]

    prs.save(str(output_pptx))
    return output_pptx


def create_sample_docx(output_docx: Path) -> Path:
    from docx import Document

    output_docx.parent.mkdir(parents=True, exist_ok=True)
    doc = Document()
    doc.add_heading("AI λ¬Έμ„œ μžλ™ μ˜μƒν™” κ°€μ΄λ“œ", 0)

    doc.add_heading("01 닀쀑 포맷 μž…λ ₯", level=1)
    doc.add_heading("λ„€ κ°€μ§€ 싀무 λ¬Έμ„œλ₯Ό κ·ΈλŒ€λ‘œ μ˜μƒμœΌλ‘œ", level=2)
    doc.add_paragraph("νŒŒμ›Œν¬μΈνŠΈ | λ°œν‘œ μŠ¬λΌμ΄λ“œμ™€ λ°œν‘œμž λ…ΈνŠΈ μžλ™ μΆ”μΆœ", style="List Bullet")
    doc.add_paragraph("μ›Œλ“œ λ¬Έμ„œ | 제λͺ© μŠ€νƒ€μΌκ³Ό ν‘œΒ·λ³Έλ¬Έ 단락 ꡬ쑰화", style="List Bullet")
    doc.add_paragraph("λ§ˆν¬λ‹€μš΄ Β· HTML | 기술 λ¬Έμ„œμ™€ μ›Ή μŠ¬λΌμ΄λ“œ μ¦‰μ‹œ νŒŒμ‹±", style="List Bullet")
    doc.add_paragraph("> μ‹€λ¬΄μ—μ„œ 이미 μ“°λ˜ μ›Œλ“œ κΈ°νšμ„œλ‚˜ ꡐ윑 κ΅μ•ˆμ„ μƒˆλ‘œ νŽΈμ§‘ν•  ν•„μš”κ°€ μ—†μŠ΅λ‹ˆλ‹€. || No need to re-edit existing Word specs or training docs.")

    doc.add_heading("02 핡심 원칙", level=1)
    doc.add_heading("λ¬Έμ„œ ꡬ쑰가 κ³§ λͺ¨μ…˜ μŠ€ν† λ¦¬λ³΄λ“œκ°€ λœλ‹€", level=2)
    doc.add_paragraph("같은 λ ˆμ΄μ•„μ›ƒ μž‘μ—…μ„ 두 번 λ°˜λ³΅ν•˜μ§€ 말고 μ½”λ“œ νŒŒμ΄ν”„λΌμΈμ— λ§‘κΈ΄λ‹€.", style="Quote")
    doc.add_paragraph("제λͺ©μ€ 챕터 λ°”λ‘œ, λͺ©λ‘μ€ λ„€μ˜¨ 포컀슀 μΉ΄λ“œλ‘œ μžλ™ λ§€ν•‘λ©λ‹ˆλ‹€.")

    doc.save(str(output_docx))
    return output_docx


def create_sample_html_slides(output_html: Path) -> Path:
    output_html.parent.mkdir(parents=True, exist_ok=True)
    content = """<!doctype html>
<html lang="ko">
<head><meta charset="utf-8"><title>μ›Ή μŠ¬λΌμ΄λ“œ μ˜μƒ λ³€ν™˜ μƒ˜ν”Œ</title></head>
<body>
  <section data-chapter="μ›Ή μŠ¬λΌμ΄λ“œ" data-badge="HTML Deck Import">
    <h2>HTML ν”„λ ˆμ  ν…Œμ΄μ…˜λ„ κ·ΈλŒ€λ‘œ MP4둜</h2>
    <ul>
      <li>μ„Ήμ…˜ μžλ™ 인식 | Reveal.js 및 일반 μ›Ή μŠ¬λΌμ΄λ“œ νƒœκ·Έ νŒŒμ‹±</li>
      <li>λ°œν‘œ λ…ΈνŠΈ 연동 | aside.notes νƒœκ·Έλ₯Ό 읽어 μ„±μš° λ‚΄λ ˆμ΄μ…˜ ν•©μ„±</li>
      <li>효과음 κ²°ν•© | ν™”λ©΄ μ „ν™˜κ³Ό μΉ΄λ“œ ν¬μ»€μŠ€μ— 맞좰 UI μ‚¬μš΄λ“œ λ―Ήμ‹±</li>
    </ul>
    <aside class="notes">
      μ›ΉμœΌλ‘œ λ§Œλ“  HTML λ°œν‘œ μžλ£Œλ„ λͺ…λ Ήμ–΄ ν•œ 쀄이면 효과음이 λ“€μ–΄κ°„ MP4 μ˜μƒμœΌλ‘œ λ³€ν™˜λ©λ‹ˆλ‹€. || Even HTML slide decks convert into SFX-synced MP4 videos in a single command.
    </aside>
  </section>
</body>
</html>
"""
    output_html.write_text(content, encoding="utf-8")
    return output_html