File size: 65,721 Bytes
c0119d1
 
 
5576989
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
c0119d1
 
 
 
 
 
5576989
c0119d1
 
 
5576989
c0119d1
5576989
 
c0119d1
 
5576989
 
 
 
c0119d1
5576989
 
 
 
 
c0119d1
 
 
 
 
5576989
c0119d1
 
 
 
 
 
 
 
 
 
5576989
c0119d1
5576989
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
c0119d1
5576989
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
 
c0119d1
 
 
 
 
 
 
 
 
 
5576989
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
5576989
c0119d1
 
5576989
c0119d1
 
 
 
 
 
 
 
 
 
5576989
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
5576989
c0119d1
 
5576989
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
 
c0119d1
5576989
 
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
c0119d1
 
5576989
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
5576989
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
5576989
 
c0119d1
 
 
 
5576989
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
5576989
c0119d1
 
 
 
5576989
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
c0119d1
 
 
 
5576989
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
5576989
c0119d1
 
 
 
5576989
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
5576989
c0119d1
 
 
 
5576989
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
5576989
c0119d1
 
 
 
5576989
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
5576989
c0119d1
 
 
 
5576989
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
5576989
c0119d1
 
 
 
5576989
 
 
 
 
c0119d1
 
 
 
5576989
 
 
 
 
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5576989
c0119d1
 
 
 
 
 
 
 
 
5576989
c0119d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import logging
import random
from typing import Optional
from datetime import datetime, timedelta
import re
from google import genai
from google.genai import types

logger = logging.getLogger(__name__)

_gemini_client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY", "").strip())
_GEMINI_MODEL  = os.environ.get("GOOGLE_MODEL", "gemini-2.5-flash").strip().strip("\"'")


def _call_gemini(prompt: str, max_tokens: int = 400) -> str:
    """
    Call Gemini with an explicit output-token budget.

    The consultation flow uses relatively short, structured narration beats.
    We keep the thinking budget effectively off so the model spends more of the
    budget on the answer itself instead of on hidden reasoning.
    """
    try:
        response = _gemini_client.models.generate_content(
            model=_GEMINI_MODEL,
            contents=prompt,
            config=types.GenerateContentConfig(
                temperature=0.58,
                top_p=0.95,
                max_output_tokens=max_tokens,
                thinking_config=types.ThinkingConfig(thinking_budget=0),
            )
        )
        print("\n")
        print("=" * 80)
        print("FULL GEMINI RESPONSE")
        print(response)
        print("=" * 80)
        print("\n")

        result = ""
        try:
            result = response.text.strip()
        except Exception:
            pass

        if not result:
            try:
                parts = []
                for part in response.candidates[0].content.parts:
                    if hasattr(part, "text") and part.text:
                        parts.append(part.text)
                result = " ".join(parts).strip()
            except Exception as e:
                logger.warning(f"[SCRIPT GEN] candidate extraction failed: {e}")

        logger.info(f"[SCRIPT GEN] response length={len(result)}")
        try:
            logger.info(
                f"[SCRIPT GEN] Finish reason: {response.candidates[0].finish_reason}"
            )
        except Exception:
            pass
        logger.info(f"[SCRIPT GEN] Gemini {len(result)} chars")
        logger.info(f"[SCRIPT GEN] Gemini output: {result[:300]}")
        return _normalize_currency_mentions(result)
    except Exception as e:
        logger.error(f"[SCRIPT GEN] Gemini failed: {e}")
        return ""
def _looks_truncated(text: str) -> bool:
    if not text:
        return True

    ending = text.strip()[-1:]

    if ending not in ".!?":
        return True

    return False


def _contains_devanagari(text: str) -> bool:
    return bool(re.search(r'[\u0900-\u097F]', text))


def _validate_llm_output(
    text: str,
    min_words: int = 60,
    max_words: Optional[int] = None,
    preferred_language: str = "English",
) -> bool:

    if not text:
        return False

    cleaned = text.strip()
    if len(cleaned) < 45:
        return False

    words = cleaned.split()
    word_count = len(words)

    relaxed_min = max(14, int(min_words * 0.55))
    if word_count < relaxed_min:
        return False

    if max_words is not None:
        relaxed_max = max_words + max(16, int(max_words * 0.25))
        if word_count > relaxed_max:
            return False

    sentence_count = cleaned.count(".") + cleaned.count("!") + cleaned.count("?")

    if word_count >= 45 and sentence_count < 1:
        return False
    if word_count >= 90 and sentence_count < 2:
        return False

    if _looks_truncated(cleaned):
        return False

    if _is_english_language(preferred_language) and _contains_devanagari(cleaned):
        return False

    return True


def _generate_with_retry(
    prompt: str,
    fallback: str,
    min_words: int = 60,
    max_words: Optional[int] = None,
    preferred_language: str = "English",
    attempts: int = 3,
    max_tokens: int = 700,
    fallback_variants: Optional[list[str]] = None,
):

    for attempt in range(attempts):
        result = _call_gemini(
            prompt,
            max_tokens=max_tokens
        )

        logger.info(
            f"[SCRIPT GEN] Attempt {attempt+1} output: {result}"
        )

        result = _normalize_currency_mentions(result)
        if _validate_llm_output(
            result,
            min_words=min_words,
            max_words=max_words,
            preferred_language=preferred_language
        ):
            logger.info(
                f"[SCRIPT GEN] valid output on attempt {attempt + 1}"
            )
            return result

        logger.warning(
            f"[SCRIPT GEN] invalid output on attempt {attempt + 1}"
        )

    logger.warning(
        "[SCRIPT GEN] falling back to deterministic narration"
    )

    if fallback_variants:
        candidates = [variant for variant in fallback_variants if variant]
        if candidates:
            chosen = random.choice(candidates)
            return _normalize_currency_mentions(chosen)

    return _normalize_currency_mentions(fallback)






def _consultation_context_payload(
    name: str,
    goal: str,
    skills: str,
    hours: str,
    timeline: str,
    milestone_ladder: list[dict],
    roadmap_modules: list[dict],
    scenario_title: Optional[str],
    skill_why: Optional[str],
    offer: dict,
    target_date: str,
    first_milestone_value: str,
    module_count: int,
    preferred_language: str,
) -> dict:
    preferred_language = _normalize_preferred_language(preferred_language)
    language_mix, language_style = _language_mix_targets(preferred_language)
    return {
        "name": name,
        "goal": goal,
        "skills": skills,
        "hours_per_week": hours,
        "timeline": timeline,
        "target_date": target_date,
        "offer": offer,
        "first_milestone_value": first_milestone_value,
        "module_count": module_count,
        "scenario_title": scenario_title,
        "skill_why": skill_why,
        "milestone_ladder": milestone_ladder,
        "roadmap_modules": roadmap_modules,
        "preferred_language": preferred_language,
        "language_mix": language_mix,
        "language_style": language_style,
    }


