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
 
 
b1407d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92accb6
 
 
 
548af4c
92accb6
 
 
548af4c
 
92accb6
 
 
548af4c
 
92accb6
 
 
 
548af4c
 
92accb6
 
 
 
 
548af4c
92accb6
 
 
 
 
 
 
2a16edf
672d8c1
92accb6
 
 
 
 
 
 
 
 
ace0412
 
92accb6
 
 
 
 
 
 
 
 
 
 
 
 
 
71f2a63
 
92accb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec03d6a
92accb6
548af4c
92accb6
 
 
 
 
 
 
 
 
 
548af4c
 
92accb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
548af4c
 
92accb6
 
 
 
548af4c
 
 
 
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
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
import os
import re
import time
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Generator, Optional

import anthropic
import gradio as gr
from anthropic import Anthropic
from docx import Document


# =========================================================
# SETTINGS
# =========================================================

MIN_WORDS = 2000
MAX_WORDS = 2400
TARGET_WORDS = 2300
CHANNEL_NAME = "The Saster"

API_TIMEOUT_SECONDS = 420
MAX_WEB_SEARCHES = 10
MAX_STYLE_CHARACTERS = 50_000
STREAM_UPDATE_INTERVAL = 0.8

RESEARCH_MAX_TOKENS = 12_000
PLAN_MAX_TOKENS = 12_000
CHUNK_MAX_TOKENS = 11_000
REVISION_MAX_TOKENS = 12_000

MAX_HISTORICAL_CONTEXT_PERCENT = 10
MAX_OLD_YEAR_MENTIONS = 2

MODEL_OPTIONS = [
    "claude-sonnet-5",
    "claude-opus-5",
]

RECENCY_OPTIONS = {
    "Last 30 days": 30,
    "Last 90 days": 90,
    "Last 180 days": 180,
    "Last 365 days": 365,
}

DEFAULT_RECENCY_OPTION = "Last 90 days"

NEWS_BALANCE_OPTIONS = {
    "Historical disaster β€” no current-news requirement": {
        "recent_anchor_min": 0,
        "recent_anchor_max": 0,
        "recent_narration_share": "0 percent required",
        "date_mentions_min": 4,
        "date_mentions_max": 18,
        "current_source_target": "0",
        "description": (
            "Reconstruct the disaster itself using the strongest available historical evidence, "
            "official reports, archives, scientific records, eyewitness material, and later "
            "investigations. Do not search for or force a current-news angle. Present-day context "
            "may appear only when it genuinely helps the ending."
        ),
    },
    "Historical + optional present-day context": {
        "recent_anchor_min": 0,
        "recent_anchor_max": 1,
        "recent_narration_share": "roughly 0–10 percent",
        "date_mentions_min": 4,
        "date_mentions_max": 18,
        "current_source_target": "0–3",
        "description": (
            "Tell the historical disaster as a complete reconstruction first. Optionally add a "
            "brief present-day update about rebuilding, changed defenses, surviving risks, or new "
            "research when it materially improves the ending."
        ),
    },
    "Balanced β€” documentary + recent updates": {
        "recent_anchor_min": 1,
        "recent_anchor_max": 3,
        "recent_narration_share": "roughly 15–35 percent",
        "date_mentions_min": 4,
        "date_mentions_max": 16,
        "current_source_target": "3–6",
        "description": (
            "Tell the disaster as a complete narrative first, then weave in a small number of "
            "meaningful current developments, rebuilt systems, new findings, anniversaries, "
            "or present-day risks."
        ),
    },
    "News-first β€” more current detail": {
        "recent_anchor_min": 3,
        "recent_anchor_max": 5,
        "recent_narration_share": "roughly 35–55 percent",
        "date_mentions_min": 5,
        "date_mentions_max": 18,
        "current_source_target": "5–9",
        "description": (
            "Use a current development as the reason to revisit the disaster, while still "
            "telling the historical event as a coherent human and technical story."
        ),
    },
}

DEFAULT_NEWS_BALANCE_OPTION = "Historical disaster β€” no current-news requirement"

HOOK_OPTIONS = [
    "Auto β€” choose the strongest cinematic opening",
    "Cinematic date + place opening",
    "Immediate disaster scene",
    "Warning / failure foreshadowing",
    "News clip continuation",
    "Hard fact / consequence opening",
]

DEFAULT_HOOK_OPTION = "Auto β€” choose the strongest cinematic opening"

VIDEO_FORMAT_OPTIONS = {
    "Standard documentary β€” 7 sections": {
        "section_count": 7,
        "chunk_sections": [2, 3, 2],
        "list_mode": False,
        "label": "sections",
    },
    "List documentary β€” 10 subtopics": {
        "section_count": 10,
        "chunk_sections": [3, 4, 3],
        "list_mode": True,
        "label": "subtopics",
    },
    "List documentary β€” 20 subtopics": {
        "section_count": 20,
        "chunk_sections": [7, 7, 6],
        "list_mode": True,
        "label": "subtopics",
    },
    "List documentary β€” 30 subtopics": {
        "section_count": 30,
        "chunk_sections": [10, 10, 10],
        "list_mode": True,
        "label": "subtopics",
    },
}

DEFAULT_VIDEO_FORMAT_OPTION = "Standard documentary β€” 7 sections"


# The three minimum values add up to exactly 2,900 words.
# The maximum values add up to exactly 3,200 words.
CHUNK_SPECS = [
    {
        "number": 1,
        "minimum": 900,
        "maximum": 1000,
        "target": 950,
        "purpose": (
            "Write a cinematic cold-open introduction of 130–180 words and the first "
            "two titled sections. Do not mention the channel in the introduction. Follow "
            "the selected hook strategy. Begin inside a specific moment, place, warning, "
            "failure, or consequence, then widen into the context needed to understand what "
            "is about to happen. Make the first two sections deliberately unequal in length."
        ),
    },
    {
        "number": 2,
        "minimum": 1000,
        "maximum": 1100,
        "target": 1050,
        "purpose": (
            "Write the next three titled sections. This is the core escalation of the "
            "documentary: track the event chronology, failure chain, scientific or engineering "
            "mechanisms, response, and human consequences with dense specific detail. Make all "
            "three sections clearly unequal in length. Do not recap part 1 and do not insert a CTA."
        ),
    },
    {
        "number": 3,
        "minimum": 1000,
        "maximum": 1100,
        "target": 1050,
        "purpose": (
            "Write the final two titled sections and an ending of 120–180 words. "
            "Cover the aftermath, accountability, rebuilding, lessons, unresolved risk, or "
            "long-term human impact as appropriate. End with one restrained reflection that "
            "echoes the documentary's central idea. Only after the story is fully resolved, "
            "add a short natural outro that mentions The Saster once and contains one brief "
            "subscribe request. Make the final two sections unequal in length."
        ),
    },
]


# =========================================================
# LOGGING AND CORE UTILITIES
# =========================================================


def log(message: str) -> None:
    timestamp = datetime.now().strftime("%H:%M:%S")
    print(f"[{timestamp}] {message}", flush=True)


def get_client() -> Anthropic:
    api_key = os.getenv("ANTHROPIC_API_KEY", "").strip()

    if not api_key:
        raise ValueError(
            "ANTHROPIC_API_KEY is missing. Add it via "
            "Hugging Face Space β†’ Settings β†’ Variables and secrets."
        )

    return Anthropic(
        api_key=api_key,
        timeout=API_TIMEOUT_SECONDS,
        max_retries=0,
    )


def count_words(text: str) -> int:
    if not text:
        return 0

    return len(re.findall(r"\b[\w’'-]+\b", text))


def format_elapsed(seconds: int, finished: bool = False) -> str:
    seconds = max(0, int(seconds))
    minutes, remaining_seconds = divmod(seconds, 60)
    prefix = "βœ… Total generation time" if finished else "⏱️ Elapsed time"

    return (
        f"{prefix}: {seconds} seconden "
        f"({minutes:02d}:{remaining_seconds:02d})"
    )


def extract_text(message) -> str:
    text_parts = []

    for block in message.content:
        if getattr(block, "type", None) != "text":
            continue

        block_text = getattr(block, "text", "")

        if block_text:
            text_parts.append(block_text)

    return "\n".join(text_parts).strip()


def joined_script(chunks: list[str]) -> str:
    return "\n\n".join(
        chunk.strip()
        for chunk in chunks
        if chunk.strip()
    ).strip()


def resolve_recency_days(option: str) -> int:
    return RECENCY_OPTIONS.get(
        option,
        RECENCY_OPTIONS[DEFAULT_RECENCY_OPTION],
    )


def resolve_news_balance(option: str) -> dict:
    return NEWS_BALANCE_OPTIONS.get(
        option,
        NEWS_BALANCE_OPTIONS[DEFAULT_NEWS_BALANCE_OPTION],
    )


def resolve_video_format(option: str) -> dict:
    return VIDEO_FORMAT_OPTIONS.get(
        option,
        VIDEO_FORMAT_OPTIONS[DEFAULT_VIDEO_FORMAT_OPTION],
    )


def get_chunk_specs(video_format_option: str) -> list[dict]:
    format_config = resolve_video_format(video_format_option)

    if not format_config["list_mode"]:
        return CHUNK_SPECS

    counts = format_config["chunk_sections"]
    total = format_config["section_count"]

    starts = [
        1,
        counts[0] + 1,
        counts[0] + counts[1] + 1,
    ]

    ends = [
        counts[0],
        counts[0] + counts[1],
        total,
    ]

    specs = []

    for base, count, start, end in zip(
        CHUNK_SPECS,
        counts,
        starts,
        ends,
    ):
        spec = dict(base)

        spec["section_count"] = count
        spec["section_start"] = start
        spec["section_end"] = end

        if base["number"] == 1:
            spec["purpose"] = (
                f"Write a cinematic cold-open introduction of 130–180 words and numbered "
                f"subtopics {start} through {end}. Follow the selected hook strategy. "
                f"Do not mention the channel in the introduction. Keep every "
                f"subtopic distinct, factual, useful, visually editable, and naturally "
                f"connected rather than padding the list."
            )

        elif base["number"] == 2:
            spec["purpose"] = (
                f"Write numbered subtopics {start} through {end}. Keep the "
                f"list-documentary pace moving while still explaining mechanisms, "
                f"geography, evidence, and consequences where useful. Keep sentence-to-"
                f"sentence flow coherent and use editor-friendly topics. Keep the "
                f"disaster narrative moving without inserting a mid-video CTA. "
                f"Do not recap part 1."
            )

        else:
            spec["purpose"] = (
                f"Write numbered subtopics {start} through {end} and then a connected "
                f"ending of 120–180 words. Keep every transition logically motivated. "
                f"Resolve the final items into the larger meaning of the disaster. In the "
                f"final 120 words, mention The Saster once and include one brief subscribe request."
            )

        specs.append(spec)

    return specs


