File size: 50,799 Bytes
59ec65a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import logging
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,
    allow_hindi: bool = False
) -> bool:

    if not text:
        return False

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

    words = cleaned.split()
    if len(words) < min_words:
        return False

    if max_words is not None and len(words) > max_words:
        return False

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

    if sentence_count < 3:
        return False

    if _looks_truncated(cleaned):
        return False

    if not allow_hindi 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,
    allow_hindi: bool = False,
    attempts: int = 3,
    max_tokens: int = 700
):

    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,
            allow_hindi=allow_hindi
        ):
            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"
    )

    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,
) -> dict:
    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,
    }


def _consultation_prompt(
    beat_id: str,
    context: dict,
    instructions: str,
    min_words: int,
    max_words: int,
) -> str:
    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.
        - 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,
) -> 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,
        attempts=3,
        max_tokens=max_tokens,
    )


def _beat5_section_prompt(
    section_id: str,
    context: dict,
    instructions: str,
    min_words: int,
    max_words: int,
) -> str:
    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.
        - 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,
) -> 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,
        attempts=3,
        max_tokens=max_tokens,
    )


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 _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"

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

    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

    # 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,
    )

    beat1_fallback = (
        f"{name}. "
        f"You told us you work with {skills}. "
        f"You are putting in {hours_clean} hours a week. "
        f"Your goal is {goal}, in {timeline}. "
        f"We went through every answer you gave us and built something specific to you, not from a template."
    )
    beat1_instructions = (
        f"Mirror the learner's profile back in a human, direct way. Mention the name, skills, hours per week, and timeline. "
        f"Make it sound like a consultation, not a form readout. Keep the tone specific and personal."
    )
    beat1_narration = _generate_beat_narration(
        beat_id="beat_1_mirror",
        context=shared_context,
        instructions=beat1_instructions,
        fallback=beat1_fallback,
        min_words=45,
        max_words=60,
        max_tokens=450,
    )

    beat2_fallback = _generate_future_self_narration(
        name, goal, timeline, milestone_ladder[0]["statement"] if milestone_ladder else "", first_milestone_value, skills
    )
    beat2_instructions = (
        f"Show the gap between today and the future self. Start from a concrete current-work situation, then move into how life and work change after {timeline}. "
        f"Reference the market value naturally in INR / rupees, not dollars. Turn the identity statement into a consequence, not a quote. "
        f"Avoid repeating the same sentence structure used in Beat 1."
    )
    beat2_narration = _generate_beat_narration(
        beat_id="beat_2_future_self",
        context=shared_context,
        instructions=beat2_instructions,
        fallback=beat2_fallback,
        min_words=70,
        max_words=80,
        max_tokens=550,
    )

    beat3_fallback = _generate_stakes_narration(goal, module_count, skills)
    beat3_instructions = (
        f"Explain why the gap is reachable. Mention the number of learnable capability layers if useful, but keep it natural. "
        f"Acknowledge the learner's existing foundation and make the path feel crossable, not vague."
    )
    beat3_narration = _generate_beat_narration(
        beat_id="beat_3_stakes_gap",
        context=shared_context,
        instructions=beat3_instructions,
        fallback=beat3_fallback,
        min_words=85,
        max_words=95,
        max_tokens=600,
    )

    beat4_fallback = _normalize_spaces(
        " ".join([
            f"This is the roadmap we built around your goal.",
            f"It contains {len(milestone_ladder)} milestone(s), each showing a different stage of job readiness.",
            *[
                (
                    f"The first milestone {card.get('label') or f'Milestone {idx}'}"
                    f" ({card.get('value') or ''}) opens into a stage where {card.get('statement') or 'job-ready progress'}"
                )
                for idx, card in enumerate(milestone_ladder, start=1)
            ][:3],
            f"This was built from your answers, not from a template.",
        ])
    )
    beat4_instructions = (
        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. Do not reuse the same sentence or the same closing phrase for multiple milestones. "
        f"If the milestone statement is vague, infer a different consequence from the label and milestone order so each stage feels unique."
    )
    beat4_narration = _generate_beat_narration(
        beat_id="beat_4_reveal",
        context=shared_context,
        instructions=beat4_instructions,
        fallback=beat4_fallback,
        min_words=85,
        max_words=95,
        max_tokens=650,
    )

    # 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(
        " ".join([
            f"Your learning path begins with {_join_phrases(module_names_beat5)}.",
            f"{beat5_modules[0].get('title') if beat5_modules else 'The first module'} gives you the starting layer, so the work feels familiar instead of abstract.",
            f"{beat5_modules[1].get('title') if len(beat5_modules) > 1 else 'The next module'} extends that foundation into a more practical layer, so the path feels like a real progression instead of a list of topics.",
            f"That is why this section matters: it shows you how the modules are arranged before the practice starts.",
            f"You are not being handed random lessons. You are being shown the order that helps the skills stack up in a way that makes sense."
        ])
    )
    beat5a_instructions = (
        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 it feel like the learner is moving through useful layers of skill, not browsing a catalog. Mention only the modules shown on the slide."
    )
    beat5a_narration = _generate_beat5_section_narration(
        section_id="beat_5a_modules",
        context={**beat5_context, "section": "modules"},
        instructions=beat5a_instructions,
        fallback=beat5a_fallback,
        min_words=80,
        max_words=95,
        max_tokens=700,
    )

    beat5b_fallback = _normalize_spaces(
        f"By the end of this milestone, you will complete a realistic work simulation that combines {_join_phrases(module_names_beat5[:2]) or 'the core modules'} into one practical workflow used in {goal}. "
        f"You will plan the task, use the modules in the right order, check the result, and finish with something you can actually show. "
        f"Each step feeds the next one, so you can see the workflow as a whole rather than isolated tasks. "
        f"The point is not to hear a summary of the course. The point is to see how the pieces become one usable workflow."
    )
    beat5b_instructions = (
        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. Keep the title concise and the wording tightly aligned with the slide."
    )
    beat5b_narration = _generate_beat5_section_narration(
        section_id="beat_5b_project",
        context={**beat5_context, "section": "project"},
        instructions=beat5b_instructions,
        fallback=beat5b_fallback,
        min_words=70,
        max_words=85,
        max_tokens=650,
    )

    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 not dealing with theory on a slide. You are under pressure to inspect the failure, figure out where the break happened, make the smallest useful fix, and confirm the result still works. "
        f"That is why this step matters: {skill_why or f'the capability {goal}s get hired for'}. It turns the skill into a work habit, and it shows why this capability matters in real interviews and real jobs."
    )
    beat5c_instructions = (
        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."
    )
    beat5c_narration = _generate_beat5_section_narration(
        section_id="beat_5c_scenario",
        context={**beat5_context, "section": "scenario"},
        instructions=beat5c_instructions,
        fallback=beat5c_fallback,
        min_words=90,
        max_words=105,
        max_tokens=750,
    )

    beat5d_fallback = _normalize_spaces(
        f"{_derive_checkpoint_teaser(roadmap)} {_derive_mock_teaser(goal, roadmap, scenario_title or '')} "
        f"The checkpoint proves you can apply the skill, and the mock question checks judgment instead of memorization. "
        f"That keeps the next module earned instead of accidental."
    )
    beat5d_instructions = (
        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."
    )
    beat5d_narration = _generate_beat5_section_narration(
        section_id="beat_5d_checkpoint",
        context={**beat5_context, "section": "checkpoint"},
        instructions=beat5d_instructions,
        fallback=beat5d_fallback,
        min_words=75,
        max_words=90,
        max_tokens=600,
    )

    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. "
        f"You stop starting from zero each time because the pattern becomes familiar, the steps become clearer, and the work feels more manageable when pressure shows up. "
        f"The repetition gives you cleaner instincts, faster recovery, and more confidence when the task changes under pressure."
    )
    beat5e_instructions = (
        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."
    )
    beat5e_narration = _generate_beat5_section_narration(
        section_id="beat_5e_outcomes",
        context={**beat5_context, "section": "outcomes"},
        instructions=beat5e_instructions,
        fallback=beat5e_fallback,
        min_words=75,
        max_words=90,
        max_tokens=600,
    )

    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. "
        f"It is there to keep you moving when the lesson feels crowded, not to replace the work that makes the skill stick. "
        f"When the work gets noisy, the tutor helps you step back, simplify the next action, and keep moving without freezing."
    )
    beat5f_instructions = (
        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."
    )
    beat5f_narration = _generate_beat5_section_narration(
        section_id="beat_5f_ai_tutor",
        context={**beat5_context, "section": "ai_tutor"},
        instructions=beat5f_instructions,
        fallback=beat5f_fallback,
        min_words=60,
        max_words=75,
        max_tokens=550,
    )

    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))

    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": _generate_beat_narration(
                beat_id="beat_6_how_it_unlocks",
                context=shared_context,
                instructions=(
                    "Explain how mastery checkpoints work, how levels unlock, and why the tutor is built into the lesson. "
                    "Keep it crisp and reassuring. Avoid sounding like a policy memo."
                ),
                fallback=(
                    f"Here is how this works. You do not buy lessons and hope something sticks. Every skill in your roadmap has a mastery checkpoint. "
                    f"Ninety percent mastery before you move on, not because we want to slow you down, but because the next level is built on the current one, and skipping it costs you later. "
                    f"Your AI tutor is available inside every lesson in your language. You are not watching a course. You are building the capability to do the job."
                ),
                min_words=75,
                max_words=85,
                max_tokens=550,
            ),
            "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": _generate_beat_narration(
                beat_id="beat_7_cta",
                context=shared_context,
                instructions=(
                    f"Close with the {offer['price']} rupees, the anchor, the refund window, and the CTA. The currency is Indian Rupees (INR).Never mention dollars, USD, or any foreign currency.Always say rupees. Make it confident and calm, not pushy. "
                    "End with the learner's name, future title, and date."
                ),
                fallback=(
                    f"The roadmap already exists. The milestones are already mapped. The question is no longer whether a path exists. "
                    f"The question is whether you want the version of yourself that comes after it. If you begin today, your first milestone is waiting. "
                    f"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. "
                    f"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,
            ),
            "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