def _consultation_prompt(
    beat_id: str,
    context: dict,
    instructions: str,
    min_words: int,
    max_words: int,
) -> str:
    preferred_language = context.get("preferred_language", "English")
    language_block = _language_prompt_block(preferred_language, beat_id=beat_id)
    return _normalize_spaces(
        f"""
        You are writing narration for a premium personalized consultation video.

        Beat: {beat_id}
        Audience: the specific learner in the context.

        Tone and style:
        - Speak directly to the learner in second person.
        - Sound strategic, warm, confident, and specific.
        - Keep the narration distinct from the other beats.
        - Do not use the phrase "the learner".
        - Do not read the roadmap like a catalog.
        - Avoid repeating the same sentence structure as the previous beat.
        - Use the learner's currency context in INR / rupees if money is mentioned.
        - Make the narration feel personalized to the user's onboarding answers, not like a generic sales pitch.
        - Use a human, natural cadence with one beat-specific idea per sentence.
        - {language_block}
        - Do not use bullet points, headings, markdown, quotes, or labels.
        - Write 3 to 5 full sentences in one paragraph.
        - Return only the narration paragraph.

        Length:
        - Target between {min_words} and {max_words} words.
        - Stay close to the target; this beat is part of a timed video.

        Context:
        {json.dumps(context, ensure_ascii=False, indent=2)}

        Instructions:
        {instructions}
        """
    )


def _generate_beat_narration(
    beat_id: str,
    context: dict,
    instructions: str,
    fallback: str,
    min_words: int,
    max_words: int,
    max_tokens: int = 700,
    preferred_language: str = "English",
    fallback_variants: Optional[list[str]] = None,
) -> str:
    prompt = _consultation_prompt(
        beat_id=beat_id,
        context=context,
        instructions=instructions,
        min_words=min_words,
        max_words=max_words,
    )
    return _generate_with_retry(
        prompt=prompt,
        fallback=fallback,
        min_words=min_words,
        max_words=max_words,
        preferred_language=preferred_language,
        attempts=3,
        max_tokens=max_tokens,
        fallback_variants=fallback_variants,
    )


def _beat5_section_prompt(
    section_id: str,
    context: dict,
    instructions: str,
    min_words: int,
    max_words: int,
) -> str:
    preferred_language = context.get("preferred_language", "English")
    language_block = _language_prompt_block(preferred_language, beat_id=section_id)
    return _normalize_spaces(
        f"""
        You are writing one section of Beat 5 for a personalized consultation video.

        Section: {section_id}

        Tone and style:
        - Speak directly to the learner in second person.
        - Be concrete and vivid.
        - Make the slide and narration feel tightly aligned.
        - Do not mention other Beat 5 sections.
        - Avoid repeated phrases like "the learner", "the roadmap", "the module stack", or "work starts to feel usable" unless the instruction explicitly asks for them.
        - Ensure section-specific wording stays unique: the project, scenario, checkpoint, outcomes, and tutor each need different wording and a different final emphasis.
        - Make the section feel human, specific, and visibly tied to the user's own inputs.
        - {language_block}
        - Write 3 to 5 full sentences in one paragraph.
        - Return only the narration paragraph.

        Length:
        - Target between {min_words} and {max_words} words.
        - This section must feel like a full part of the story, not a caption.

        Context:
        {json.dumps(context, ensure_ascii=False, indent=2)}

        Instructions:
        {instructions}
        """
    )


def _generate_beat5_section_narration(
    section_id: str,
    context: dict,
    instructions: str,
    fallback: str,
    min_words: int,
    max_words: int,
    max_tokens: int = 800,
    preferred_language: str = "English",
    fallback_variants: Optional[list[str]] = None,
) -> str:
    prompt = _beat5_section_prompt(
        section_id=section_id,
        context=context,
        instructions=instructions,
        min_words=min_words,
        max_words=max_words,
    )
    return _generate_with_retry(
        prompt=prompt,
        fallback=fallback,
        min_words=min_words,
        max_words=max_words,
        preferred_language=preferred_language,
        attempts=3,
        max_tokens=max_tokens,
        fallback_variants=fallback_variants,
    )


def _normalize_spaces(text: str) -> str:
    return re.sub(r"\s+", " ", text).strip()

def _normalize_currency_mentions(text: str) -> str:
    """
    Normalize accidental USD / dollar wording in generated narration.
    Consultation videos are localized for INR-based audiences here.
    """
    if not text:
        return text

    cleaned = text
    cleaned = re.sub(r"\bUS\s*dollars?\b", "rupees", cleaned, flags=re.IGNORECASE)
    cleaned = re.sub(r"\bdollars?\b", "rupees", cleaned, flags=re.IGNORECASE)
    cleaned = re.sub(r"\bUSD\b", "INR", cleaned, flags=re.IGNORECASE)
    cleaned = re.sub(r"\$\s*(?=\d)", "₹", cleaned)
    return cleaned



def _normalize_preferred_language(language: Optional[str]) -> str:
    value = (language or "English").strip()
    return value or "English"


def _is_english_language(language: Optional[str]) -> bool:
    normalized = _normalize_preferred_language(language).lower()
    return normalized in {"english", "en"}


def _language_mix_targets(preferred_language: Optional[str], beat_id: str = "") -> tuple[str, str]:
    """
    Return a soft English / preferred-language ratio for the beat.
    We vary the target a little so the whole video feels balanced instead of segmented.
    """
    preferred = _normalize_preferred_language(preferred_language)
    if _is_english_language(preferred):
        return ("100% English", "English only")

    beat_key = (beat_id or "").lower()
    if "beat_1" in beat_key or "beat_7" in beat_key:
        return (f"70% English / 30% {preferred}", "Mostly English with a short native-language line for warmth")
    if "beat_2" in beat_key or "beat_4" in beat_key:
        return (f"65% English / 35% {preferred}", "Balanced code-switching with the preferred language used for emotional emphasis")
    if "beat_5" in beat_key:
        return (f"60% English / 40% {preferred}", "Natural mixed narration that still keeps English dominant")
    return (f"65% English / 35% {preferred}", "Natural mixed narration with English leading")