def get_chunk_structure_issue(
    text: str,
    spec: dict,
) -> Optional[str]:
    if "section_start" not in spec:
        return None

    numbers = [
        int(value)
        for value in re.findall(
            r"(?m)^##\s+(\d+)\.\s+.+$",
            text or "",
        )
    ]

    expected = list(
        range(
            int(spec["section_start"]),
            int(spec["section_end"]) + 1,
        )
    )

    if numbers == expected:
        return None

    expected_text = (
        f"{spec['section_start']}–"
        f"{spec['section_end']}"
    )

    found_text = (
        ", ".join(str(number) for number in numbers)
        if numbers
        else "none"
    )

    return (
        f"Expected numbered headings {expected_text} exactly once and in order; "
        f"found: {found_text}."
    )


def build_video_structure_requirements(
    video_format_option: str,
) -> str:
    config = resolve_video_format(video_format_option)
    total = config["section_count"]

    if not config["list_mode"]:
        return f"""
VIDEO STRUCTURE β€” STANDARD DOCUMENTARY

- Build exactly {total} titled sections across the three chunks.
- The sections should feel like a connected documentary rather than a numbered list.
- Make section lengths deliberately unequal. Give the richest topics more room and use
  shorter sections as bridges or reveals.
- The largest section should be at least 150 words longer than the shortest section.
""".strip()

    return f"""
VIDEO STRUCTURE β€” LIST DOCUMENTARY ({total} SUBTOPICS)

- Build exactly {total} distinct, visible, numbered subtopics across the complete script.
- This is a Reasons-Why-style list documentary, but adapt the item type naturally to the
  title: reasons, warning signs, places, facts, changes, risks, explanations, discoveries,
  consequences, or another clearly fitting category.
- Every item must use the exact visible heading format: ## NUMBER. Short Title
- Number continuously from ## 1. through ## {total}. Never skip, duplicate, restart, merge,
  or add an extra numbered item.
- Each numbered item must contribute a genuinely different idea. Do not split one fact into
  several artificial items merely to reach the requested count.
- Keep the core The Saster writing voice: direct, documentary-like, evidence-dense, and
  human. Do not turn it into a shallow countdown or repetitive listicle.
- Use tighter pacing as the item count rises. A 30-item script needs concise items; a 10-item
  script can give each item substantially more explanation.
- Transitions should still connect neighboring items, but do not force a cliffhanger after
  every single item. Use stronger open loops at natural intervals.
""".strip()


def build_hook_requirements(
    hook_option: str,
) -> str:
    if hook_option == "Cinematic date + place opening":
        return """
HOOK STRATEGY β€” CINEMATIC DATE + PLACE

- Open with a precise date or time and a concrete location when the evidence supports it.
- Put the viewer inside the scene immediately: what the weather, landscape, city, facility,
  aircraft, ship, crowd, or infrastructure is doing at that moment.
- Within the first four sentences, introduce the threat and one piece of information that the
  people involved do not yet fully understand.
- Use chronology as tension. Do not dump the entire backstory in the first paragraph.
- After the cold open, briefly widen the frame so the audience understands why this place or
  system was vulnerable before the event escalates.
""".strip()

    if hook_option == "Immediate disaster scene":
        return """
HOOK STRATEGY β€” IMMEDIATE DISASTER SCENE

- Start at or just before the most consequential moment, not with general background.
- Use concrete physical action: water rising, ground moving, alarms sounding, wind intensifying,
  structures failing, communications going silent, people evacuating, or another verified event.
- Keep the first paragraph tightly focused on one scene and one time frame.
- Reveal only enough outcome to establish stakes, then rewind to explain how the situation reached
  that point.
- Do not use invented sensory details or fictionalized dialogue.
""".strip()

    if hook_option == "Warning / failure foreshadowing":
        return """
HOOK STRATEGY β€” WARNING / FAILURE FORESHADOWING

- Open with the central vulnerability, warning, ignored finding, design weakness, operational
  decision, or known hazard that later becomes crucial.
- Establish what experts, officials, operators, or residents knew before the disaster without
  claiming they knew more than the evidence shows.
- Contrast the warning with the later event through chronology, not accusation or melodrama.
- Within the first paragraph, make clear what could happen if the vulnerable system failed.
""".strip()

    if hook_option == "News clip continuation":
        return """
HOOK STRATEGY β€” NEWS CLIP CONTINUATION

- Write the first line as a seamless continuation from a real news clip placed immediately before
  the narration.
- Do not repeat the headline or summarize the clip.
- Use the clip as the visible surface of the event, then widen into the hidden chain of geography,
  engineering, warnings, decisions, or physical mechanisms behind it.
- Never invent details about the unseen clip.
""".strip()

    if hook_option == "Hard fact / consequence opening":
        return """
HOOK STRATEGY β€” HARD FACT / CONSEQUENCE

- Open with one verified number or consequence that immediately establishes the scale of the event.
- In the next two or three sentences, connect that number to a specific place, moment, or failure.
- Do not stack statistics. One strong figure is enough before the narrative begins.
- Move from the consequence into the chain of events that produced it.
""".strip()

    return """
HOOK STRATEGY β€” AUTO

- Choose the strongest opening for this specific disaster from:
  CINEMATIC DATE + PLACE, IMMEDIATE DISASTER SCENE, WARNING / FAILURE FORESHADOWING,
  or HARD FACT / CONSEQUENCE.
- Do not choose NEWS CLIP CONTINUATION automatically.
- Prefer a concrete scene over a general explanation.
- The opening should create a clear before-and-after tension: what was happening, what people
  believed, and what was about to change.
- State the chosen hook mode in the INTERNAL plan and follow it consistently in chunk 1.
""".strip()


def get_news_window(
    recency_days: int,
) -> tuple[date, date]:
    current_date = date.today()
    cutoff_date = (
        current_date
        - timedelta(days=recency_days)
    )

    return cutoff_date, current_date


def count_channel_mentions(
    text: str,
) -> int:
    return len(
        re.findall(
            re.escape(CHANNEL_NAME),
            text or "",
            flags=re.IGNORECASE,
        )
    )


def count_channel_questions(
    text: str,
) -> int:
    questions = re.findall(
        r"[^?]*\?",
        text or "",
        flags=re.DOTALL,
    )

    return sum(
        CHANNEL_NAME.lower()
        in question.lower()
        for question in questions
    )


def count_subscribe_mentions(
    text: str,
) -> int:
    return len(
        re.findall(
            r"\bsubscribe\b",
            text or "",
            flags=re.IGNORECASE,
        )
    )


def extract_recency_verdict(
    research: str,
) -> str:
    match = re.search(
        r"(?:EVIDENCE|RECENCY) VERDICT\s*:\s*(SUFFICIENT|INSUFFICIENT)",
        research,
        flags=re.IGNORECASE,
    )

    return (
        match.group(1).upper()
        if match
        else "UNKNOWN"
    )


def find_old_year_mentions(
    text: str,
    cutoff_date: date,
) -> list[int]:
    years = [
        int(value)
        for value in re.findall(
            r"\b(?:19|20)\d{2}\b",
            text or "",
        )
    ]

    return [
        year
        for year in years
        if year < cutoff_date.year
    ]


def story_requirement_warnings(
    text: str,
    cutoff_date: date,
    current_date: date,
    news_balance_option: str,
    video_format_option: str,
) -> list[str]:
    warnings = []

    channel_mentions = count_channel_mentions(text)
    subscribe_mentions = count_subscribe_mentions(text)

    if channel_mentions != 1:
        warnings.append(
            f"{CHANNEL_NAME} appears {channel_mentions}x instead of 1x"
        )

    if subscribe_mentions != 1:
        warnings.append(
            f"subscribe appears {subscribe_mentions}x instead of 1x"
        )

    format_config = resolve_video_format(video_format_option)

    if format_config["list_mode"]:
        expected = format_config["section_count"]
        numbered_headings = re.findall(
            r"(?m)^##\s+(\d+)\.\s+.+$",
            text or "",
        )
        numbers = [int(value) for value in numbered_headings]
        expected_numbers = list(range(1, expected + 1))

        if numbers != expected_numbers:
            warnings.append(
                f"numbered subtopics are not exactly 1–{expected} in continuous order "
                f"({len(numbers)} matching headings found)"
            )

    if (
        news_balance_option == "News-first β€” more current detail"
        and re.search(rf"\b{current_date.year}\b", text or "") is None
    ):
        warnings.append(
            f"the current year {current_date.year} is not mentioned in news-first mode"
        )

    return warnings


# =========================================================
# GLOBAL WRITING RULES
# =========================================================


def build_global_writing_requirements(
    cutoff_date: date,
    current_date: date,
    news_balance_option: str,
    hook_option: str,
    video_format_option: str,
) -> str:
    balance = resolve_news_balance(news_balance_option)
    hook_requirements = build_hook_requirements(hook_option)
    format_config = resolve_video_format(video_format_option)
    structure_requirements = build_video_structure_requirements(video_format_option)
    topic_count = format_config["section_count"]

    if format_config["list_mode"]:
        ratio_min = balance["recent_anchor_min"] / 7
        ratio_max = balance["recent_anchor_max"] / 7
        recent_anchor_min = max(0, round(topic_count * ratio_min))
        recent_anchor_max = max(recent_anchor_min, round(topic_count * ratio_max))
    else:
        recent_anchor_min = balance["recent_anchor_min"]
        recent_anchor_max = balance["recent_anchor_max"]

    return f"""
Write for The Saster: a high-retention documentary channel about natural disasters,
catastrophes, engineering failures, extreme events, accidents, evacuations, and the systems
that determine who survives and what fails.

The finished narration should feel cinematic without becoming fictional. It should combine the
clarity of a strong documentary with the momentum of a disaster reconstruction: concrete dates,
places, warnings, physical mechanisms, decisions, human consequences, response, aftermath, and
accountability.

Preserve the creator's own visible section structure. Do not imitate another channel's exact
sentences, recurring phrases, or unique wording.

{structure_requirements}

STORY DNA β€” THE SASTER

- Treat the disaster as a chain of events, not a pile of facts.
- Prefer chronological cause-and-effect whenever chronology is central to understanding what
  happened.
- Build tension from information asymmetry: what was known, what was believed, what was missed,
  and what changed next.
- Move repeatedly between MACRO and HUMAN scale:
  city/region/system -> street/building/person -> back to the wider consequence.
- Use exact places and times when they matter.
- Introduce technical background at the moment the audience needs it. Do not front-load a lecture.
- When a levee, dam, fault, aircraft system, warning network, building, evacuation plan, or other
  mechanism becomes important, explain it simply before showing how it performed under stress.
- Separate the hazard from the disaster. Ask what came from nature, what came from infrastructure,
  decisions, exposure, communication, or preparedness.
- Do not invent scenes, thoughts, dialogue, motives, or sensory details.
- Human stories must come from verified evidence and should be used sparingly but specifically.
- Avoid exploitative language around deaths, injuries, or suffering.
- The emotional force should come from documented events and consequences.

NARRATIVE SHAPE

- Cold open: enter a specific moment, place, warning, or consequence.
- Widen the frame: explain why the location or system was vulnerable.
- Reconstruct the approach/escalation in a clean timeline.
- Slow down at the decisive failure or turning point.
- Show what the failure meant for real people and emergency response.
- Explain why the outcome became so severe.
- Cover aftermath, accountability, rebuilding, lessons, and present-day vulnerability when relevant.
- End by returning to the documentary's central idea, not by simply recapping the sections.

DOCUMENTARY TIMEFRAME β€” {news_balance_option}

- {balance['description']}
- Historical disasters do NOT need a recent-news hook.
- Current material, when the selected mode allows it, may anchor approximately
  {recent_anchor_min}–{recent_anchor_max} of the {topic_count} main topics/subtopics.
- Required current material: {balance['recent_narration_share']} of the final narration.
- Historical EVENT dates are encouraged whenever they clarify the timeline.
- The target of {balance['date_mentions_min']}–{balance['date_mentions_max']} refers to useful
  explicit date/time references in narration, not publication dates.
- Never mention a source publication date merely to make the script sound researched.

OPTIONAL PRESENT-DAY MATERIAL

- The core research may come from any year that is relevant to the disaster.
- Prioritize sources closest to the event and authoritative later investigations over recent
  articles that merely retell old information.
- Anything explicitly described as current, new, recently announced, newly measured, newly rebuilt,
  newly discovered, or newly warned must be supported by a source published between
  {cutoff_date.isoformat()} and {current_date.isoformat()}.
- Never require a current source merely because the documentary is being produced today.
- Older authoritative sources are expected for the original event, official investigations,
  engineering analysis, historical weather records, casualty figures, and durable background.
- Keep source publication date, event date, and later investigation date distinct internally.

INTRODUCTION β€” 130–180 WORDS

- Do not print the video title.
- Do not introduce The Saster or ask viewers to subscribe.
- Start immediately inside the story using the selected hook below.
- The first paragraph should normally contain a concrete date/time, place, physical event,
  warning, decision, or consequence.
- Keep the first 3–5 sentences on one immediate scene or thread.
- Establish the central threat before giving broad background.
- Reveal one tension the documentary will resolve: a known vulnerability, a hidden failure,
  a forecast, a decision, a system under stress, or a consequence that was not yet understood.
- The final sentence of the intro should pull the viewer forward into the explanation. It may
  pose the central question or state the key unresolved problem, but do not use generic hype.

{hook_requirements}

SECTION WRITING

- Keep the creator's section headings and section count exactly as planned.
- Each section should still read like the next chapter of one continuous story.
- The first 2–4 sentences after a heading must continue the immediate thread from the previous
  section or deliberately establish the next chronological step.
- Section headings must not make the narration feel like a list of disconnected mini-essays.
- Standard documentary sections should be deliberately unequal in length.
- In list mode, each numbered item must still have its own distinct claim or event.

DISASTER TIMELINE AND CAUSALITY

- Make event order unambiguous.
- Use temporal bridges when useful and vary the wording.
- Distinguish trigger, contributing factor, system failure, response failure, and consequence.
- Never imply causation when the evidence supports only correlation or contribution.
- If official investigations disagree, attribute the disagreement clearly.
- If later evidence changed the accepted explanation, show that change explicitly.

TECHNICAL EXPLANATION

- Explain technical systems in plain spoken English.
- Use measurements when they advance the story: wind, surge, depth, pressure, magnitude, speed,
  rainfall, temperature, structural load, evacuation distance, population, cost, or response time.
- Connect every technical explanation to a concrete consequence.
- Avoid generic textbook paragraphs that could fit any disaster.
- Prefer named infrastructure, neighborhoods, agencies, facilities, geographic features, and
  official investigations.

HUMAN SCALE

- Use verified individual or group experiences when they reveal something the macro statistics
  cannot: inability to evacuate, rescue conditions, communications failure, shelter conditions,
  survival decisions, displacement, or unequal exposure.
- Do not overuse names merely for emotion.
- Do not fictionalize what a person saw, thought, heard, or felt.
- Treat fatalities and victims with restraint.

RETENTION

- Put a strong verified development in the first 250 words.
- Build open loops from factual uncertainty, approaching danger, a system under stress, an
  unanswered warning, or the next chronological turning point.
- Do not end every section with a question.
- Avoid fake mystery language. The viewer should continue because the causal chain is unfolding.
- Pay off earlier warnings and vulnerabilities when the failure occurs.
- Use short standalone sentences occasionally for emphasis, but not as a repetitive gimmick.

HUMAN WRITING

- Use mostly short and medium-length spoken sentences.
- Keep most paragraphs between one and four sentences.
- Prefer direct verbs and concrete nouns.
- Vary sentence rhythm naturally.
- Avoid academic framing, source-list phrasing, or AI-summary language.
- Avoid recurring stock phrases and obvious template language.
- Do not copy distinctive wording from the style sample or competitor reference.

COMPARISONS

- Use exactly three factual comparisons in the complete script.
- Each must clarify scale, speed, depth, distance, volume, time, or impact.
- Spread them across the documentary and verify the units.
- Do not use decorative analogies merely for drama.

THE SASTER BRANDING AND OUTRO

- Mention β€œ{CHANNEL_NAME}” exactly once in the complete script.
- Do not mention the channel in the introduction or middle of the documentary.
- Do not use the word subscribe before the ending.
- The final 120–180 words should first resolve the story with one restrained closing insight.
- Only after that resolution, add a short human outro.
- In that outro, mention β€œ{CHANNEL_NAME}” once and use the word subscribe exactly once.
- A brief thanks or invitation to comment is allowed, but do not let the CTA overpower the ending.
""".strip()


# =========================================================
# STYLE SAMPLE
# =========================================================


def load_style_file(
    filepath: Optional[str],
) -> str:
    default_style = """
Write cinematic but factual spoken English for a disaster documentary. Begin in a
specific moment, reconstruct events through clean cause-and-effect, introduce technical
background only when the viewer needs it, and move between system-level scale and verified
human consequences. Use short and medium-length sentences, brief paragraphs, concrete
places, times, measurements, warnings, decisions, failures, and aftermath. Sound like a
skilled human documentary writer, never an academic summary, sensational reenactment, or
AI narrator.
""".strip()

    if not filepath:
        return default_style

    path = Path(filepath)

    try:
        if path.suffix.lower() == ".txt":
            style_text = path.read_text(
                encoding="utf-8",
                errors="replace",
            ).strip()

        elif path.suffix.lower() == ".docx":
            document = Document(
                str(path)
            )

            content = []

            for paragraph in document.paragraphs:
                paragraph_text = (
                    paragraph.text.strip()
                )

                if paragraph_text:
                    content.append(
                        paragraph_text
                    )

            for table in document.tables:
                for row in table.rows:
                    for cell in row.cells:
                        cell_text = (
                            cell.text.strip()
                        )

                        if cell_text:
                            content.append(
                                cell_text
                            )

            style_text = "\n".join(
                content
            ).strip()

        else:
            raise ValueError(
                "Only .docx and .txt files are supported."
            )

        return (
            style_text[:MAX_STYLE_CHARACTERS]
            if style_text
            else default_style
        )

    except Exception as exc:
        raise ValueError(
            f"The style document could not be read: {exc}"
        ) from exc


# =========================================================
# CLAUDE REQUESTS
# =========================================================


def validate_response(
    response,
    allow_partial_max_tokens: bool = False,
) -> None:
    if response.stop_reason == "max_tokens":
        if allow_partial_max_tokens:
            return

        raise RuntimeError(
            "Claude reached the maximum output length."
        )

    if response.stop_reason == "refusal":
        raise RuntimeError(
            "Claude refused this request."
        )

    if response.stop_reason == "pause_turn":
        raise RuntimeError(
            "Claude did not complete the request."
        )


def request_text(
    client: Anthropic,
    model: str,
    system_prompt: str,
    user_prompt: str,
    max_tokens: int,
    effort: str,
    tools: Optional[list] = None,
    allow_pause_turn: bool = False,
    allow_partial_max_tokens: bool = False,
) -> tuple[str, object]:

    messages = [
        {
            "role": "user",
            "content": user_prompt,
        }
    ]

    attempts = (
        2
        if allow_pause_turn
        else 1
    )

    for attempt in range(attempts):
        request = {
            "model": model,
            "system": system_prompt,
            "messages": messages,
            "max_tokens": max_tokens,
            "thinking": {
                "type": "disabled",
            },
            "output_config": {
                "effort": effort,
            },
        }

        if tools:
            request["tools"] = tools

        with client.messages.stream(
            **request
        ) as stream:
            response = (
                stream.get_final_message()
            )

        if (
            response.stop_reason
            == "pause_turn"
            and allow_pause_turn
            and attempt == 0
        ):
            log(
                "Web research returned pause_turn; "
                "performing one continuation."
            )

            messages.append(
                {
                    "role": "assistant",
                    "content": response.content,
                }
            )

            continue

        validate_response(
            response,
            allow_partial_max_tokens=(
                allow_partial_max_tokens
            ),
        )

        text = extract_text(
            response
        )

        if not text:
            raise RuntimeError(
                "Claude returned no usable text."
            )

        return text, response

    raise RuntimeError(
        "Claude could not complete the web research. "
        "Try a more specific title."
    )