def _language_prompt_block(
    preferred_language: Optional[str],
    beat_id: str = ""
) -> str:

    preferred = _normalize_preferred_language(preferred_language)

    if _is_english_language(preferred):
        return (
            "Language Rules (MANDATORY):\n"
            "- Write entirely in English.\n"
            "- Keep the narration natural, specific, conversational, and personalized.\n"
            "- Avoid generic motivational language.\n"
            "- Use the user's onboarding details and roadmap context naturally.\n"
        )

    return (
        f"""
Language Rules (MANDATORY):

1. English MUST be the dominant language.

2. Approximately 65-70% of all words must be English.

3. Approximately 30-35% of all words may be {preferred}.

4. This is a bilingual consultation, NOT a translated consultation.

5. The FIRST sentence of the beat MUST be written completely in English.

6. Every beat must contain at least two full English sentences.

7. Never write more than one consecutive sentence in {preferred}.

8. Use {preferred} only for:
   - emotional emphasis
   - reassurance
   - conversational transitions
   - natural human reactions
   - short relational phrases

9. Keep the following primarily in English:
   - roadmap explanation
   - milestone explanation
   - module explanation
   - project explanation
   - scenario explanation
   - salary discussion
   - career guidance
   - outcomes
   - CTA

10. Use only English and {preferred}.
    Never introduce a third language.
    Never introduce a third script.
    Never use words or characters from any other language.

11. Do not write entire paragraphs in {preferred}.

12. Blend both languages naturally inside the narration.

13. Do not over-translate:
    - technical terms
    - module names
    - role names
    - company names
    - salary figures
    - software names

14. The final narration should feel like a professional mentor speaking mostly English while occasionally switching into {preferred} for warmth and human connection.

15. Avoid sounding like a translated script.

Output only the narration.
"""
    ).strip()

def _join_phrases(items: list[str]) -> str:
    items = [item for item in items if item]
    if not items:
        return ""
    if len(items) == 1:
        return items[0]
    if len(items) == 2:
        return f"{items[0]} and {items[1]}"
    return ", ".join(items[:-1]) + f", and {items[-1]}"


def _module_skill_names(module: dict) -> list[str]:
    skill_names = []
    for skill in module.get("skills", []) or []:
        skill_name = (
            skill.get("skill_name")
            or skill.get("title")
            or skill.get("name")
        )
        if skill_name:
            skill_names.append(skill_name)
    return skill_names


def _build_module_card(module: dict) -> dict:
    skill_names = _module_skill_names(module)
    return {
        "title": module.get("title", "Module"),
        "skills": skill_names,
        "skill_count": len(skill_names),
        "preview": _join_phrases(skill_names[:3]) if skill_names else "core capabilities",
    }


def _transform_identity_statement(
    statement: str,
    goal: str = "",
    skills: str = "",
    label: str = "",
    milestone_index: int = 0,
) -> str:
    """
    Convert a roadmap identity statement into a consequence-oriented line.

    The goal is to avoid narrating the statement verbatim on screen while still
    preserving the intent of each milestone.
    """
    goal_phrase = goal or "your target role"
    label_text = _normalize_spaces(label or "")
    statement_l = _normalize_spaces(statement or "").lower()
    label_l = label_text.lower()

    if any(token in statement_l for token in ["excel", "email", "computer", "office", "typing", "files", "windows"]):
        if milestone_index <= 1:
            return _normalize_spaces(
                f"{label_text or 'This first milestone'} turns basic computer use into a working routine, so daily office tasks stop feeling intimidating."
            )
        return _normalize_spaces(
            f"{label_text or 'This milestone'} turns everyday office tools into something you can use with less hesitation and more control."
        )

    if any(token in statement_l for token in ["it support", "helpdesk", "troubleshoot", "troubleshooting", "printers", "network"]):
        if milestone_index <= 1:
            return _normalize_spaces(
                f"{label_text or 'This first milestone'} turns troubleshooting into a repeatable habit, so common support issues start feeling manageable."
            )
        return _normalize_spaces(
            f"{label_text or 'This milestone'} turns support work into a practical response pattern, so problems feel easier to isolate and solve."
        )

    if any(token in statement_l for token in ["data", "sql", "dashboard", "analysis", "model", "analytics"]):
        if milestone_index <= 1:
            return _normalize_spaces(
                f"{label_text or 'This first milestone'} turns raw data work into a clearer starting point, so the work starts to feel structured."
            )
        return _normalize_spaces(
            f"{label_text or 'This milestone'} turns analysis into a more job-facing routine, so you move from clean inputs to useful output with more confidence."
        )

    if label_l:
        if milestone_index <= 1 or any(token in label_l for token in ["foundation", "foundations", "core", "basics"]):
            return _normalize_spaces(
                f"{label_text} builds the base that makes {goal_phrase} work feel more familiar and less intimidating."
            )
        if any(token in label_l for token in ["job ready", "practical", "ready", "execution"]):
            return _normalize_spaces(
                f"{label_text} turns that base into job-facing execution, so the work feels more familiar, manageable, and easier to trust."
            )
        return _normalize_spaces(
            f"{label_text} gives you a more practical layer of capability, so the next step feels easier to trust."
        )

    if statement_l:
        return _normalize_spaces(
            f"The work tied to {goal_phrase} starts to feel more familiar, manageable, and easier to trust."
        )

    return _normalize_spaces(
        f"Daily work starts to feel more familiar because you have practiced the tools and routines tied to {goal_phrase}."
    )


def _build_milestone_cards(milestones: list, goal: str = "", skills: str = "") -> list[dict]:
    cards = []
    for idx, milestone in enumerate(milestones, start=1):
        modules = [_build_module_card(mod) for mod in milestone.get("modules", []) or []]
        raw_statement = milestone.get("identity_statement", "") or ""
        label = milestone.get("identity_label", "") or f"Milestone {idx}"
        cards.append({
            "index": idx,
            "label": label,
            "value": milestone.get("market_value_display", ""),
            "statement": _transform_identity_statement(
                raw_statement,
                goal=goal,
                skills=skills,
                label=label,
                milestone_index=idx,
            ),
            "statement_raw": raw_statement,
            "modules": modules,
            "module_count": len(modules),
            "module_preview": _join_phrases([m["title"] for m in modules[:4]]),
        })
    return cards


def _build_roadmap_summary(milestone_ladder: list[dict]) -> list[str]:
    summary_lines = []
    total = len(milestone_ladder)

    for card in milestone_ladder:
        label = card.get("label") or f"Milestone {card.get('index', '')}".strip()
        value = card.get("value") or "open"
        module_preview = card.get("module_preview") or "core modules"
        statement = card.get("statement") or "This milestone builds a job-ready layer of capability."
        summary_lines.append(
            f"{label} ({value}) combines {module_preview}. {statement}"
        )

    if total:
        summary_lines.append(
            f"Together these milestones form a step-by-step path instead of a random catalogue of lessons."
        )

    return summary_lines


def _estimate_words(*parts: str) -> int:
    return len(" ".join(parts).split())


def _first_nonempty(*values: Optional[str]) -> str:
    for value in values:
        if isinstance(value, str) and value.strip():
            return value.strip()
    return ""


def _iter_nested_items(node):
    if isinstance(node, dict):
        yield node
        for value in node.values():
            yield from _iter_nested_items(value)
    elif isinstance(node, list):
        for item in node:
            yield from _iter_nested_items(item)


def _extract_first_project(roadmap: dict) -> dict:
    for node in _iter_nested_items(roadmap or {}):
        projects = node.get("projects")
        if isinstance(projects, list) and projects:
            first = projects[0]
            if isinstance(first, dict):
                return first
        project = node.get("project")
        if isinstance(project, dict):
            return project
    return {}