def stream_text(
    client: Anthropic,
    model: str,
    system_prompt: str,
    user_prompt: str,
    max_tokens: int,
    effort: str,
) -> Generator[
    tuple[str, Optional[object]],
    None,
    None,
]:
    request = {
        "model": model,
        "system": system_prompt,
        "messages": [
            {
                "role": "user",
                "content": user_prompt,
            }
        ],
        "max_tokens": max_tokens,
        "thinking": {
            "type": "disabled",
        },
        "output_config": {
            "effort": effort,
        },
    }

    collected_text = ""
    last_update = time.monotonic()

    with client.messages.stream(
        **request
    ) as stream:
        for text_delta in stream.text_stream:
            collected_text += text_delta
            now = time.monotonic()

            if (
                now - last_update
                >= STREAM_UPDATE_INTERVAL
            ):
                yield (
                    collected_text,
                    None,
                )

                last_update = now

        response = (
            stream.get_final_message()
        )

    final_text = (
        extract_text(response)
        or collected_text.strip()
    )

    if response.stop_reason == "max_tokens":
        log(
            "A writing pass reached max_tokens; "
            "the existing text is being kept."
        )

        yield (
            final_text,
            response,
        )

        return

    validate_response(
        response
    )

    yield (
        final_text,
        response,
    )


# =========================================================
# PHASE 1 β€” DOCUMENTARY RESEARCH + CURRENT NEWS
# =========================================================


def research_topic(
    client: Anthropic,
    model: str,
    title: str,
    recency_days: int,
    news_balance_option: str,
    video_format_option: str,
) -> str:

    cutoff_date, current_date = (
        get_news_window(
            recency_days
        )
    )

    balance = resolve_news_balance(
        news_balance_option
    )

    format_config = resolve_video_format(
        video_format_option
    )

    topic_count = format_config[
        "section_count"
    ]

    list_mode = format_config[
        "list_mode"
    ]

    if list_mode:
        ratio_min = (
            balance["recent_anchor_min"]
            / 7
        )

        ratio_max = (
            balance["recent_anchor_max"]
            / 7
        )

        research_anchor_min = max(
            1,
            round(
                topic_count * ratio_min
            ),
        )

        research_anchor_max = max(
            research_anchor_min,
            round(
                topic_count * ratio_max
            ),
        )

    else:
        research_anchor_min = (
            balance["recent_anchor_min"]
        )

        research_anchor_max = (
            balance["recent_anchor_max"]
        )

    prompt = f"""
Today's date is {current_date.isoformat()}.

Research this proposed YouTube documentary title:

"{title}"

Create an INTERNAL evidence pack for a factual, high-retention disaster documentary of
approximately {TARGET_WORDS} words. Do not write the script. Build enough evidence to reconstruct
the event as a causal timeline, explain the physical or technical systems involved, show verified
human consequences, and cover aftermath/accountability without fictionalization.

SELECTED DOCUMENTARY TIMEFRAME

{news_balance_option}
{balance['description']}

The disaster itself is the narrative anchor. Do not require a modern news story to justify
covering a historical event.

Current material may be used in approximately {research_anchor_min}–{research_anchor_max} of
{topic_count} main topics/subtopics only when the selected mode allows it.
Required current-event narration: {balance['recent_narration_share']}.

HISTORICAL RESEARCH RULE

- Search across the full historical record needed to reconstruct the event accurately.
- Prefer contemporaneous official records, archived reporting, meteorological/seismological data,
  government investigations, engineering reports, peer-reviewed studies, and credible eyewitness
  documentation over modern retellings.
- Do NOT reject a topic because there is little or no recent news about it.
- Do NOT manufacture a present-day angle, anniversary hook, new warning, or "scientists now say"
  framing when the historical story already stands on its own.
- If you use anything described as recent, new, current, newly measured, newly announced,
  newly warned, newly rebuilt, or newly discovered, that specific claim must come from a source
  published between {cutoff_date.isoformat()} and {current_date.isoformat()}.
- A recent article that repeats an old fact does not make that fact current news.
- Distinguish source publication date from event date and investigation date.

AUTHORITATIVE DOCUMENTARY BACKGROUND

- You MAY use older authoritative sources for stable topography, geology, hydrology,
  engineering, historical context, long-running hazards, scientific mechanisms, and baseline
  measurements when needed to explain the story.
- Prefer official agencies, universities, peer-reviewed research, recognized scientific
  institutions, and high-quality datasets.
- Clearly label this material internally as BACKGROUND, not CURRENT.
- Do not use old background to manufacture a fake news angle.
- Avoid weak SEO explainers, copied summaries, and sensational unsupported claims.

EVIDENCE DECISION

Return exactly one of these near the beginning:

EVIDENCE VERDICT: SUFFICIENT
EVIDENCE VERDICT: INSUFFICIENT

Return SUFFICIENT when there is enough reliable historical and/or scientific evidence to build
{topic_count} connected main topics/subtopics. A historical disaster can be fully SUFFICIENT with
zero current-news sources.

A larger list format does NOT require a separate source or news story for every item.

If the verdict is INSUFFICIENT:

- Explain briefly which central claims or parts of the event cannot be verified well enough.
- Provide three alternative title angles that preserve the same broad event but are better
  supported by the available evidence.
- Do not compensate for weak evidence with speculation, modern clickbait framing, or stale material
  presented as news.

TITLE AUDIT

Also return:

TITLE VERDICT: SUPPORTED
TITLE VERDICT: PARTLY SUPPORTED
TITLE VERDICT: UNSUPPORTED

Continued activity is not acceleration, improved detection is not acceleration, and a new
publication about old data is not a new physical event.

Do not assume scientists are afraid, shocked, baffled, or issuing warnings unless reliable
evidence explicitly supports it.

SOURCE PRIORITY

Use no more than {MAX_WEB_SEARCHES} focused searches. Prioritize:

1. Official agency alerts, releases, datasets, maps, monitoring pages, and project updates.
2. University and scientific-institution research pages.
3. Peer-reviewed studies and recognized scientific journals.
4. Government decisions, infrastructure projects, legislation, funding, and operations.
5. Reputable news reporting for current human and regional context.

EDITORIAL VISUAL AVAILABILITY

- Use one or two of the available searches to check whether the strongest candidate story angles
  have realistic visual support for a YouTube editor.
- Look for discoverable video or visual material on YouTube and/or official public websites:
  news clips, agency videos, press briefings, interviews, fieldwork, maps, satellite imagery,
  monitoring dashboards, animations, infrastructure footage, location footage, or other
  concrete visuals.
- Do not select a weakly visual, text-only, or extremely obscure research detail as a major
  standalone topic merely because it is scientifically interesting.
- If a scientifically important detail has poor visual support, mark it as SUPPORTING ONLY and
  attach it to a stronger visually supported topic.
- Prefer candidate topics that can be illustrated with multiple independent visual options.
- Do not treat visual availability as evidence that a factual claim is true. Factual verification
  and editability are separate checks.

BUILD THIS EVIDENCE PACK

1. EVIDENCE VERDICT.

2. TITLE VERDICT.

3. NEWS WINDOW:
   {cutoff_date.isoformat()} to {current_date.isoformat()}.

4. THE CENTRAL DOCUMENTARY STORY in 120–180 words. Identify the trigger, the vulnerability,
   the decisive turning point, the human consequence, and the deeper reason this disaster became
   as severe as it did.

5. MASTER EVENT TIMELINE with the most important verified dates/times in chronological order.
   Include forecasts, warnings, operational decisions, physical changes, failures, rescue/response,
   and major aftermath milestones. Separate what was known AT THE TIME from what investigations
   established later.

6. FAILURE / ESCALATION CHAIN:
   map TRIGGER -> VULNERABILITY -> STRESS -> FAILURE/TURNING POINT -> CONSEQUENCE -> RESPONSE.
   If the event does not involve an infrastructure failure, adapt this to the relevant physical
   or organizational chain.

7. HUMAN EVIDENCE BANK:
   verified experiences, evacuation constraints, rescue conditions, shelter conditions, injuries,
   displacement, communications problems, or other human-scale evidence that can be narrated
   without invention.

8. CURRENT NEWS LEDGER with roughly {balance['current_source_target']} strong sources when
   available. For every source include publication date, event/research date, institution,
   location, the genuinely new information, and certainty level.

6. DOCUMENTARY BACKGROUND LEDGER with 4–10 authoritative sources for durable topography,
   mechanisms, baseline science, historical context, or regional consequences. Include dates
   internally, but mark them BACKGROUND and do not imply recency.

7. FACT BANK with enough specific, non-duplicative evidence to support all {topic_count}
   main topics/subtopics, normally at least {max(45, topic_count * 3)} useful facts.
   Label every fact CURRENT or BACKGROUND.
   Include location, source/institution, certainty, and why it matters.

8. SUBTOPIC BANK:
   propose at least {topic_count + (5 if list_mode else 2)} distinct candidate topic angles so
   the planner can select exactly {topic_count} without padding or duplication.

   For list mode, each candidate must be meaningfully different and strong enough to support a
   visible numbered item.

9. OPENING MATERIAL BANK with one strong evidence-based candidate for each opening mode:

   - TOPOGRAPHY / GEOGRAPHY;
   - DATE / CURRENT EVENT;
   - NEWS CLIP CONTINUATION;
   - HARD FACT / SCALE.

   Also include two strong intro-ending candidates:
   one central question and one verified hard fact/consequence.

10. RECENT DATA BLOCK containing the strongest current figures and measurements that are worth
    mentioning in narration.

    Do NOT include dates that add no storytelling value.

11. SCIENTIFIC EXPLANATIONS needed to understand the story:
    mechanism, method, uncertainty, competing explanations, and limitations.

12. TOPOGRAPHY AND GEOGRAPHY details that can make the documentary visually specific.

13. HUMAN, environmental, economic, infrastructure, policy, or safety consequences.

14. At least six candidate factual comparisons with checked units.
    The script will select exactly three.

15. ESSENTIAL HISTORICAL CONTEXT, limited to what genuinely improves understanding and short
    enough to stay within {MAX_HISTORICAL_CONTEXT_PERCENT} percent of the final script.

16. EDITORIAL VISUAL SUPPORT BANK:

    - For every strong candidate topic/subtopic, rate editability as HIGH, MEDIUM, or LOW.
    - List 2–5 realistic visual avenues such as named locations, agency footage, maps,
      satellite imagery, dashboards, interviews, fieldwork, public briefings, news clips,
      infrastructure, or other searchable visuals.
    - Mark LOW-visual topics as SUPPORTING ONLY unless they are absolutely essential.
    - Prefer HIGH or MEDIUM topics for standalone sections/subtopics.

17. CONTINUITY LINKS:

    - For every major candidate topic, state what fact or unresolved point naturally leads
      INTO it.
    - State what consequence, question, or mechanism naturally leads OUT of it.
    - Flag any pair of candidate topics that would create an abrupt narrative jump.

18. CLAIMS TO AVOID.

19. EXTRA VERIFIED FACTS that can be used to reach the word target without repetitive dates,
    stale filler, generic textbook language, or visually unworkable standalone topics.

Do not copy source sentences.

Do not write dramatic narration.

The evidence pack should be rich enough to support documentary depth, the selected amount of
current news, smooth narrative continuity, and realistic editing with discoverable visual
material.
""".strip()

    web_search_tool = [
        {
            "type": "web_search_20260318",
            "name": "web_search",
            "max_uses": MAX_WEB_SEARCHES,
            "allowed_callers": [
                "direct",
            ],
            "response_inclusion": "excluded",
        }
    ]

    log(
        "Phase 1 started: documentary research with a current-news layer "
        f"({cutoff_date.isoformat()} to {current_date.isoformat()}; "
        f"{news_balance_option})."
    )

    research, response = request_text(
        client=client,
        model=model,
        system_prompt=(
            "You are a rigorous disaster-documentary researcher. Reconstruct event chronology, "
            "distinguish what was known at the time from what later investigations found, and separate "
            "the initiating hazard from infrastructure, operational, communication, preparedness, and "
            "response factors. Build strong scientific, engineering, geographic, human, and aftermath "
            "evidence without fictionalization. Current developments are optional unless the selected "
            "news balance requires them. Also evaluate visual editability and natural continuity."
        ),
        user_prompt=prompt,
        max_tokens=RESEARCH_MAX_TOKENS,
        effort="medium",
        tools=web_search_tool,
        allow_pause_turn=True,
        allow_partial_max_tokens=True,
    )

    research_words = count_words(
        research
    )

    recency_verdict = extract_recency_verdict(
        research
    )

    if response.stop_reason == "max_tokens":
        log(
            "Research reached max_tokens; "
            "the completed research is being used."
        )

    if recency_verdict == "INSUFFICIENT":
        raise RuntimeError(
            "There is not enough reliable evidence to support this documentary angle. "
            "Try a more specific or better-documented event/title."
        )

    if recency_verdict != "SUFFICIENT":
        raise RuntimeError(
            "Claude could not confirm that there is enough reliable evidence for the documentary. "
            "Try a more specific title or event."
        )

    if research_words < 800:
        raise RuntimeError(
            "Claude returned too little usable research. Make the event or title more specific."
        )

    log(
        f"Phase 1 complete: "
        f"{research_words} words of research."
    )

    return research


# =========================================================
# PHASE 2 β€” SCRIPT PLAN WITH FIXED WORD BUDGETS
# =========================================================


def create_script_plan(
    client: Anthropic,
    model: str,
    title: str,
    research: str,
    cutoff_date: date,
    current_date: date,
    global_requirements: str,
    news_balance_option: str,
    hook_option: str,
    video_format_option: str,
) -> str:

    balance = resolve_news_balance(
        news_balance_option
    )

    format_config = resolve_video_format(
        video_format_option
    )

    topic_count = format_config[
        "section_count"
    ]

    list_mode = format_config[
        "list_mode"
    ]

    chunk_counts = format_config[
        "chunk_sections"
    ]

    if list_mode:
        ratio_min = (
            balance["recent_anchor_min"]
            / 7
        )

        ratio_max = (
            balance["recent_anchor_max"]
            / 7
        )

        anchor_min = max(
            1,
            round(
                topic_count * ratio_min
            ),
        )

        anchor_max = max(
            anchor_min,
            round(
                topic_count * ratio_max
            ),
        )

        structure_plan = f"""
LIST-DOCUMENTARY STRUCTURE

- Plan exactly {topic_count} numbered subtopics.
- Chunk 1 contains subtopics 1–{chunk_counts[0]} after the introduction.
- Chunk 2 contains subtopics {chunk_counts[0] + 1}–{chunk_counts[0] + chunk_counts[1]}.
- Chunk 3 contains subtopics {chunk_counts[0] + chunk_counts[1] + 1}–{topic_count},
  followed by the 100–160 word ending.
- Every planned heading must use: ## NUMBER. Short Title
- The item type must fit the title naturally. Use β€œreasons” only if the title truly asks why;
  otherwise use facts, warning signs, locations, risks, mechanisms, changes, consequences,
  or another fitting category.
- Give each item an exact word budget. Keep enough variation to avoid monotony, but do not use
  the standard documentary rule requiring a 150-word gap between longest and shortest items.
- Prevent duplication aggressively: each numbered item must have its own core claim and evidence.
""".strip()

    else:
        anchor_min = (
            balance["recent_anchor_min"]
        )

        anchor_max = (
            balance["recent_anchor_max"]
        )

        structure_plan = """
STANDARD DOCUMENTARY STRUCTURE

- Plan exactly seven titled sections:
  two in chunk 1,
  three in chunk 2,
  and two in chunk 3.
- Give every section an exact individual word budget.
- Do not give neighboring sections similar budgets unless necessary.
- Use the largest sections for the richest scientific or geographic material.
- Use at least two noticeably short bridge sections.
- The largest section must be at least 150 words longer than the shortest.
""".strip()

    prompt = f"""
Create a concise but detailed INTERNAL writing plan for this proposed title:

"{title}"

<evidence_pack>
{research}
</evidence_pack>

SELECTED VIDEO FORMAT

{video_format_option}

The final spoken script must contain 2,900–3,200 words and exactly three writing chunks:

CHUNK 1 β€” 900–1,000 words

- A cinematic cold-open introduction of 130–180 words.
- Follow the selected hook: {hook_option}.
- Then cover the first {chunk_counts[0]} main topics/subtopics.
- Move into the strongest story material instead of automatically dumping dates or source
  chronology.

CHUNK 2 β€” 1,000–1,100 words

- Cover the next {chunk_counts[1]} main topics/subtopics.
- Carry the densest scientific explanation, analysis, regional consequences, named research or
  monitoring, and selected current developments.

CHUNK 3 β€” 1,000–1,100 words

- Cover the final {chunk_counts[2]} main topics/subtopics.
- Finish with a connected ending of 120–180 words that resolves the story before the brief outro.

That produces exactly {topic_count} main topics/subtopics in the full script.

{structure_plan}

{global_requirements}

NEWS / DOCUMENTARY ALLOCATION

- Mark every main topic/subtopic internally as either NEWS ANCHOR or DOCUMENTARY CORE.
- Use NEWS ANCHOR for approximately {anchor_min}–{anchor_max} items total.
  Do not force news into every item.
- Use DOCUMENTARY CORE for topography, physical mechanisms, scientific explanation, regional
  consequences, long-running systems, infrastructure, or other durable material.
- Recent-event narration across the whole script should be
  {balance['recent_narration_share']}.
- Plan only {balance['date_mentions_min']}–{balance['date_mentions_max']} explicit calendar-date
  references for the spoken narration.
- Publication dates can remain internal in the plan.
- Never create a standalone history lesson merely to fill an item.
- Never create a standalone latest-update item merely to satisfy recency.
  Blend current developments into the central documentary story.

INTRO PLAN

- State the exact hook mode that chunk 1 will use.
- If the selected hook is AUTO, choose the strongest mode from the evidence pack and
  record the choice.
- Plan the first 3–4 sentences by function only, not as sample narration.
- Do not include channel branding or a CTA in the introduction.
- Plan the intro as a cold open: one immediate scene/thread, one emerging threat, and one
  unresolved vulnerability or consequence that pulls the viewer into section 1.
- Choose the intro's final sentence type:
  CENTRAL QUESTION or HARD FACT / CONSEQUENCE.
- Do not automatically choose a question every time.

FOR EVERY MAIN TOPIC / SUBTOPIC PROVIDE

- its exact heading/title;
- ROLE: NEWS ANCHOR or DOCUMENTARY CORE;
- its central purpose;
- its exact word budget;
- the exact facts, measurements, people, locations, topography, and mechanisms it uses;
- the scientific explanation or analysis it contains;
- the human or practical consequence;
- if NEWS ANCHOR:
  the current development, publication date, and event date;
- if DOCUMENTARY CORE:
  the durable evidence it explains and how it connects to the story;
- whether an explicit date should actually be spoken aloud;
- MICRO-STORY:
  the one person/place/event/measurement/mechanism the first 2–4 sentences follow;
- CONTINUITY IN:
  the exact fact or unresolved point from the previous topic that leads here;
- CONTINUITY OUT:
  the exact consequence, mechanism, or unresolved point that leads onward;
- VISUAL SUPPORT:
  HIGH or MEDIUM;
- 2–4 INTERNAL VISUAL SEARCH ANCHORS for the editor;
- its transition to the next item or section;
- any essential historical context, limited to one or two brief points.

ALLOCATION RULES

- Assign every important fact to only one topic/subtopic.
- Put the strongest verified material in chunk 1, but that material does not have to be news.
- Reserve enough unused evidence for chunks 2 and 3.
- Select exactly three verified comparisons and assign each to a different part of the script.
- Assign named studies, projects, reports, alerts, datasets, or monitoring efforts where they
  add substance. They do not all need to be recent.
- In list mode, audit the full list for overlap before finalizing the plan.
- If two items are substantially similar, merge the idea and replace one with a genuinely
  different topic.
- Do not create a debunking video.
- Silently use the strongest accurate angle.

EDITORIAL EDITABILITY CHECK

- For every planned main topic/subtopic, include VISUAL SUPPORT: HIGH or MEDIUM.
- Do not use a LOW-visual candidate as a standalone item.
- Fold its useful science into the nearest HIGH/MEDIUM topic.
- For every planned topic, list 2–4 short visual search anchors for the editor:
  named place, project, agency, event, map, satellite view, fieldwork, interview,
  monitoring system, or infrastructure.
- These are INTERNAL planning notes only and must never appear in narration.
- Prefer topics with several realistic visual avenues rather than a single obscure paper or
  text-only finding.
- If two candidate topics are equally strong factually, prefer the one with better editability.

CONTINUITY MAP

- Before finalizing the plan, audit every neighboring topic pair.
- For each transition write:

  PREVIOUS THREAD β†’ BRIDGE LOGIC β†’ NEXT THREAD.

- The bridge logic must explain why the next topic follows naturally from the previous one.
- Reject or reorder any topic pair where one line would begin a story and the next line would
  need to switch subject, location, time period, cause, or meaning without explanation.
- Within each topic, define a single MICRO-STORY for the opening 2–4 sentences.
- The opening 2–4 sentences of a topic must stay on that micro-story before widening into
  background, science, or consequences.
- Mark any intentional change in interpretation as EXPLICIT CONTRAST so the writer must signal
  it rather than abruptly reversing the previous sentence.

THE SASTER OUTRO PLAN

- No channel branding or CTA in chunks 1 or 2.
- No mid-video subscription interruption.
- In the final 120–180 words, resolve the documentary first.
- Then add a short human outro containing β€œ{CHANNEL_NAME}” exactly once and the word
  β€œsubscribe” exactly once.
- A brief thanks or comment invitation is optional.

Keep the complete plan between 1,500 and 2,700 words.
Use compact bullet points.
Do not write sample narration and do not repeat the entire evidence pack.
This is a plan only.
""".strip()

    log(
        f"Phase 2 started: three-part plan for "
        f"{video_format_option}."
    )

    plan, response = request_text(
        client=client,
        model=model,
        system_prompt=(
            "You are a senior disaster-documentary editor. Build a connected reconstruction with "
            "a clear timeline, escalating cause-and-effect, technical explanation at the moment it "
            "becomes relevant, verified human consequences, and a strong aftermath. Preserve the "
            "creator's exact section format, prevent repetition, use current news only when warranted, "
            "and give every neighboring topic a clear narrative bridge."
        ),
        user_prompt=prompt,
        max_tokens=PLAN_MAX_TOKENS,
        effort="medium",
        allow_partial_max_tokens=True,
    )

    if response.stop_reason == "max_tokens":
        log(
            "The script plan reached max_tokens; "
            "the completed plan is being used."
        )

    if count_words(plan) < 400:
        raise RuntimeError(
            "Claude did not create a usable documentary plan."
        )

    log(
        f"Phase 2 complete: "
        f"{count_words(plan)} words in the plan."
    )

    return plan