def _extract_first_mock(roadmap: dict) -> dict:
    for milestone in (roadmap or {}).get("milestones", []) or []:
        for module in milestone.get("modules", []) or []:
            for skill in module.get("skills", []) or []:
                flow = skill.get("content_flow", {}) or {}
                mock = flow.get("mock") or {}
                if isinstance(mock, dict) and mock:
                    return {
                        "mock": mock,
                        "skill": skill,
                        "module": module,
                        "milestone": milestone,
                        "flow": flow,
                    }
    return {}


def _derive_project_teaser(goal: str, module_names: list[str], roadmap: dict) -> str:
    project = _extract_first_project(roadmap)
    title = _first_nonempty(project.get("title"), project.get("name"))
    deliverable = _first_nonempty(project.get("deliverable"), project.get("summary"), project.get("description"))
    phases = project.get("phases") if isinstance(project.get("phases"), list) else []
    phase_hint = _join_phrases([str(p).replace("_", " ") for p in phases[:3]]) if phases else ""

    if title or deliverable:
        parts = [f"Real project teaser: {title or 'your first project'}."]
        if deliverable:
            parts.append(f"By the end of this milestone, you will complete {deliverable}.")
        if phase_hint:
            parts.append(f"It moves through {phase_hint} before the final check.")
        return _normalize_spaces(" ".join(parts))

    focus = _join_phrases(module_names[:3]) if module_names else "the core modules"
    return _normalize_spaces(
        f"By the end of this milestone, you will complete a realistic work simulation that combines {focus} into one practical workflow used in {goal}."
    )


def _derive_mock_teaser(goal: str, roadmap: dict, scenario_title: str = "") -> str:
    mock_info = _extract_first_mock(roadmap)
    mock = mock_info.get("mock", {}) if mock_info else {}
    sample_question = _first_nonempty(
        mock.get("sample_question"),
        mock.get("question"),
        mock.get("prompt"),
    )
    if sample_question:
        return _normalize_spaces(
            f"Mock teaser: the checkpoint also includes a question like {sample_question}"
        )

    scenario_hint = scenario_title or f"a real task a {goal} handles at work"
    return _normalize_spaces(
        f"Mock teaser: you will also face a short practice question based on {scenario_hint}, so the feedback checks recall and judgment instead of memorization."
    )


def _derive_checkpoint_teaser(roadmap: dict) -> str:
    mock_info = _extract_first_mock(roadmap)
    mock = mock_info.get("mock", {}) if mock_info else {}
    milestone = mock_info.get("milestone", {}) if mock_info else {}
    checkpoint_rule = milestone.get("checkpoint_rule", {}) if isinstance(milestone.get("checkpoint_rule"), dict) else {}
    required = checkpoint_rule.get("required_mastery") or mock.get("unlock_mastery") or 0.90
    required_pct = int(round(float(required) * 100))
    return _normalize_spaces(
        f"Checkpoint teaser: before the next module unlocks, you complete a practical check at {required_pct}% mastery, so you show the task instead of just recognising it."
    )


def _derive_outcome_line(goal: str, skills: str) -> str:
    foundation = skills or "your current foundation"
    return _normalize_spaces(
        f"Expected outcome: with practice on {foundation}, daily work starts to feel less intimidating, and the same office tasks become more repeatable, steadier, and easier to finish cleanly in {goal} work."
    )


def _derive_ai_tutor_line(goal: str) -> str:
    return _normalize_spaces(
        f"AI tutor support: the tutor stays inside every lesson, slows things down when needed, gives hints, and can translate the instruction into plain language without removing the practice that builds real confidence for {goal}."
    )




def _generate_future_self_narration(
    name: str, goal: str, timeline: str,
    identity_statement: str, market_value: str,
    skills: str
) -> str:
    """
    Beat 2 — the want.
    Keep it concrete, specific, and job-facing.
    """
    foundation = skills if skills else "your current foundation"
    goal_phrase = goal or "your target role"
    future_identity = _transform_identity_statement(identity_statement, goal=goal_phrase, skills=foundation)

    current_state = (
        "Right now, a new workplace task can still slow you down because you have not seen that exact situation enough times yet."
    )
    future_state = (
        f"In {timeline}, similar situations feel familiar because you have already practiced them repeatedly."
    )
    confidence_line = (
        f"That means daily work stops feeling intimidating, and {future_identity[0].lower() + future_identity[1:] if future_identity else 'you start trusting your decisions more.'}"
    )
    market_line = (
        f"The market value for this level of judgment sits around {market_value}."
        if market_value else
        ""
    )
    return _normalize_spaces(" ".join([current_state, future_state, confidence_line, market_line]))


def _generate_stakes_narration(
    goal: str,
    module_count: int,
    skills: str
) -> str:
    """
    Beat 3 — why it's reachable (EPPM arc).

    Fear -> Efficacy
    """
    foundation = skills if skills else "your current foundation"
    return _normalize_spaces(
        f"Staying still means the gap keeps widening while other candidates keep learning the exact capabilities employers ask for. "
        f"Between you and becoming a {goal}, there are only {module_count} learnable capabilities, which is a real gap but not an impossible one. "
        f"You already bring {foundation} to the table, so you are not starting from zero. "
        f"You are starting from a base that can be sharpened into job-ready judgment, and that is the part most people miss. "
        f"The gap is real. It is also crossable."
    )


def _generate_whats_inside_narration(
    goal: str,
    scenario_title: Optional[str],
    skill_why: Optional[str],
    roadmap_modules: list,
    skills: str
) -> str:
    """
    Legacy single-block narration. The current render path uses split sections,
    but we keep this helper for compatibility.
    """
    scenario_line = scenario_title or f"a real situation a {goal} faces on the job"
    why_line = skill_why or f"the capability that separates {goal}s who get hired"
    module_names = [m.get("title", "Module") for m in (roadmap_modules or [])[:4]]
    focus = _join_phrases(module_names) if module_names else "the core modules"
    foundation = skills if skills else "your current foundation"
    return _normalize_spaces(
        f"Your learning path begins with {focus}. "
        f"Real scenario: {scenario_line}. "
        f"Expected outcomes: with practice on {foundation}, daily work starts to feel less intimidating. "
        f"AI tutor support: the tutor stays inside every lesson and helps when you get stuck. "
        f"Checkpoint teaser: before the next module unlocks, you complete a practical check that proves you can perform the task, not just recognise it. "
        f"That is why this step matters: {why_line}."
    )