# =========================================================
# PHASE 3 β€” THREE SCRIPT CHUNKS
# =========================================================


def channel_rules_for_chunk(
    chunk_number: int,
) -> str:
    if chunk_number in (1, 2):
        return f"""
THE SASTER RULES FOR THIS CHUNK

- Do not mention β€œ{CHANNEL_NAME}” in this chunk.
- Do not use the word subscribe.
- Do not interrupt the disaster narrative with a CTA, like request, or comment request.
""".strip()

    return f"""
THE SASTER RULES FOR THIS CHUNK

- Do not mention β€œ{CHANNEL_NAME}” until the final outro.
- Do not use the word subscribe before the final outro.
- First finish the documentary itself with a 120–180 word connected ending.
- After the story is resolved, add a short human outro.
- Mention β€œ{CHANNEL_NAME}” exactly once in that outro.
- Use the word subscribe exactly once.
- A brief thank-you or invitation to comment is allowed.
- Keep the CTA restrained; the final documentary thought should remain the emotional endpoint.
""".strip()


def build_chunk_prompt(
    title: str,
    research: str,
    plan: str,
    style_text: str,
    previous_script: str,
    spec: dict,
    cutoff_date: date,
    current_date: date,
    global_requirements: str,
) -> str:

    chunk_number = spec["number"]
    minimum = spec["minimum"]
    maximum = spec["maximum"]
    target = spec["target"]

    if "section_start" in spec:
        format_rule = (
            f"This chunk must contain exactly the numbered headings "
            f"## {spec['section_start']}. through ## {spec['section_end']}. "
            f"Use every number once, in order, with no extra numbered subtopic."
        )

    else:
        format_rule = (
            "This chunk must contain exactly the standard documentary section headings "
            "assigned to it in the plan."
        )

    if chunk_number == 1:
        continuity_rule = (
            "Do not print the video title. Write the 130–180 word introduction according "
            "to the selected hook strategy in the global requirements and the exact hook "
            "choice recorded in the plan. After the intro, move directly into the planned "
            "story material without a source-list or date dump."
        )

    else:
        continuity_rule = (
            "Continue naturally from the previous script. Do not write a new introduction, "
            "do not recap earlier sections, and do not repeat facts."
        )

    return f"""
Write ONLY CHUNK {chunk_number} of the final spoken YouTube documentary.

Proposed title:

"{title}"

<evidence_pack>
{research}
</evidence_pack>

<full_writing_plan>
{plan}
</full_writing_plan>

<style_sample>
{style_text}
</style_sample>

<previous_script>
{previous_script if previous_script else "No previous script yet."}
</previous_script>

CHUNK PURPOSE

{spec['purpose']}

EXACT STRUCTURE FOR THIS CHUNK

- {format_rule}

HARD LENGTH REQUIREMENT

- This chunk must contain between {minimum} and {maximum} words.
- Aim for {target} words.
- This is a hard production requirement, not a suggestion.
- Before answering, silently count the chunk and keep adding unused verified information,
  explanation, consequences, topographic detail, or analysis until it reaches at least
  {minimum} words.
- Do not add dates merely to fill space.

{global_requirements}

NEWS / DOCUMENTARY REQUIREMENTS FOR THIS CHUNK

- Follow the ROLE assignments in the plan:
  NEWS ANCHOR versus DOCUMENTARY CORE.
- Only NEWS ANCHOR material may be narrated as a current development.
- Any claim described as recent or current must fall inside the news window
  {cutoff_date.isoformat()} through {current_date.isoformat()}.
- DOCUMENTARY CORE material may use authoritative older evidence when the plan marks it as
  durable background.
- Never make that material sound newly discovered.
- Follow the planned spoken-date budget.
- Do not mention publication dates unless the audience actually needs them.
- Do not turn every named study or agency update into a date sentence.
- Use exact dates sparingly.
- Use names, places, measurements, mechanisms, and consequences more often than chronology.

WRITING STANDARD

- {continuity_rule}

- Follow the exact topic/subtopic budgets assigned in the plan.

- Every paragraph must add a new fact, example, mechanism, measurement, consequence, event,
  research result, analysis, topographic detail, or documented uncertainty.

- Write straight to the point and explain why the information matters.

- Use mostly short and medium-length sentences and paragraphs of one to four sentences.

- Translate technical language into natural spoken English.

- Use exact names, places, numbers, and measurements when useful.

- Explain the science deeply where the plan assigns it:
  methods, causal mechanisms, uncertainty, limitations, competing explanations,
  and practical implications.

- Follow the planned open loops and chronological turning points so each section connects directly
  to the next. Prefer factual anticipation over rhetorical teasing.

- Follow the plan's MICRO-STORY, CONTINUITY IN, and CONTINUITY OUT instructions.

- Once a sentence introduces a person, place, event, measurement, mechanism, or claim,
  keep the next sentence on that same thread unless an explicit bridge explains the change.

- Never let one sentence begin a story while the next sentence changes the subject,
  location, time frame, cause, or interpretation without explaining the connection.

- Keep the first 2–4 sentences after each heading on the planned micro-story before widening
  into background or analysis.

- When changing direction inside a paragraph, use one short causal, temporal, geographic,
  or contrast bridge so the viewer understands why the new point follows.

- Do not let a pronoun or phrase such as β€œthis,” β€œit,” β€œthey,” or β€œthat” silently change
  referent from one sentence to the next.

- If the plan marks a point as EXPLICIT CONTRAST, signal the contrast clearly before changing
  or qualifying the previous meaning.

- Keep standalone topics limited to material marked VISUAL SUPPORT: HIGH or MEDIUM in the plan.

- Technical LOW-visual details should appear only as supporting explanation inside a stronger
  editable topic.

- Fully paraphrase the evidence and the style sample.

- Preserve uncertainty.
  Do not turn possible, estimated, preliminary, or disputed information into certainty.

- Do not tell the audience that the proposed title was fact-checked or exaggerated.

- Use every heading exactly as planned for this chunk.
  In list mode, preserve the exact continuous numbering.

- Use only the comparisons assigned to this chunk.
  The complete script must contain exactly three factual comparisons in total.

- Do not include sources, URLs, citations, editor notes, camera directions, or B-roll.

DISASTER RECONSTRUCTION CHECK

- Keep the event order clear. If the narration jumps backward for context, signal the rewind.
- Separate what participants knew at the time from what later investigations established.
- When a system fails, explain what it was supposed to do before describing how it failed.
- Do not let technical explanation stall the timeline for too long; return to the unfolding event.
- Use verified human-scale evidence to show consequences, but never invent scenes or emotions.
- Treat casualty figures and suffering with restraint.
- If responsibility is disputed, attribute findings instead of declaring motive or blame.
- Let the most important causal insight emerge from the evidence rather than repeating the title.

SILENT CONTINUITY AUDIT BEFORE RETURNING

- Read every pair of neighboring sentences.

- If sentence B does not clearly continue, explain, qualify, contrast, or result from
  sentence A, rewrite the pair or add a brief bridge.

- Check every paragraph boundary the same way.

- Remove abrupt pivots that change meaning or direction without setup.

- Check especially for:
  sudden location changes;
  sudden timeline changes;
  sudden changes from one researcher to another;
  sudden changes from a measurement to an unrelated mechanism;
  sudden switches from confirmed fact to speculation;
  and sentences that appear to contradict the line immediately before them.

- Preserve the same factual content.
  Fix the flow rather than adding new material.

{channel_rules_for_chunk(chunk_number)}

Return only CHUNK {chunk_number} as finished spoken narration.
""".strip()