def _generate_whats_inside_sections(
    goal: str,
    scenario_title: Optional[str],
    skill_why: Optional[str],
    roadmap_modules: list,
    skills: str,
    roadmap: Optional[dict] = None
) -> list[dict]:
    """
    Beat 5 is rendered as separate synchronized sections so each slide
    carries a distinct part of the story.
    """
    scenario_line = scenario_title or f"a real situation a {goal} faces on the job"
    why_line = skill_why or f"the capability that separates {goal}s who get hired"
    modules = roadmap_modules[:4] if roadmap_modules else []
    module_names = [m.get("title", "Module") for m in modules]

    if modules:
        module_overview_parts = []
        for idx, module in enumerate(modules, start=1):
            title = module.get("title", f"Module {idx}")
            preview = module.get("preview") or _join_phrases(module.get("skills", [])[:3]) or "core practice"
            if idx == 1:
                tail = "so the first layer feels familiar instead of abstract"
            elif idx == 2:
                tail = "so the work starts to feel usable in a real setting"
            elif idx == 3:
                tail = "so the communication layer connects to actual office work"
            else:
                tail = "so the final layer closes the loop with problem-solving"
            module_overview_parts.append(f"{title} opens with {preview}, {tail}.")
        module_overview = (
            f"Your learning path begins with {_join_phrases(module_names)}. "
            + " ".join(module_overview_parts)
        )
    else:
        module_overview = (
            f"Your learning path begins with the core modules already mapped out. "
            f"The first layer feels familiar instead of abstract. "
            f"The second layer makes the work usable in a real setting. "
            f"The third layer connects communication to office work. "
            f"The final layer closes the loop with problem-solving."
        )

    project_line = _derive_project_teaser(goal, module_names, roadmap or {})
    mock_line = _derive_mock_teaser(goal, roadmap or {}, scenario_line)
    checkpoint_line = _derive_checkpoint_teaser(roadmap or {})
    outcomes_line = _derive_outcome_line(goal, skills)
    tutor_line = _derive_ai_tutor_line(goal)

    section_templates = [
        ("beat_5a_modules", "src/template/consultation/beat_5a_modules.html", module_overview),
        ("beat_5b_project", "src/template/consultation/beat_5b_project.html", project_line),
        ("beat_5c_scenario", "src/template/consultation/beat_5c_scenario.html", f"Real scenario: {scenario_line}. In that moment, you are not watching theory for the sake of theory. You are following a workflow, checking the result, correcting the mistake, and moving the task forward. That is why this step matters: {why_line}."),
        ("beat_5d_checkpoint", "src/template/consultation/beat_5d_checkpoint.html", f"{checkpoint_line} {mock_line}"),
        ("beat_5e_outcomes", "src/template/consultation/beat_5e_outcomes.html", outcomes_line),
        ("beat_5f_ai_tutor", "src/template/consultation/beat_5f_ai_tutor.html", tutor_line),
    ]

    sections = []
    for beat_id, template_path, narration in section_templates:
        sections.append({
            "beat_id": beat_id,
            "template_path": template_path,
            "narration": _normalize_spaces(narration),
            "on_screen": {},
        })

    return sections


def _get_target_date(timeline: str) -> str:
    """Convert timeline string to approximate target date for peak-end frame."""
    import re
    match = re.search(r'(\d+)', timeline)
    if match:
        months = int(match.group(1))
        target = datetime.now() + timedelta(days=months * 30)
        return target.strftime("%B %Y")
    return "your target date"




def build_consultation_script(
    onboarding: dict,
    roadmap:    dict,
    offer:      dict
) -> list:
    """
    7-beat consultation video script.

    The script must feel personalized, concrete, and earned.
    """
    name       = onboarding.get("user_name") or "there"
    goal       = onboarding.get("target_role") or "your target role"
    skills_raw = onboarding.get("technical_skills") or "your current skills"
    skills     = skills_raw if isinstance(skills_raw, str) else ", ".join(skills_raw)
    hours = str(onboarding.get("hours_per_week") or "a few")
    hours_clean = hours.replace("hours", "").replace("hour", "").strip()
    timeline   = onboarding.get("goal_timeline") or "a few months"
    preferred_language = _normalize_preferred_language(
        onboarding.get("preferred_language") or roadmap.get("preferred_language") or "English"
    )

    logger.info(
        f"[SCRIPT GEN] name={name}, goal={goal}, timeline={timeline}, preferred_language={preferred_language}"
    )

    milestones = roadmap.get("milestones", []) or []
    first_milestone = milestones[0] if milestones else {}
    first_milestone_value = first_milestone.get("market_value_display", "")

    module_count = sum(len(m.get("modules", []) or []) for m in milestones)

    roadmap_modules: list[dict] = []
    for milestone in milestones:
        for mod in milestone.get("modules", []) or []:
            module_card = _build_module_card(mod)
            roadmap_modules.append(module_card)
            logger.info(f"[ROADMAP MODULE] {mod.get('title')} -> {module_card['skills']}")
    module_names = [m["title"] for m in roadmap_modules]

    scenario = None
    skill_why = None
    for module in first_milestone.get("modules", []) or []:
        for skill in module.get("skills", []) or []:
            flow = skill.get("content_flow", {}) or {}
            if not scenario and flow.get("scenario"):
                scenario = flow["scenario"]
            if not skill_why:
                skill_why = skill.get("why_this_skill")

    scenario_title = scenario.get("title") if scenario else None
    logger.info(f"[SCRIPT GEN] modules={module_count}, modules_list={module_names[:3]}, scenario={scenario_title}")

    milestone_ladder = _build_milestone_cards(milestones, goal=goal, skills=skills)
    target_date = _get_target_date(timeline)
    per_day = offer["price"] // 90

    def _fallback_pack(*variants: str) -> list[str]:
        return [_normalize_spaces(v) for v in variants if v and v.strip()]

    # LLM-first narration generation with deterministic fallbacks.
    shared_context = _consultation_context_payload(
        name=name,
        goal=goal,
        skills=skills,
        hours=hours_clean or hours,
        timeline=timeline,
        milestone_ladder=milestone_ladder,
        roadmap_modules=roadmap_modules,
        scenario_title=scenario_title,
        skill_why=skill_why,
        offer=offer,
        target_date=target_date,
        first_milestone_value=first_milestone_value,
        module_count=module_count,
        preferred_language=preferred_language,
    )

    beat1_fallback = _normalize_spaces(
        f"{name}, you told us you work with {skills}, can spend {hours_clean} hours a week, and want {goal} in {timeline}. We used those exact inputs instead of a generic template, so the plan starts from your real situation."
    )
    beat1_narration = _generate_beat_narration(
        beat_id="beat_1_mirror",
        context=shared_context,
        instructions=(
            f"Mirror the learner's exact onboarding answer set back in a human, direct way. Mention the name, skills, hours per week, timeline, and one concrete detail from the input. "
            f"Keep the tone warm and specific, and include a short natural phrase in {preferred_language} only if it helps the line feel more human. "
            f"Do not sound like a form recap or a sales pitch."
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
        ),
        fallback=beat1_fallback,
        min_words=45,
        max_words=60,
        max_tokens=450,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"{name}, you told us you work with {skills}, can spend {hours_clean} hours a week, and want {goal} in {timeline}. We used those exact inputs instead of a generic template, so the plan starts from your real situation.",
            f"We listened to your skills, your time budget, and your timeline. That is why this consultation feels personal: it is built around what you can actually do next, not around filler.",
            f"Nothing here is random. Your name, skills, time budget, and target role shaped the whole path, so the first thing you see is a plan that matches your life.",
        ),
    )

    beat2_fallback = _normalize_spaces(
        f"Right now, some parts of the work still take extra effort because you have not had enough repeated practice in the exact situations that {goal} work demands. In {timeline}, those same situations feel familiar because you will have already built the habit. The market value for that level of judgment sits around {first_milestone_value}."
    )
    beat2_narration = _generate_beat_narration(
        beat_id="beat_2_future_self",
        context=shared_context,
        instructions=(
            f"Use only English and {preferred_language}; do not introduce any third language, third script, or unrelated regional language. "
            f"Show the future self as a working reality, not a motivational poster. Start with a concrete present-day friction point, then show how life and work change after {timeline}. "
            f"Use {first_milestone_value} naturally as market context, and turn the identity statement into a consequence the user can feel. "
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language."
        ),
        fallback=beat2_fallback,
        min_words=70,
        max_words=80,
        max_tokens=550,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"Right now, some parts of the work still take extra effort because you have not had enough repeated practice in the exact situations that {goal} work demands. In {timeline}, those same situations feel familiar because you will have already built the habit. The market value for that level of judgment sits around {first_milestone_value}.",
            f"In {timeline}, you are not guessing your way through the work anymore. You will have seen the patterns enough times that your decisions feel steadier, your pace feels calmer, and the market reads that difference as {first_milestone_value}.",
            f"The next version of you is not a fantasy cutout. It is you, but with the judgment to handle the pressure that comes with {goal}, and that level of work is already priced around {first_milestone_value}.",
        ),
    )

    beat3_fallback = _normalize_spaces(
        f"The gap is real, but it is not absurd. You already bring {skills} with you, and {module_count} focused capabilities are enough to close what is missing without turning this into a never-ending syllabus."
    )
    beat3_narration = _generate_beat_narration(
        beat_id="beat_3_stakes_gap",
        context=shared_context,
        instructions=(
            f"Explain why the gap is reachable without sounding dramatic. Acknowledge the learner's existing foundation and show that the path is finite, specific, and crossable. "
            f"Mention {module_count} as the number of learnable capability layers only if it helps the rhythm. "
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language."
        ),
        fallback=beat3_fallback,
        min_words=85,
        max_words=95,
        max_tokens=600,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"The gap is real, but it is not absurd. You already bring {skills} with you, and {module_count} focused capabilities are enough to close what is missing without turning this into a never-ending syllabus.",
            f"This is not a zero-to-hero pitch. You already have a base, and the roadmap turns that base into job-ready judgment step by step.",
            f"The path is finite and specific, which is why it is workable. You are not starting from nothing, you are starting from {skills}, and that makes the climb much more practical.",
        ),
    )

    beat4_fallback = _normalize_spaces(
        f"We built this roadmap around your target role, not around a random syllabus. It has {len(milestone_ladder)} milestone(s), and each one changes what you can actually do at work. This was built from your answers, not from a template."
    )
    beat4_narration = _generate_beat_narration(
        beat_id="beat_4_reveal",
        context=shared_context,
        instructions=(
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
            f"Reveal the roadmap as a progression of real capability and life change. Mention the milestone count and each milestone's role, but do not write it like a catalog or use the phrase 'leads to'. "
            f"Translate each milestone label into a distinct consequence the learner can feel in work. Keep the language balanced and natural, with English leading and {preferred_language} used as a human accent rather than a separate section."
        ),
        fallback=beat4_fallback,
        min_words=85,
        max_words=95,
        max_tokens=650,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"We built this roadmap around your target role, not around a random syllabus. It has {len(milestone_ladder)} milestone(s), and each one changes what you can actually do at work. This was built from your answers, not from a template.",
            f"Each milestone is there for a reason. The sequence is designed to move you from where you are now to work that feels more controlled, more credible, and more useful on the job.",
            f"This is the exact progression your inputs called for. The milestones are not decorative; they are the steps that turn your current skills into a path you can actually walk.",
        ),
    )

    # Keep Beat 5 aligned as a synchronized sequence, but make the narration LLM-first per slide.
    project_title = "Real Work Simulation"
    project_why = _normalize_spaces(
        f"You will move through plan, build, check, and ship on one realistic task tied to {goal} work."
    )
    tutor_headline = "Help when you're stuck"
    checkpoint_headline = "Show it to unlock"
    outcomes_headline = "Work feels manageable"

    beat5_modules = roadmap_modules[:4]
    module_names_beat5 = [m["title"] for m in beat5_modules]

    beat5_context = {
        **shared_context,
        "module_names": module_names_beat5,
        "project_title": project_title,
        "project_why": project_why,
        "tutor_headline": tutor_headline,
        "checkpoint_headline": checkpoint_headline,
        "outcomes_headline": outcomes_headline,
        "checkpoint_line": _derive_checkpoint_teaser(roadmap),
        "mock_teaser": _derive_mock_teaser(goal, roadmap, scenario_title or ""),
        "project_teaser": _derive_project_teaser(goal, module_names, roadmap),
        "outcome_line": _derive_outcome_line(goal, skills),
    }

    beat5a_fallback = _normalize_spaces(
        f"Your learning path begins with {_join_phrases(module_names_beat5) or 'the core modules'}. The first layer feels familiar instead of abstract, and the later layers add the kind of practice that makes the work usable."
    )
    beat5a_narration = _generate_beat5_section_narration(
        section_id="beat_5a_modules",
        context={**beat5_context, "section": "modules"},
        instructions=(
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
            f"Explain the module sequence as a real learning path. The slide shows {', '.join(module_names_beat5) if module_names_beat5 else 'the modules'}. "
            f"Make the sequencing feel intentional, and keep the pacing natural with English dominant and {preferred_language} used sparingly for human warmth."
        ),
        fallback=beat5a_fallback,
        min_words=80,
        max_words=95,
        max_tokens=700,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"Your learning path begins with {_join_phrases(module_names_beat5) or 'the core modules'}. The first layer feels familiar instead of abstract, and the later layers add the kind of practice that makes the work usable.",
            f"This section is about sequence, not a catalog. Each module has a job, and the order is there so the skills stack in a way that actually makes sense.",
            f"You are not collecting random lessons. You are moving through a stack of capabilities that becomes more useful with every step.",
        ),
    )

    beat5b_fallback = _normalize_spaces(
        f"By the end of this milestone, you complete one realistic workflow in {goal} work. You plan the task, use the modules in the right order, check the result, and finish with something you can actually show."
    )
    beat5b_narration = _generate_beat5_section_narration(
        section_id="beat_5b_project",
        context={**beat5_context, "section": "project"},
        instructions=(
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
            f"Describe the project simulation in a concrete way. Show that the learner will plan the task, use the modules, check the result, and ship something they can show. "
            f"Avoid generic course language and keep the project feeling like a real deliverable, not a demo for its own sake."
        ),
        fallback=beat5b_fallback,
        min_words=70,
        max_words=85,
        max_tokens=650,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"By the end of this milestone, you complete one realistic workflow in {goal} work. You plan the task, use the modules in the right order, check the result, and finish with something you can actually show.",
            f"This is where the modules become a deliverable. The work moves from learning to building, and that is what makes the milestone feel real.",
            f"The point here is not to hear about a project. It is to finish a workflow that looks and feels like actual work output.",
        ),
    )

    beat5c_fallback = _normalize_spaces(
        f"Real scenario: {scenario_title or f'a real situation a {goal} faces on the job'}. In that moment, you are under pressure to inspect the failure, make the smallest useful fix, and confirm the result still works."
    )
    beat5c_narration = _generate_beat5_section_narration(
        section_id="beat_5c_scenario",
        context={**beat5_context, "section": "scenario"},
        instructions=(
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
            f"Describe the real scenario in a workplace tone. Make the pressure and the decision-making feel real, then connect it directly to why the skill matters. "
            f"This should feel like a live work moment, not an example from a textbook, and it should sound grounded in the user's current context."
        ),
        fallback=beat5c_fallback,
        min_words=90,
        max_words=105,
        max_tokens=750,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"Real scenario: {scenario_title or f'a real situation a {goal} faces on the job'}. In that moment, you are under pressure to inspect the failure, make the smallest useful fix, and confirm the result still works.",
            f"This is the moment where judgment matters. You are looking at a real problem, deciding what to check first, and fixing the right thing without making the situation worse.",
            f"You are not solving a textbook exercise here. You are in a live work moment, with pressure on, and the skill matters because the next step has to be the useful step.",
        ),
    )

    beat5d_fallback = _normalize_spaces(
        f"The checkpoint proves you can apply the skill, and the mock question checks judgment instead of memorization. That keeps the next module earned instead of accidental."
    )
    beat5d_narration = _generate_beat5_section_narration(
        section_id="beat_5d_checkpoint",
        context={**beat5_context, "section": "checkpoint"},
        instructions=(
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
            f"Explain the checkpoint and mock preview. Make it clear that mastery unlocks progress and that the question checks judgment, not rote memorization. "
            f"Keep the pacing crisp and reassuring, and avoid making it sound like a policy memo."
        ),
        fallback=beat5d_fallback,
        min_words=75,
        max_words=90,
        max_tokens=600,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"The checkpoint proves you can apply the skill, and the mock question checks judgment instead of memorization. That keeps the next module earned instead of accidental.",
            f"You do not move forward just because a video ended. You move forward when the work shows mastery, and that is why the checkpoint matters.",
            f"This is the gate, not the ceremony. The mock and the checkpoint exist to prove you can do the thing, not just recognise it.",
        ),
    )

    beat5e_fallback = _normalize_spaces(
        f"With practice on {skills}, daily work starts to feel less intimidating, and the same tasks become more repeatable, steadier, and easier to finish cleanly."
    )
    beat5e_narration = _generate_beat5_section_narration(
        section_id="beat_5e_outcomes",
        context={**beat5_context, "section": "outcomes"},
        instructions=(
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
            f"Describe the outcome after practice. Show how daily work changes, how the learner becomes steadier, and how the same tasks stop feeling intimidating. "
            f"Keep it concrete and role-specific, and make the before-versus-after shift obvious."
        ),
        fallback=beat5e_fallback,
        min_words=75,
        max_words=90,
        max_tokens=600,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"With practice on {skills}, daily work starts to feel less intimidating, and the same tasks become more repeatable, steadier, and easier to finish cleanly.",
            f"The repetition gives you cleaner instincts and faster recovery. What used to feel noisy starts to feel manageable because the pattern is familiar now.",
            f"Your day-to-day work becomes calmer and more predictable. The same kinds of tasks stop draining you because you have already practiced the shape of the problem.",
        ),
    )

    beat5f_fallback = _normalize_spaces(
        f"The AI tutor stays inside every lesson, slows things down when needed, gives hints, and can translate the instruction into plain language without removing the practice that builds real confidence."
    )
    beat5f_narration = _generate_beat5_section_narration(
        section_id="beat_5f_ai_tutor",
        context={**beat5_context, "section": "ai_tutor"},
        instructions=(
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
            f"Explain the AI tutor as support that stays inside every lesson. Show that it helps without removing practice, and mention hints, slower explanations, and translation into plain language. "
            f"Make it feel useful and calm, not like a chatbot demo, and keep English as the main layer of explanation."
        ),
        fallback=beat5f_fallback,
        min_words=60,
        max_words=75,
        max_tokens=550,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"The AI tutor stays inside every lesson, slows things down when needed, gives hints, and can translate the instruction into plain language without removing the practice that builds real confidence.",
            f"When you get stuck, the tutor does not replace the work. It helps you keep moving, explains the next step more simply, and reduces the chance that you freeze.",
            f"This support is there to keep the lesson usable under pressure. It gives hints, simpler explanations, and just enough help to get you unstuck without doing the thinking for you.",
        ),
    )

    beat5_sections = [
        {
            "beat_id": "beat_5a_modules",
            "template_path": "src/template/consultation/beat_5a_modules.html",
            "narration": beat5a_narration,
            "on_screen": {},
        },
        {
            "beat_id": "beat_5b_project",
            "template_path": "src/template/consultation/beat_5b_project.html",
            "narration": beat5b_narration,
            "on_screen": {},
        },
        {
            "beat_id": "beat_5c_scenario",
            "template_path": "src/template/consultation/beat_5c_scenario.html",
            "narration": beat5c_narration,
            "on_screen": {},
        },
        {
            "beat_id": "beat_5d_checkpoint",
            "template_path": "src/template/consultation/beat_5d_checkpoint.html",
            "narration": beat5d_narration,
            "on_screen": {},
        },
        {
            "beat_id": "beat_5e_outcomes",
            "template_path": "src/template/consultation/beat_5e_outcomes.html",
            "narration": beat5e_narration,
            "on_screen": {},
        },
        {
            "beat_id": "beat_5f_ai_tutor",
            "template_path": "src/template/consultation/beat_5f_ai_tutor.html",
            "narration": beat5f_narration,
            "on_screen": {},
        },
    ]

    beat5_narration = _normalize_spaces(" ".join(section["narration"] for section in beat5_sections))

    beat6_narration = _generate_beat_narration(
        beat_id="beat_6_how_it_unlocks",
        context=shared_context,
        instructions=(
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
            f"Explain how mastery checkpoints work, how levels unlock, and why the tutor is built into the lesson. "
            f"Keep it crisp and reassuring, and mention that the user is earning access through proof rather than buying lectures. "
            f"The tone should stay calm, strategic, and lightly motivating, with English dominant and {preferred_language} used only as a human accent if it feels natural."
        ),
        fallback=_normalize_spaces(
            f"You do not buy lessons and hope something sticks. Every skill in your roadmap has a mastery checkpoint, and you move on when the work shows 90% mastery. The AI tutor stays inside every lesson in your preferred language, so support is there without removing the practice."
        ),
        min_words=75,
        max_words=85,
        max_tokens=550,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"You do not buy lessons and hope something sticks. Every skill in your roadmap has a mastery checkpoint, and you move on when the work shows 90% mastery. The AI tutor stays inside every lesson in your preferred language, so support is there without removing the practice.",
            f"The system is simple: show mastery, unlock the next step. That keeps the path honest, and it means the tutor helps you reach the gate instead of replacing the gate.",
            f"This is how the learning path stays real. You earn the next module when you can actually do the work, and the tutor is there to help you get there without guessing.",
        ),
    )

    beat7_narration = _generate_beat_narration(
        beat_id="beat_7_cta",
        context=shared_context,
        instructions=(
            f"Close with the {offer['price']} rupees, the {offer['refund_days']} days refund window, and the CTA. The currency is Indian Rupees (INR). Never mention dollars, USD, or any foreign currency. Always say rupees. "
            f"End with the learner's name, future title, and date, and keep the CTA calm and confident rather than pushy. "
            f"Use English for the main close, then a brief human-sounding line in {preferred_language} if it fits naturally."
            f"Dont keep the tone in a sales pitch. Mention why the user needs it."
            f"Strictly generate 60-70% of the narration in English and 30-40% in {preferred_language} only; do not introduce any third language, third script, or unrelated regional language. "
        ),
        fallback=_normalize_spaces(
            f"The roadmap already exists. The milestones are already mapped. The question is no longer whether a path exists. The question is whether you want the version of yourself that comes after it. If you begin today, your first milestone is waiting. The full program is {offer['price']} rupees. If it is not right for you, you have {offer['refund_days']} days to walk away with a full refund. But if it is right, then every week you delay is a week the future version of you waits. {name}. {goal}. {target_date}."
        ),
        min_words=85,
        max_words=95,
        max_tokens=550,
        preferred_language=preferred_language,
        fallback_variants=_fallback_pack(
            f"The roadmap already exists. The milestones are already mapped. The question is no longer whether a path exists. The question is whether you want the version of yourself that comes after it. If you begin today, your first milestone is waiting. The full program is {offer['price']} rupees. If it is not right for you, you have {offer['refund_days']} days to walk away with a full refund. But if it is right, then every week you delay is a week the future version of you waits. {name}. {goal}. {target_date}."
            f"{target_date} will arrive whether you start or not. The question is what arrives with it. If the path feels right, start Milestone 1 and let the next version of you do the work. The price is {offer['price']} rupees ,full refund in {offer['refund_days']} days if it is not right for you. {name}. {goal}. {target_date}."
        ),
    )

    beats = [
        {
            "beat_id": "beat_1_mirror",
            "narration": beat1_narration,
            "on_screen": {
                "name": name,
                "goal": goal,
                "timeline": timeline,
                "hours": hours,
                "skills": skills,
            },
            "duration_s": 0,
        },
        {
            "beat_id": "beat_2_future_self",
            "narration": beat2_narration,
            "on_screen": {
                "goal": goal,
                "market_value": first_milestone_value,
                "identity_statement": milestone_ladder[0]["statement"] if milestone_ladder else "",
                "identity_statement_raw": milestone_ladder[0].get("statement_raw", "") if milestone_ladder else "",
            },
            "duration_s": 0,
        },
        {
            "beat_id": "beat_3_stakes_gap",
            "narration": beat3_narration,
            "on_screen": {
                "gap_label": f"Between you and {goal}",
                "module_count": module_count,
                "target_role": goal,
            },
            "duration_s": 0,
        },
        {
            "beat_id": "beat_4_reveal",
            "narration": beat4_narration,
            "on_screen": {
                "milestones": milestone_ladder,
                "module_preview": milestone_ladder[0]["module_preview"] if milestone_ladder else "",
                "roadmap_summary": _build_roadmap_summary(milestone_ladder),
            },
            "duration_s": 0,
        },
        {
            "beat_id": "beat_5_whats_inside",
            "narration": beat5_narration,
            "on_screen": {
                "goal": goal,
                "scenario_title": scenario_title or f"Real situations a {goal} faces",
                "skill_why": skill_why or f"The capability {goal}s get hired for",
                "tutor_line": "AI tutor — mid-lesson, in your language",
                "module_names": module_names_beat5,
                "roadmap_modules": beat5_modules,
                "beat_5a_modules": beat5_modules,
                "beat_5b_project": {
                    "title": project_title,
                    "why": project_why,
                    "goal": goal,
                },
                "beat_5c_scenario": {
                    "title": scenario_title or f"Real situations a {goal} faces",
                    "why": skill_why or f"The capability {goal}s get hired for",
                    "goal": goal,
                },
                "beat_5d_checkpoint": {
                    "headline": checkpoint_headline,
                    "checkpoint_line": _derive_checkpoint_teaser(roadmap),
                    "mock_line": _derive_mock_teaser(goal, roadmap, scenario_title or ""),
                    "goal": goal,
                },
                "beat_5e_outcomes": {
                    "headline": outcomes_headline,
                    "summary": _derive_outcome_line(goal, skills),
                    "skills": skills,
                    "goal": goal,
                },
                "beat_5f_ai_tutor": {
                    "headline": tutor_headline,
                    "prompts": [
                        "Explain it simply",
                        "Give me a hint",
                        "Show me an example",
                        "Translate it",
                    ],
                },
                "beat_5_sections": beat5_sections,
                "project_teaser": _derive_project_teaser(goal, module_names, roadmap),
                "checkpoint_teaser": _derive_checkpoint_teaser(roadmap),
                "mock_teaser": _derive_mock_teaser(goal, roadmap, scenario_title or ""),
                "outcome_line": _derive_outcome_line(goal, skills),
            },
            "duration_s": 0,
            "beat_5_sections": beat5_sections,
        },
        {
            "beat_id": "beat_6_how_it_unlocks",
            "narration": beat6_narration,
            "on_screen": {
                "unlock_line": "You don't buy lessons. You earn levels.",
                "gate_label": "90% mastery unlocks the next module",
                "module_names": module_names[:3],
            },
            "duration_s": 0,
        },
        {
            "beat_id": "beat_7_cta",
            "narration": beat7_narration,
            "on_screen": {
                "price": offer["price"],
                "anchor": offer["anchor"],
                "per_day": per_day,
                "refund_days": offer["refund_days"],
                "cta_label": "Begin Milestone 1",
                "user_name": name,
                "future_title": goal,
                "target_date": target_date,
            },
            "duration_s": 0,
        },
    ]

    logger.info(f"[SCRIPT GEN] Built {len(beats)} beats for: {name}")
    return beats