def build_chunk_revision_prompt(
    research: str,
    plan: str,
    previous_script: str,
    current_chunk: str,
    chunk_number: int,
    minimum: int,
    maximum: int,
    target: int,
    cutoff_date: date,
    current_date: date,
    global_requirements: str,
    structure_issue: Optional[str] = None,
) -> str:

    current_words = count_words(
        current_chunk
    )

    operations = []

    if current_words < minimum:
        operations.append(
            f"The chunk is {minimum - current_words} words below the minimum. "
            "Expand it with unused verified facts, topography, mechanisms, "
            "scientific explanation, measurements, consequences, or planned "
            "current developments assigned to this part. Respect the section "
            "roles and spoken-date budget."
        )

    elif current_words > maximum:
        operations.append(
            f"The chunk is {current_words - maximum} words above the maximum. "
            "Remove repetition, unnecessary chronology, source-date language, "
            "and decorative phrasing while preserving important science, geography, "
            "current anchors, open loops, comparisons, and CTA placement."
        )

    else:
        operations.append(
            "The chunk is already inside the required word range. "
            "Preserve its overall length."
        )

    if structure_issue:
        operations.append(
            "Repair this exact structural problem: "
            + structure_issue
            + " Preserve every correct numbered heading, restore missing headings, "
            "remove duplicates, and keep the planned evidence attached to the correct item."
        )

    operation = "\n".join(
        operations
    )

    return f"""
Rewrite the COMPLETE chunk below.

It currently contains approximately {current_words} words.

It must contain between {minimum} and {maximum} words.

Aim for {target} words.

{operation}

<recent_evidence_pack>
{research}
</recent_evidence_pack>

<writing_plan>
{plan}
</writing_plan>

<previous_script>
{previous_script if previous_script else "No previous script."}
</previous_script>

<current_chunk>
{current_chunk}
</current_chunk>

{global_requirements}

NEWS / DOCUMENTARY BALANCE CHECK

- Preserve the NEWS ANCHOR and DOCUMENTARY CORE roles from the plan.

- Claims narrated as recent or current must be supported inside the window
  {cutoff_date.isoformat()} through {current_date.isoformat()}.

- Durable older evidence may remain when it provides useful scientific, geographic,
  or historical context and is not presented as recent.

- When expanding, prefer unused mechanisms, measurements, topography, consequences,
  or verified facts over extra date references.

- When shortening, remove repetitive chronology and source-date language before
  removing important science or geographic detail.

Keep the same topic purposes, exact headings, appropriate topic pacing,
scientific explanations, analysis, planned comparisons, and content-based cliffhangers.

If the chunk uses numbered ## headings, preserve the intended number range exactly:
do not skip, duplicate, merge, restart, or add a numbered item.

CONTINUITY REPAIR

- Preserve the plan's MICRO-STORY, CONTINUITY IN, and CONTINUITY OUT for each topic.

- Check each neighboring sentence pair.

- Sentence B must clearly continue, explain, qualify, contrast, or result from sentence A.

- Repair abrupt switches in:
  subject;
  location;
  time frame;
  causal explanation;
  scientific interpretation;
  or meaning.

- Keep the first 2–4 sentences under a heading on one immediate story before widening out.

- Add a short bridge when the narrative genuinely needs to pivot.

- Do not let pronouns silently change referent between sentences.

- Preserve intentional contrasts, but signpost them clearly.

- Do not promote a LOW-visual supporting detail into a standalone topic during revision.

- If a line begins a concrete event or story, do not abandon that event in the very next line.
  Give it enough explanation or resolution before moving on.

- Check paragraph boundaries as carefully as sentence boundaries.
  The first sentence of a new paragraph must clearly connect to what came immediately before it.

Keep the narration direct, human, and information-dense.

Do not add a new introduction, sources, citations, or production notes.

{channel_rules_for_chunk(chunk_number)}

Before returning:

1. Silently count the result.
2. Silently reread every neighboring sentence pair.
3. Fix any abrupt change of subject or meaning.
4. Confirm that standalone topics remain realistically editable.

Return only the complete revised chunk.
""".strip()


def revise_chunk(
    client: Anthropic,
    model: str,
    research: str,
    plan: str,
    previous_script: str,
    current_chunk: str,
    chunk_number: int,
    minimum: int,
    maximum: int,
    target: int,
    cutoff_date: date,
    current_date: date,
    global_requirements: str,
    structure_issue: Optional[str] = None,
) -> str:

    prompt = build_chunk_revision_prompt(
        research=research,
        plan=plan,
        previous_script=previous_script,
        current_chunk=current_chunk,
        chunk_number=chunk_number,
        minimum=minimum,
        maximum=maximum,
        target=target,
        cutoff_date=cutoff_date,
        current_date=current_date,
        global_requirements=global_requirements,
        structure_issue=structure_issue,
    )

    revised, _ = request_text(
        client=client,
        model=model,
        system_prompt=(
            "You are a strict disaster-documentary editor. Meet the requested word range while "
            "preserving timeline clarity, factual density, technical explanation, verified human "
            "impact, natural spoken rhythm, causal escalation, aftermath, and exact brand placement. "
            "Repair sentence-to-sentence continuity, preserve what was known at each point in time, "
            "and never fictionalize scenes or motives."
        ),
        user_prompt=prompt,
        max_tokens=REVISION_MAX_TOKENS,
        effort="medium",
        allow_partial_max_tokens=True,
    )

    return revised


# =========================================================
# TOTAL LENGTH REBALANCING
# =========================================================


def rebalance_total(
    client: Anthropic,
    model: str,
    research: str,
    plan: str,
    chunks: list[str],
    cutoff_date: date,
    current_date: date,
    global_requirements: str,
) -> list[str]:

    for _ in range(2):
        total_words = count_words(
            joined_script(chunks)
        )

        if MIN_WORDS <= total_words <= MAX_WORDS:
            return chunks

        if total_words < MIN_WORDS:
            deficit = (
                MIN_WORDS
                - total_words
            )

            index = 1

            current = count_words(
                chunks[index]
            )

            minimum = (
                current
                + deficit
                + 25
            )

            maximum = (
                minimum
                + 70
            )

            target = (
                minimum
                + 35
            )

        else:
            excess = (
                total_words
                - MAX_WORDS
            )

            index = max(
                range(
                    len(chunks)
                ),
                key=lambda i: count_words(
                    chunks[i]
                ),
            )

            current = count_words(
                chunks[index]
            )

            maximum = max(
                650,
                current - excess - 20,
            )

            minimum = max(
                600,
                maximum - 70,
            )

            target = (
                minimum
                + 35
            )

        previous_script = joined_script(
            chunks[:index]
        )

        chunks[index] = revise_chunk(
            client=client,
            model=model,
            research=research,
            plan=plan,
            previous_script=previous_script,
            current_chunk=chunks[index],
            chunk_number=index + 1,
            minimum=minimum,
            maximum=maximum,
            target=target,
            cutoff_date=cutoff_date,
            current_date=current_date,
            global_requirements=global_requirements,
        )

    return chunks


# =========================================================
# MAIN WORKFLOW
# =========================================================


def generate_script(
    title: str,
    style_file: Optional[str],
    model: str,
    recency_option: str,
    news_balance_option: str,
    hook_option: str,
    video_format_option: str,
):
    current_script = ""

    if not title or not title.strip():
        yield (
            "❌ Enter a video title first.",
            "",
        )
        return

    try:
        client = get_client()

        clean_title = (
            title.strip()
        )

        style_text = load_style_file(
            style_file
        )

        recency_days = resolve_recency_days(
            recency_option
        )

        cutoff_date, current_date = (
            get_news_window(
                recency_days
            )
        )

        global_requirements = (
            build_global_writing_requirements(
                cutoff_date=cutoff_date,
                current_date=current_date,
                news_balance_option=news_balance_option,
                hook_option=hook_option,
                video_format_option=video_format_option,
            )
        )

        yield (
            "πŸ”Ž Phase 1/3 β€” gathering documentary research, "
            "historical evidence, event chronology, and editor-friendly visual topics "
            f"from {cutoff_date.isoformat()}…",
            "",
        )

        research = research_topic(
            client=client,
            model=model,
            title=clean_title,
            recency_days=recency_days,
            news_balance_option=news_balance_option,
            video_format_option=video_format_option,
        )

        yield (
            "🧭 Phase 2/3 β€” distributing evidence, editability, "
            "and narrative continuity across three parts…",
            "",
        )

        plan = create_script_plan(
            client=client,
            model=model,
            title=clean_title,
            research=research,
            cutoff_date=cutoff_date,
            current_date=current_date,
            global_requirements=global_requirements,
            news_balance_option=news_balance_option,
            hook_option=hook_option,
            video_format_option=video_format_option,
        )

        chunks: list[str] = []

        active_chunk_specs = (
            get_chunk_specs(
                video_format_option
            )
        )

        for spec in active_chunk_specs:
            chunk_number = spec[
                "number"
            ]

            previous_script = (
                joined_script(
                    chunks
                )
            )

            yield (
                f"✍️ Phase 3/3 β€” writing part "
                f"{chunk_number}/3 β€” total so far "
                f"{count_words(previous_script)} words…",
                previous_script,
            )

            prompt = build_chunk_prompt(
                title=clean_title,
                research=research,
                plan=plan,
                style_text=style_text,
                previous_script=previous_script,
                spec=spec,
                cutoff_date=cutoff_date,
                current_date=current_date,
                global_requirements=global_requirements,
            )

            chunk_text = ""
            final_response = None

            for (
                partial_text,
                response,
            ) in stream_text(
                client=client,
                model=model,
                system_prompt=(
                    "You are an experienced human disaster-documentary writer. Write cinematic "
                    "but factual spoken English with a clear timeline, escalating cause-and-effect, "
                    "concrete places and times, plain-English technical explanation, verified human "
                    "consequences, and a strong aftermath. Use short and medium sentences with natural "
                    "rhythm. Build retention from what happens next and why, not generic hype. Never "
                    "invent scenes, motives, dialogue, or sensory details. Preserve the creator's "
                    "exact section format."
                ),
                user_prompt=prompt,
                max_tokens=CHUNK_MAX_TOKENS,
                effort="medium",
            ):
                chunk_text = (
                    partial_text
                )

                if response is not None:
                    final_response = (
                        response
                    )

                current_script = (
                    joined_script(
                        chunks
                        + [partial_text]
                    )
                )

                if response is None:
                    yield (
                        f"✍️ Part {chunk_number}/3 β€” "
                        f"{count_words(partial_text)} words in this part β€” "
                        f"{count_words(current_script)} total",
                        current_script,
                    )

            if not chunk_text.strip():
                raise RuntimeError(
                    f"Claude did not write "
                    f"part {chunk_number}."
                )

            chunk_words = count_words(
                chunk_text
            )

            log(
                f"Part {chunk_number} "
                f"first draft: "
                f"{chunk_words} words."
            )

            structure_issue = (
                get_chunk_structure_issue(
                    chunk_text,
                    spec,
                )
            )

            for correction_attempt in range(3):
                length_ok = (
                    spec["minimum"]
                    <= chunk_words
                    <= spec["maximum"]
                )

                if (
                    length_ok
                    and not structure_issue
                ):
                    break

                issue_text = (
                    f" Structure check: "
                    f"{structure_issue}"
                    if structure_issue
                    else ""
                )

                yield (
                    f"πŸ“ Part {chunk_number}/3 has "
                    f"{chunk_words} words; target is "
                    f"{spec['minimum']}–{spec['maximum']}."
                    f"{issue_text} Correction "
                    f"{correction_attempt + 1}/3…",
                    joined_script(
                        chunks
                        + [chunk_text]
                    ),
                )

                chunk_text = revise_chunk(
                    client=client,
                    model=model,
                    research=research,
                    plan=plan,
                    previous_script=previous_script,
                    current_chunk=chunk_text,
                    chunk_number=chunk_number,
                    minimum=spec["minimum"],
                    maximum=spec["maximum"],
                    target=spec["target"],
                    cutoff_date=cutoff_date,
                    current_date=current_date,
                    global_requirements=global_requirements,
                    structure_issue=structure_issue,
                )

                chunk_words = count_words(
                    chunk_text
                )

                structure_issue = (
                    get_chunk_structure_issue(
                        chunk_text,
                        spec,
                    )
                )

                log(
                    f"Part {chunk_number} after "
                    f"correction "
                    f"{correction_attempt + 1}: "
                    f"{chunk_words} words."
                )

            if (
                final_response is not None
                and final_response.stop_reason
                == "max_tokens"
            ):
                log(
                    f"Part {chunk_number} reached "
                    "max_tokens, but the existing "
                    "text is being kept."
                )

            chunks.append(
                chunk_text.strip()
            )

            current_script = (
                joined_script(
                    chunks
                )
            )

            yield (
                f"βœ… Part {chunk_number}/3 complete β€” "
                f"{chunk_words} words β€” "
                f"{count_words(current_script)} total",
                current_script,
            )

        total_words = count_words(
            current_script
        )

        if not (
            MIN_WORDS
            <= total_words
            <= MAX_WORDS
        ):
            yield (
                f"πŸ”§ Total length is "
                f"{total_words} words; "
                "running final length correction…",
                current_script,
            )

            chunks = rebalance_total(
                client=client,
                model=model,
                research=research,
                plan=plan,
                chunks=chunks,
                cutoff_date=cutoff_date,
                current_date=current_date,
                global_requirements=global_requirements,
            )

            current_script = (
                joined_script(
                    chunks
                )
            )

            total_words = count_words(
                current_script
            )

        warnings = story_requirement_warnings(
            text=current_script,
            cutoff_date=cutoff_date,
            current_date=current_date,
            news_balance_option=news_balance_option,
            video_format_option=video_format_option,
        )

        window_text = (
            f"news window "
            f"{cutoff_date.isoformat()} "
            f"to "
            f"{current_date.isoformat()}"
        )

        if (
            MIN_WORDS
            <= total_words
            <= MAX_WORDS
            and not warnings
        ):
            status = (
                f"βœ… Ready β€” "
                f"{total_words} words β€” "
                f"{window_text} β€” "
                f"1x {CHANNEL_NAME} β€” "
                "1x subscribe in outro"
            )

        elif (
            MIN_WORDS
            <= total_words
            <= MAX_WORDS
        ):
            status = (
                f"⚠️ Ready β€” "
                f"{total_words} words β€” "
                f"{window_text}. Check: "
                + "; ".join(warnings)
            )

        else:
            warning_text = (
                f" Also check: "
                f"{'; '.join(warnings)}"
                if warnings
                else ""
            )

            status = (
                f"⚠️ Ready β€” "
                f"{total_words} words. "
                f"Target: "
                f"{MIN_WORDS}–{MAX_WORDS}. "
                f"{window_text}."
                + warning_text
            )

        yield (
            status,
            current_script,
        )

    except anthropic.AuthenticationError:
        yield (
            "❌ The Anthropic API key is invalid.",
            current_script,
        )

    except anthropic.PermissionDeniedError:
        yield (
            "❌ Your Anthropic account does not have access "
            "to this model or web search.",
            current_script,
        )

    except anthropic.RateLimitError:
        yield (
            "❌ The Anthropic rate or usage limit has been reached. "
            "Check your billing.",
            current_script,
        )

    except anthropic.APITimeoutError:
        yield (
            f"❌ Claude did not respond within "
            f"{API_TIMEOUT_SECONDS} seconden.",
            current_script,
        )

    except anthropic.APIConnectionError:
        yield (
            "❌ Could not connect to Claude.",
            current_script,
        )

    except anthropic.BadRequestError as exc:
        error_text = str(
            exc
        )

        lower_error = (
            error_text.lower()
        )

        if (
            "web search is not enabled"
            in lower_error
        ):
            message = (
                "❌ Web search is not enabled for "
                "your Anthropic organization."
            )

        elif (
            "credit balance"
            in lower_error
        ):
            message = (
                "❌ Your Anthropic API credit "
                "balance is insufficient."
            )

        else:
            message = (
                f"❌ Anthropic rejected "
                f"the request: "
                f"{error_text}"
            )

        yield (
            message,
            current_script,
        )

    except anthropic.APIStatusError as exc:
        yield (
            f"❌ Anthropic API error "
            f"{exc.status_code}: "
            f"{exc.message}",
            current_script,
        )

    except Exception as exc:
        log(
            f"Unexpected error: "
            f"{exc}"
        )

        yield (
            f"❌ Something went wrong: "
            f"{exc}",
            current_script,
        )


# =========================================================
# TIMER AND INTERFACE
# =========================================================


def start_run():
    start_time = time.time()

    return (
        start_time,
        True,
        format_elapsed(0),
        "πŸš€ Generation started…",
        "",
        gr.Button(
            interactive=False,
        ),
    )


def update_timer(
    start_time: float,
    is_running: bool,
):
    if (
        not is_running
        or not start_time
    ):
        return gr.skip()

    elapsed_seconds = int(
        time.time()
        - float(start_time)
    )

    return format_elapsed(
        elapsed_seconds
    )


def finish_run(
    start_time: float,
):
    elapsed_seconds = (
        int(
            time.time()
            - float(start_time)
        )
        if start_time
        else 0
    )

    return (
        False,
        format_elapsed(
            elapsed_seconds,
            finished=True,
        ),
        gr.Button(
            interactive=True,
        ),
    )


def clear_interface():
    return (
        "",
        None,
        DEFAULT_RECENCY_OPTION,
        DEFAULT_NEWS_BALANCE_OPTION,
        DEFAULT_HOOK_OPTION,
        DEFAULT_VIDEO_FORMAT_OPTION,
        "",
        "",
        0.0,
        False,
        format_elapsed(0),
        gr.Button(
            interactive=True,
        ),
    )


with gr.Blocks() as demo:
    gr.Markdown(
        """
# The Saster Documentary Script Writer

Creates a cinematic, factual disaster-documentary script of 2,900–3,200 words.
The Saster style prioritizes a strong cold open, clean event chronology, warnings,
failure chains, human consequences, technical explanation, aftermath, and accountability,
while preserving your own 7-section or 10/20/30-subtopic structure.
"""
    )

    start_time_state = gr.State(
        0.0
    )

    running_state = gr.State(
        False
    )

    elapsed_timer = gr.Timer(
        value=1.0,
        active=True,
    )

    with gr.Row():
        title_input = gr.Textbox(
            label="🎯 Video title",
            placeholder=(
                "The Storm That Emptied an Entire City β€” Houston 2005"
            ),
            lines=2,
        )

        model_input = gr.Dropdown(
            choices=MODEL_OPTIONS,
            value="claude-sonnet-5",
            label="🧠 Claude model",
        )

        # Hidden internal state. Historical-disaster mode does not use a recency window.
        # The fixed default is only consulted when a present-day-context mode is selected.
        recency_input = gr.State(DEFAULT_RECENCY_OPTION)

    with gr.Row():
        news_balance_input = gr.Dropdown(
            choices=list(
                NEWS_BALANCE_OPTIONS.keys()
            ),
            value=DEFAULT_NEWS_BALANCE_OPTION,
            label="πŸ•°οΈ Documentary timeframe",
            info=(
                "Historical disaster mode requires no recent-news angle. "
                "Use the other modes only when you intentionally want "
                "present-day context or a current hook."
            ),
        )

        hook_input = gr.Dropdown(
            choices=HOOK_OPTIONS,
            value=DEFAULT_HOOK_OPTION,
            label="🎬 Opening hook",
            info=(
                "Choose how the cold open starts. Auto selects "
                "a date/place scene, an immediate disaster moment, "
                "a warning/failure setup, or a hard consequence. "
                "News clip continuation is used only when selected."
            ),
        )

    video_format_input = gr.Dropdown(
        choices=list(
            VIDEO_FORMAT_OPTIONS.keys()
        ),
        value=DEFAULT_VIDEO_FORMAT_OPTION,
        label="🧩 Video format",
        info=(
            "Choose the normal 7-section documentary "
            "or a Reasons-Why-style list documentary "
            "with exactly 10, 20, or 30 visible "
            "numbered subtopics."
        ),
    )

    style_file_input = gr.File(
        label=(
            "πŸ“„ Upload a handmade sample script "
            "for style inspiration (.docx or .txt)"
        ),
        file_types=[
            ".docx",
            ".txt",
        ],
        type="filepath",
    )

    with gr.Row():
        clear_button = gr.Button(
            "Clear"
        )

        generate_button = gr.Button(
            "πŸš€ Generate",
            variant="primary",
        )

    with gr.Row():
        status_output = gr.Textbox(
            label="Status",
            interactive=False,
        )

        elapsed_output = gr.Textbox(
            label="Elapsed time",
            value=format_elapsed(0),
            interactive=False,
        )

    script_output = gr.Textbox(
        label="Final script",
        lines=35,
        interactive=False,
        buttons=[
            "copy",
        ],
    )

    elapsed_timer.tick(
        fn=update_timer,
        inputs=[
            start_time_state,
            running_state,
        ],
        outputs=elapsed_output,
        queue=False,
        show_progress="hidden",
    )

    generation_event = (
        generate_button.click(
            fn=start_run,
            inputs=None,
            outputs=[
                start_time_state,
                running_state,
                elapsed_output,
                status_output,
                script_output,
                generate_button,
            ],
            queue=False,
        )
    )

    generation_event = (
        generation_event.then(
            fn=generate_script,
            inputs=[
                title_input,
                style_file_input,
                model_input,
                recency_input,
                news_balance_input,
                hook_input,
                video_format_input,
            ],
            outputs=[
                status_output,
                script_output,
            ],
            concurrency_limit=1,
            show_progress="hidden",
        )
    )

    generation_event.then(
        fn=finish_run,
        inputs=start_time_state,
        outputs=[
            running_state,
            elapsed_output,
            generate_button,
        ],
        queue=False,
        show_progress="hidden",
    )

    clear_button.click(
        fn=clear_interface,
        inputs=None,
        outputs=[
            title_input,
            style_file_input,
            recency_input,
            news_balance_input,
            hook_input,
            video_format_input,
            status_output,
            script_output,
            start_time_state,
            running_state,
            elapsed_output,
            generate_button,
        ],
        queue=False,
        show_progress="hidden",
    )


demo.queue(
    default_concurrency_limit=1,
    max_size=10,
)


if __name__ == "__main__":
    demo.launch()