File size: 57,950 Bytes
8e64a96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eb740b
8e64a96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import shutil
import subprocess
import uuid
import json
import time
import asyncio
import random
import re
import importlib.util
import inspect
import requests  
from datetime import datetime
from typing import List, Optional, Union, Dict
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
import google.generativeai as genai
from pydantic import BaseModel
from PIL import Image, ImageDraw, ImageFont
from pydub import AudioSegment
from pydub.silence import detect_silence
from groq import Groq  

# --- سازگاری با محیط‌هایی که Pillow بدون libraqm نصب شده است ---
# در برخی سرورها Pillow بدون کتابخانه libraqm کامپایل می‌شود و پارامترهای
# direction/language/features باعث خطای "not supported without libraqm" می‌شوند.
# این پچ باعث می‌شود در چنین شرایطی به‌جای کرش کردن، متن بدون این پارامترها
# (با جهت پیش‌فرض چپ‌به‌راست کتابخانه) رسم شود و ساخت ویدیو ادامه پیدا کند.
_orig_draw_text = ImageDraw.ImageDraw.text
_orig_draw_textlength = ImageDraw.ImageDraw.textlength
_orig_draw_textbbox = ImageDraw.ImageDraw.textbbox

def _strip_raqm_kwargs(kwargs):
    kwargs.pop('direction', None)
    kwargs.pop('language', None)
    kwargs.pop('features', None)
    return kwargs

def _safe_draw_text(self, xy, text, *args, **kwargs):
    try:
        return _orig_draw_text(self, xy, text, *args, **kwargs)
    except ValueError as e:
        if 'raqm' in str(e).lower():
            return _orig_draw_text(self, xy, text, *args, **_strip_raqm_kwargs(kwargs))
        raise

def _safe_draw_textlength(self, text, *args, **kwargs):
    try:
        return _orig_draw_textlength(self, text, *args, **kwargs)
    except ValueError as e:
        if 'raqm' in str(e).lower():
            return _orig_draw_textlength(self, text, *args, **_strip_raqm_kwargs(kwargs))
        raise

def _safe_draw_textbbox(self, xy, text, *args, **kwargs):
    try:
        return _orig_draw_textbbox(self, xy, text, *args, **kwargs)
    except ValueError as e:
        if 'raqm' in str(e).lower():
            return _orig_draw_textbbox(self, xy, text, *args, **_strip_raqm_kwargs(kwargs))
        raise

ImageDraw.ImageDraw.text = _safe_draw_text
ImageDraw.ImageDraw.textlength = _safe_draw_textlength
ImageDraw.ImageDraw.textbbox = _safe_draw_textbbox

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

TEMP_DIR = "temp"
STATIC_DIR = "static"
STYLES_DIR = "styles"
os.makedirs(TEMP_DIR, exist_ok=True)
os.makedirs(STATIC_DIR, exist_ok=True)
os.makedirs(STYLES_DIR, exist_ok=True)

app.mount("/temp", StaticFiles(directory="temp"), name="temp")
app.mount("/static", StaticFiles(directory="static"), name="static")

MODEL_NAME = "Gemini 3 Flash Preview" 

FONT_DIR = "static/fonts" 
FONT_DATASET_REPO_ID = "Opera8/font"  # دیتاست عمومی هاگینگ‌فیس حاوی تمام فایل‌های فونت
FONT_FILES_MAP = {
    "vazir": "Vazirmatn.ttf", 
    "lalezar": "Lalezar.ttf",
    "amiri": "Amiri-Bold.ttf", 
    "sarbaz": "Sarbaz.ttf", 
    "nastaliq": "IranNastaliq.ttf", 
    "vazir-thin": "Vazirmatn-Thin.ttf", 
    "mada-thin": "Mada-ExtraLight.ttf", 
    "aref-bold": "ArefRuqaa-Bold.ttf", 
    "dastnevis": "Dastnevis.ttf",
    "entazar": "Entazar.ttf",
    "kamran": "Kamran.ttf",
    "gharib": "Gharib.ttf",
    "pinar": "Pinar-Bold.ttf",
    "hasti": "Hasti.ttf",
}

def ensure_fonts_downloaded():
    """
    دیگر هیچ فایل فونتی داخل خود پروژه/اسپیس قرار نمی‌گیرد.
    این تابع در لحظه بالا آمدن سرور، تمام فایل‌های فونت را از دیتاست عمومی
    هاگینگ‌فیس (Opera8/font) دریافت کرده و در مسیر static/fonts ذخیره می‌کند.
    """
    os.makedirs(FONT_DIR, exist_ok=True)
    downloaded_names = []
    failed_names = []
    try:
        from huggingface_hub import list_repo_files, hf_hub_download
        remote_files = list_repo_files(repo_id=FONT_DATASET_REPO_ID, repo_type="dataset")
        font_remote_files = [f for f in remote_files if f.lower().endswith((".ttf", ".otf"))]

        for remote_name in font_remote_files:
            local_name = os.path.basename(remote_name)
            local_path = os.path.join(FONT_DIR, local_name)
            try:
                cached_file_path = hf_hub_download(repo_id=FONT_DATASET_REPO_ID, filename=remote_name, repo_type="dataset")
                shutil.copyfile(cached_file_path, local_path)
                downloaded_names.append(local_name)
            except Exception as e:
                failed_names.append(f"{local_name} ({e})")
    except Exception as e:
        print(f"❌ اتصال به دیتاست فونت‌ها «{FONT_DATASET_REPO_ID}» ناموفق بود: {e}")
        return

    if downloaded_names:
        print(f"✅ تعداد {len(downloaded_names)} فونت از دیتاست «{FONT_DATASET_REPO_ID}» با موفقیت دریافت و ذخیره شد: {', '.join(downloaded_names)}")
    if failed_names:
        print(f"❌ دریافت {len(failed_names)} فونت از دیتاست با خطا مواجه شد:")
        for name in failed_names:
            print(f"   - {name}")

# --- تنظیمات چندزبانه (Multi-language support) ---
# هر زبان: کد ویسپر گراک، جهت نوشتار، متن راهنمای رونویسی، و فونت پیش‌فرض امن برای آن زبان
SUPPORTED_LANGUAGES = {
    "fa": {
        "label": "فارسی", "flag": "🇮🇷", "rtl": True, "whisper_code": "fa",
        "default_font": "pinar",
        "prompt": "سلام سلام، چطوری؟ کلمات دقیقاً همان‌طور که تلفظ می‌شوند، با رعایت حروف اضافه، ساختار عامیانه، محاوره‌ای و شکسته نوشته شوند. حتماً تمامی کلمات تکراری و تکرار پشت سر هم کلمات (مثل سلام سلام، خوب خوب) دقیقاً و دونه به دونه ثبت شوند و به هیچ عنوان حذف یا خلاصه‌سازی نشوند."
    },
    "en": {
        "label": "English", "flag": "🇺🇸", "rtl": False, "whisper_code": "en",
        "default_font": "vazir",
        "prompt": "Hi hi, how are you? Transcribe the words exactly as spoken, keeping casual and colloquial speech intact. Repeated words said back to back (like hi hi, okay okay) must be written exactly and individually, never removed, merged or summarized."
    },
    "ar": {
        "label": "العربية", "flag": "🇸🇦", "rtl": True, "whisper_code": "ar",
        "default_font": "amiri",
        "prompt": "مرحباً مرحباً، كيف حالك؟ يجب كتابة الكلمات تماماً كما تُنطق، بما في ذلك اللهجة العامية. يجب تدوين الكلمات المكررة المتتالية (مثل مرحباً مرحباً) بدقة ودون حذف أو تلخيص."
    },
    "tr": {
        "label": "Türkçe", "flag": "🇹🇷", "rtl": False, "whisper_code": "tr",
        "default_font": "vazir",
        "prompt": "Merhaba merhaba, nasılsın? Kelimeleri tam olarak söylendiği gibi, günlük konuşma diliyle yazın. Art arda tekrar eden kelimeler (merhaba merhaba gibi) tek tek ve eksiksiz yazılmalı, asla silinmemeli veya özetlenmemelidir."
    },
    "es": {
        "label": "Español", "flag": "🇪🇸", "rtl": False, "whisper_code": "es",
        "default_font": "vazir",
        "prompt": "Hola hola, ¿cómo estás? Transcribe las palabras exactamente como se pronuncian, manteniendo el habla coloquial. Las palabras repetidas consecutivamente (como hola hola) deben escribirse exactamente, sin eliminarlas ni resumirlas."
    },
    "fr": {
        "label": "Français", "flag": "🇫🇷", "rtl": False, "whisper_code": "fr",
        "default_font": "vazir",
        "prompt": "Salut salut, comment ça va ? Transcrivez les mots exactement comme ils sont prononcés, en conservant le langage familier. Les mots répétés consécutivement (comme salut salut) doivent être écrits exactement, sans suppression ni résumé."
    },
    "de": {
        "label": "Deutsch", "flag": "🇩🇪", "rtl": False, "whisper_code": "de",
        "default_font": "vazir",
        "prompt": "Hallo hallo, wie geht's? Transkribiere die Wörter genau so, wie sie gesprochen werden, einschließlich Umgangssprache. Aufeinanderfolgende Wiederholungen (wie hallo hallo) müssen exakt und einzeln erfasst werden, niemals entfernt oder zusammengefasst."
    },
    "it": {
        "label": "Italiano", "flag": "🇮🇹", "rtl": False, "whisper_code": "it",
        "default_font": "vazir",
        "prompt": "Ciao ciao, come stai? Trascrivi le parole esattamente come vengono pronunciate, mantenendo il linguaggio colloquiale. Le parole ripetute consecutivamente (come ciao ciao) devono essere scritte esattamente, senza rimuoverle o riassumerle."
    },
    "pt": {
        "label": "Português", "flag": "🇵🇹", "rtl": False, "whisper_code": "pt",
        "default_font": "vazir",
        "prompt": "Oi oi, como vai? Transcreva as palavras exatamente como são faladas, mantendo a linguagem coloquial. Palavras repetidas consecutivamente (como oi oi) devem ser escritas exatamente, sem remover ou resumir."
    },
    "ur": {
        "label": "اردو", "flag": "🇵🇰", "rtl": True, "whisper_code": "ur",
        "default_font": "nastaliq",
        "prompt": "ہیلو ہیلو، کیا حال ہے؟ الفاظ کو بالکل اسی طرح لکھیں جیسے بولے گئے ہیں، بول چال کی زبان کو برقرار رکھیں۔ لگاتار دہرائے گئے الفاظ (جیسے ہیلو ہیلو) کو بالکل اور الگ الگ لکھا جائے، کبھی حذف یا خلاصہ نہ کیا جائے۔"
    },
}
DEFAULT_LANGUAGE = "fa"
RTL_LANGS = {code for code, cfg in SUPPORTED_LANGUAGES.items() if cfg["rtl"]}

def normalize_language(lang: Optional[str]) -> str:
    if lang and lang in SUPPORTED_LANGUAGES:
        return lang
    return DEFAULT_LANGUAGE

# دریافت توکن Groq و Gemini از تنظیمات سکرت اسپیس
GROQ_API_KEYS_ENV = os.getenv("GROQ_API_KEYS", "")
GROQ_API_KEYS = [k.strip() for k in GROQ_API_KEYS_ENV.split(",") if k.strip()]
groq_key_index = 0

API_KEYS = [os.getenv("GEMINI_API_KEY")] if os.getenv("GEMINI_API_KEY") else []

# --- سیستم صف و پایش موقت آپلود غیرهمگام ---
class UploadJobStatus:
    QUEUED = "queued"
    PROCESSING = "processing"
    COMPLETED = "completed"
    FAILED = "failed"

class UploadJob:
    def __init__(self, task_id: str, file_name: str, language: str = "fa"):
        self.id = task_id
        self.file_name = file_name
        self.language = language
        self.status = UploadJobStatus.QUEUED
        self.result = None
        self.error_message = None
        self.created_at = datetime.now()

upload_jobs: Dict[str, UploadJob] = {}

# --- Dynamic Style Loading ---
loaded_styles = {}
style_configs = {}
style_templates = {}

def load_all_styles():
    print("--- Loading Styles from /styles ---")
    for filename in os.listdir(STYLES_DIR):
        if filename.endswith(".py") and filename != "__init__.py":
            module_name = filename[:-3]
            file_path = os.path.join(STYLES_DIR, filename)
            spec = importlib.util.spec_from_file_location(module_name, file_path)
            if spec and spec.loader:
                mod = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(mod)
                
                if hasattr(mod, 'config'):
                    ids = mod.config.get("ids", [])
                    for style_id in ids:
                        loaded_styles[style_id] = mod
                        style_configs[style_id] = mod.config
                        if hasattr(mod, 'frontend_template'):
                            style_templates[style_id] = mod.frontend_template.strip()
                        print(f"Loaded Style: {style_id}")

load_all_styles()

# تنظیم همزمانی پردازش
CONCURRENCY_LIMIT = 20
GEMINI_SEMAPHORE = asyncio.Semaphore(CONCURRENCY_LIMIT)

# --- Data Models ---
class WordInfo(BaseModel):
    word: str; start: float; end: float
    highlight: Optional[bool] = False
    color: Optional[str] = None

class SubtitleSegment(BaseModel):
    id: Optional[Union[str, int]] = None
    start: float
    end: float
    text: str
    words: Optional[List[WordInfo]] = []

class StyleConfig(BaseModel):
    font: str; fontSize: int; primaryColor: str; outlineColor: str
    backType: str; marginV: int
    x: Optional[int] = 0
    name: Optional[str] = "classic"
    radius: Optional[int] = 16
    paddingX: Optional[int] = 20
    paddingY: Optional[int] = 10
    total_video_duration: Optional[float] = None
    current_render_time: Optional[float] = None
    entry_anim_progress: Optional[float] = 1.0
    styleBgColors: Dict[str, str] = {}
    styleColors: Dict[str, str] = {}
    styleActiveColors: Dict[str, str] = {}
    useActiveColor: Optional[bool] = True
    fadeUnread: Optional[bool] = True
    fadeSurrounding: Optional[bool] = False
    typewriter: Optional[bool] = False
    language: Optional[str] = "fa"
    text_direction: Optional[str] = "rtl"
    lang_code: Optional[str] = "fa"
    ai_design: Optional[Dict] = None

class ProcessRequest(BaseModel):
    file_id: str; segments: List[SubtitleSegment]
    video_width: int; video_height: int; style: StyleConfig

class StylePrompt(BaseModel):
    description: str

class JobStatus:
    QUEUED = "queued"; PROCESSING = "processing"
    COMPLETED = "completed"; FAILED = "failed"

class Job:
    def __init__(self, job_id: str, request_data: ProcessRequest):
        self.id = job_id; self.data = request_data; self.status = JobStatus.QUEUED
        self.created_at = datetime.now(); self.result_url = None; self.error_message = None

render_queue = asyncio.Queue()
jobs_db: Dict[str, Job] = {}

async def queue_worker():
    print("--- Queue Worker Started ---")
    while True:
        job_id = await render_queue.get()
        job = jobs_db.get(job_id)
        if job:
            try:
                print(f"Processing job: {job_id}")
                job.status = JobStatus.PROCESSING
                output_url = process_render_logic(job.data)
                job.result_url = output_url
                job.status = JobStatus.COMPLETED  # اصلاح باگ عدم تعریف نام متغیر COMPLETED
                print(f"Job {job_id} completed.")
            except Exception as e:
                print(f"Job {job_id} failed: {e}")
                job.status = JobStatus.FAILED
                job.error_message = str(e)
        render_queue.task_done()

async def cleanup_old_files_loop():
    print("--- File Cleanup Worker Started ---")
    while True:
        await asyncio.sleep(600)  # بررسی وضعیت هر ۱۰ دقیقه یک‌بار
        try:
            now = time.time()
            for filename in os.listdir(TEMP_DIR):
                file_path = os.path.join(TEMP_DIR, filename)
                if filename.endswith(".mp4") and "_final_" in filename:
                    try:
                        mtime = os.path.getmtime(file_path)
                        if now - mtime > 7200:
                            os.remove(file_path)
                            print(f"Cleanup: Removed expired final video: {filename}")
                    except Exception as e:
                        print(f"Cleanup error for {filename}: {e}")
        except Exception as e:
            print(f"Global cleanup loop error: {e}")

@app.on_event("startup")
async def startup_event(): 
    print(f"تعداد {len(API_KEYS)} کلید جیمینای و تعداد {len(GROQ_API_KEYS)} کلید گراک شناسایی شد.")
    ensure_fonts_downloaded()
    check_fonts_integrity()
    asyncio.create_task(queue_worker())
    asyncio.create_task(cleanup_old_files_loop())

def check_fonts_integrity():
    """بررسی سلامت تمامی فایل‌های فونت هنگام بالا آمدن سرور و گزارش آن به فارسی در لاگ"""
    healthy = []
    broken = []
    for key, filename in FONT_FILES_MAP.items():
        fpath = os.path.join(FONT_DIR, filename)
        if not os.path.exists(fpath):
            broken.append(f"{filename} (فایل موجود نیست)")
            continue
        try:
            ImageFont.truetype(fpath, 40)
            healthy.append(filename)
        except Exception as e:
            broken.append(f"{filename} ({e})")

    if healthy:
        print(f"✅ تعداد {len(healthy)} فونت با این نام‌ها شناسایی و با موفقیت بارگذاری شد: {', '.join(healthy)}")
    if broken:
        print(f"❌ تعداد {len(broken)} فونت خراب/ناقص یا در دسترس نبود:")
        for b in broken:
            print(f"   - {b}")

# --- Helper Functions ---
def clean_json_response(text: str):
    text = text.strip()
    if text.startswith('{') and text.endswith('}'): return text
    match = re.search(r'```json\s*(\{.*?\})\s*```', text, re.DOTALL)
    if match: return match.group(1)
    match = re.search(r'\{.*\}', text, re.DOTALL)
    if match: return match.group(0)
    return text

def get_video_info(path):
    try:
        cmd = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,duration", "-of", "json", path]
        res = subprocess.run(cmd, capture_output=True, text=True)
        data = json.loads(res.stdout)
        stream = data['streams'][0]
        w = int(stream.get('width', 1080)); h = int(stream.get('height', 1920)); dur = stream.get('duration')
        if not dur:
            cmd_dur = ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "json", path]
            res_dur = subprocess.run(cmd_dur, capture_output=True, text=True)
            data_dur = json.loads(res_dur.stdout)
            dur = data_dur['format'].get('duration', 60)
        return w, h, float(dur)
    except: return 1080, 1920, 60.0

_FONT_OBJ_CACHE = {}

def get_font_object(style_font_name, size):
    """
    بار کردن فونت درخواستی. اگر فایل فونت موردنظر روی دیسک نبود، مانند قبل
    به فونت پیش‌فرض Vazirmatn سوییچ می‌کند؛ اما اگر فایل فونت وجود داشت ولی خراب/ناقص
    بود (مثلاً مشکل دانلود ناقص Git LFS)، به‌جای رد شدن بی‌صدا، خطای واضح و مشخص
    می‌دهد تا خودتان متوجه شوید و فایل فونت صحیح را در static/fonts قرار دهید.
    """
    cache_key = (style_font_name, size)
    if cache_key in _FONT_OBJ_CACHE:
        return _FONT_OBJ_CACHE[cache_key]

    target_filename = FONT_FILES_MAP.get(style_font_name, "Vazirmatn.ttf")
    target_path = os.path.join(FONT_DIR, target_filename)
    if not os.path.exists(target_path):
        target_path = os.path.join(FONT_DIR, "Vazirmatn.ttf")

    try:
        font_obj = ImageFont.truetype(target_path, size)
    except Exception as e:
        raise RuntimeError(
            f"❌ فایل فونت «{os.path.basename(target_path)}» خراب یا ناقص است و بارگذاری نشد ({e}). "
            f"لطفاً یک فایل فونت (.ttf) سالم را در مسیر static/fonts/{os.path.basename(target_path)} قرار دهید."
        )

    _FONT_OBJ_CACHE[cache_key] = font_obj
    return font_obj

def get_color_tuple(color_str: str, default=(255, 255, 255, 255)):
    if not color_str or not isinstance(color_str, str): return default
    color_str = color_str.strip().lower()
    if color_str.startswith('#'):
        try:
            hex_val = color_str.lstrip('#')
            if len(hex_val) == 6: return tuple(int(hex_val[i:i+2], 16) for i in (0, 2, 4)) + (255,)
            elif len(hex_val) == 8: return tuple(int(hex_val[i:i+2], 16) for i in (0, 2, 4, 6))
        except: pass
    elif color_str.startswith('rgba'):
        try:
            content = color_str[color_str.find('(')+1 : color_str.rfind(')')]
            parts = [x.strip() for x in content.split(',')]
            if len(parts) >= 4:
                r, g, b = int(parts[0]), int(parts[1]), int(parts[2])
                a = int(float(parts[3]) * 255)
                return (r, g, b, a)
        except: pass
    elif color_str.startswith('rgb'):
        try:
            content = color_str[color_str.find('(')+1 : color_str.rfind(')')]
            parts = [x.strip() for x in content.split(',')]
            if len(parts) >= 3: return (int(parts[0]), int(parts[1]), int(parts[2]), 255)
        except: pass
    return default

def create_subtitle_image(text_parts: list, active_idx: int, width: int, height: int, style: StyleConfig, word_infos: Optional[List[WordInfo]] = None):
    img = Image.new('RGBA', (width, height), (0, 0, 0, 0))
    draw = ImageDraw.Draw(img)

    # --- تعیین جهت نوشتار و کد زبان بر اساس زبان انتخابی پروژه (چندزبانه) ---
    lang_code = normalize_language(getattr(style, 'language', None))
    is_rtl = lang_code in RTL_LANGS
    text_direction = 'rtl' if is_rtl else 'ltr'
    setattr(style, 'text_direction', text_direction)
    setattr(style, 'lang_code', lang_code)

    text_offset = 0
    fs = style.fontSize
    if style.font == 'dastnevis':
        text_offset = int(fs * 0.15) if style.name == "music_player" else int(fs * 0.25)
    elif style.font == 'entazar':
        text_offset = int(fs * 0.03) if style.name == "music_player" else int(fs * 0.2)
    elif style.font == 'kamran':
        text_offset = int(fs * 0.03) if style.name == "music_player" else int(fs * 0.2)
    elif style.font == 'pinar':
        text_offset = 0 if style.name == "music_player" else int(fs * -0.2)

    stroke_val = 0
    if style.font == 'entazar' and style.name != "music_player":
        stroke_val = 0.1

    if text_offset != 0 or stroke_val > 0:
        original_text_method = draw.text
        def custom_draw_text(xy, text, **kwargs):
            if stroke_val > 0:
                current_fill = kwargs.get('fill', (255, 255, 255, 255))
                kwargs['stroke_width'] = stroke_val
                kwargs['stroke_fill'] = current_fill
            
            # برای استایل‌های کادردار، انحراف دستی را صفر می‌کنیم تا تراز بصری کادر به هم نخورد
            actual_offset = text_offset
            if style.name in ["instagram_box", "alpha_gradient", "karaoke_static", "auto_director", "falling_karaoke"]:
                actual_offset = 0
                
            original_text_method((xy[0], xy[1] + actual_offset), text, **kwargs)
        draw.text = custom_draw_text

    font = get_font_object(style.font, style.fontSize)
    lines = []
    if style.name == "music_player":
        lines.append(text_parts)
    else:
        MAX_WORDS_PER_LINE = 5
        current_line = []
        for i, word in enumerate(text_parts):
            current_line.append(word)
            if len(current_line) == MAX_WORDS_PER_LINE:
                lines.append(current_line)
                current_line = []
        if current_line:
            lines.append(current_line)

    line_metrics = [] 
    max_line_width = 0
    for line_words in lines:
        w_widths = []
        l_width = 0
        full_line_text = " ".join(line_words)
        try: l_width = draw.textlength(full_line_text, font=font, direction=text_direction, language=lang_code)
        except: l_width = font.getlength(full_line_text)
        if l_width > max_line_width: max_line_width = l_width
        for w in line_words:
            try: wl = draw.textlength(w, font=font, direction=text_direction, language=lang_code)
            except: wl = font.getlength(w)
            w_widths.append(wl)
        line_metrics.append({"width": l_width, "words": line_words, "word_widths": w_widths})

    safe_word_infos = word_infos
    if word_infos:
        safe_word_infos = []
        self_handled = ["instagram_box", "alpha_gradient", "music_player", "falling_words", "falling_karaoke", "blue_cloud", "spring_popup", "falling_plain", "red_outline_box"]
        should_fade_unread = getattr(style, 'fadeUnread', True) and (style.name not in self_handled)
        should_fade_surr = getattr(style, 'fadeSurrounding', False) and (style.name not in self_handled)
        curr_t = getattr(style, 'current_render_time', None)
        
        for i, w in enumerate(word_infos):
            w_copy = w.copy() if hasattr(w, 'copy') else w
            
            if (i == active_idx) and not getattr(style, 'useActiveColor', True):
                if style.name in ["auto_director", "karaoke_static", "falling_karaoke", "alpha_gradient", "falling_plain"]:
                    # اعمال رنگ متن انتخابی کاربر برای استایل‌های داینامیک و نئون آلفا
                    w_copy.color = style.styleColors.get(style.name, "#FFFFFF")
                elif style.name in ["instagram_box"]:
                    # حفظ رفتار قبلی برای باکس متحرک بدون تغییر
                    w_copy.color = "#FFFFFF"
            
            is_future = (curr_t is not None and curr_t < w.start) or (curr_t is None and active_idx != -1 and i > active_idx)
            is_past = (curr_t is not None and curr_t >= w.end) or (curr_t is None and active_idx != -1 and i < active_idx)
            
            if (is_future and (should_fade_unread or should_fade_surr)) or (is_past and should_fade_surr):
                    if style.name in ["classic", "progressive_write"]:
                        default_txt_color = style.primaryColor
                    else:
                        # تعریف جدول رنگ‌های پیش‌فرض استایل‌های اختصاصی جهت جلوگیری از لود رنگ سفید اشتباه
                        default_style_colors = {
                            "blue_outline": "#0000FF",
                            "blue_cloud": "#00b4ff",
                            "dark_edges": "#ffffff",
                            "falling_words": "#ffffff",
                            "falling_karaoke": "#ffffff"
                        }
                        default_txt_color = style.styleColors.get(style.name, default_style_colors.get(style.name, "#FFFFFF"))
                    
                    tr, tg, tb, _ = get_color_tuple(w_copy.color if w_copy.color else default_txt_color, (255, 255, 255, 255))
                    
                    # قرار دادن هر دو استایل جدید در لیست بدون کادرها جهت اعمال مستقیم کانال آلفا
                    no_box_styles = ["karaoke_static", "auto_director", "plain_white", "white_outline", "dark_edges", "blue_outline", "spring_popup", "falling_plain"]
                    if style.name in no_box_styles:
                        w_copy.color = f"rgba({tr},{tg},{tb},0.35)"
                    else:
                        bg_key = 'simple_bar_main_box' if style.name == "simple_bar" else style.name
                        bgr, bgg, bgb, _ = get_color_tuple(style.styleBgColors.get(bg_key, style.outlineColor), (0, 0, 0, 255))
                        fr, fg, fb = int((tr * 0.35) + (bgr * 0.65)), int((tg * 0.35) + (bgg * 0.65)), int((tb * 0.35) + (bgb * 0.65))
                        w_copy.color = f"rgba({fr},{fg},{fb},255)"
            
            safe_word_infos.append(w_copy)

    style_module = loaded_styles.get(style.name)
    if style_module and hasattr(style_module, 'draw_frame'):
        style_module.draw_frame(
            draw=draw,
            img=img,
            width=width,
            height=height,
            style_config=style,
            lines=lines,
            line_metrics=line_metrics,
            active_idx=active_idx,
            font=font,
            color_parser=get_color_tuple,
            word_infos=safe_word_infos
        )
    else:
        y = height - style.marginV
        draw.text((width/2, y), "Style Error", font=font, fill="red")
    return img

def generate_subtitle_video(data: ProcessRequest, temp_dir: str):
    target_styles = [
        "instagram_box",      
        "dark_edges",         
        "falling_words",      
        "classic",            
        "progressive_write"   
    ]
    
    if data.style.name in target_styles:
        data.style.paddingX = (data.style.paddingX or 0) + 15

    list_file = os.path.join(temp_dir, f"{data.file_id}_list.txt")
    empty_img_path = os.path.join(temp_dir, "empty.png")
    if not os.path.exists(empty_img_path): Image.new('RGBA', (data.video_width, data.video_height), (0, 0, 0, 0)).save(empty_img_path)

    sorted_segments = sorted(data.segments, key=lambda x: x.start)
    if sorted_segments:
        setattr(data.style, 'total_video_duration', sorted_segments[-1].end)
    else:
        setattr(data.style, 'total_video_duration', 1.0)

    with open(list_file, "w") as f:
        current_timeline = 0.0
        last_generated_image = "empty.png"

        for idx, seg in enumerate(sorted_segments):
            start_time = round(max(seg.start, current_timeline), 3)
            end_time = round(max(seg.end, start_time + 0.1), 3)
            if end_time - start_time < 0.04: continue

            gap = round(start_time - current_timeline, 3)
            if gap > 0.005:
                # حذف کلمات چسبیده قبلی در زمان سکوت و نمایش ندادن هیچ متنی (نمایش فریم خالی)
                f.write(f"file 'empty.png'\nduration {gap:.3f}\n")
                current_timeline = start_time
                last_generated_image = "empty.png"
            
            current_timeline = start_time
            available_duration = round(end_time - current_timeline, 3)
            words = [w.word for w in seg.words] if seg.words else seg.text.split()
            
            if seg.words and len(words) > 0:
                seg.words.sort(key=lambda x: x.start)
                words = [w.word for w in seg.words]

                SUB_FRAME_DURATION = 0.025 if data.style.name in ["falling_words", "falling_karaoke", "spring_popup"] else 0.05
                time_cursor = start_time
                ANIMATION_DURATION = 0.4 
                while time_cursor < end_time:
                    active_word_index = -1
                    for i, w_info in enumerate(seg.words):
                        if time_cursor >= w_info.start and time_cursor < w_info.end:
                            active_word_index = i
                            break
                    setattr(data.style, 'current_render_time', time_cursor)
                    time_into_segment = time_cursor - start_time
                    anim_progress = min(1.0, time_into_segment / ANIMATION_DURATION)
                    setattr(data.style, 'entry_anim_progress', anim_progress)
                    name = f"sub_{data.file_id}_{idx}_{int(time_cursor*1000)}.png"
                    img = create_subtitle_image(words, active_word_index, data.video_width, data.video_height, data.style, word_infos=seg.words)
                    img.save(os.path.join(temp_dir, name))
                    last_generated_image = name
                    f.write(f"file '{name}'\nduration {SUB_FRAME_DURATION:.3f}\n")
                    time_cursor += SUB_FRAME_DURATION
                current_timeline = end_time
            else:
                name = f"sub_{data.file_id}_{idx}_full.png"
                img = create_subtitle_image(words, -1, data.video_width, data.video_height, data.style, word_infos=seg.words)
                img.save(os.path.join(temp_dir, name))
                f.write(f"file '{name}'\nduration {available_duration:.3f}\n")
                last_generated_image = name
                current_timeline += available_duration

        f.write(f"file 'empty.png'\nduration 30.0\n")
    return list_file

def process_render_logic(req: ProcessRequest) -> str:
    # اعمال زمان‌های مرزی دقیق برای هر سگمنت
    for s in req.segments:
        if s.words:
            s.words.sort(key=lambda x: x.start)
            s.start = s.words[0].start
            s.end = s.words[-1].end

    req.segments = [s for s in req.segments if s.end > s.start]
    req.segments.sort(key=lambda x: x.start)

    lst = generate_subtitle_video(req, TEMP_DIR)
    inp = f"{TEMP_DIR}/{req.file_id}.mp4"
    if not os.path.exists(inp): raise Exception("Input video not found")

    out = f"{TEMP_DIR}/{req.file_id}_final_{int(time.time())}.mp4"
    
    # ترکیب مستقیم روی ویدیو با حفظ زمان‌بندی متغیر (VFR) بدون دستکاری فریم‌ها
    cmd_merge = [
        "ffmpeg", "-y", 
        "-i", inp, 
        "-f", "concat", "-safe", "0", "-i", lst, 
        "-filter_complex", "[0:v][1:v]overlay=0:0:eof_action=pass[outv]", 
        "-map", "[outv]", "-map", "0:a", 
        "-c:v", "libx264", "-r", "30", "-preset", "ultrafast", "-c:a", "aac", out
    ]
    
    res = subprocess.run(cmd_merge, capture_output=True, text=True)
    if res.returncode != 0: raise Exception(f"Merge failed: {res.stderr}")
    return f"/temp/{os.path.basename(out)}"

@app.get("/")
async def index(): return FileResponse("index.html")

@app.get("/api/styles")
def get_style_definitions():
    return {
        "styles": style_configs,
        "templates": style_templates
    }

@app.get("/api/languages")
def get_supported_languages():
    return {
        "default": DEFAULT_LANGUAGE,
        "languages": [
            {"code": code, "label": cfg["label"], "flag": cfg["flag"], "rtl": cfg["rtl"]}
            for code, cfg in SUPPORTED_LANGUAGES.items()
        ]
    }

def _hex_or_default(value, default):
    """اعتبارسنجی ساده کد رنگ هگز؛ اگر نامعتبر بود مقدار پیش‌فرض امن برمی‌گردد."""
    if isinstance(value, str) and re.fullmatch(r"#[0-9A-Fa-f]{6}", value.strip()):
        return value.strip()
    return default

def _clamp_ai_design(raw: dict) -> dict:
    """
    هرچه هوش مصنوعی برگرداند، اینجا کاملاً کنترل و به مقادیر امن محدود (clamp) می‌شود
    تا موتور رندر هیچ‌وقت با یک مقدار عجیب/خراب کرش نکند.
    توجه: این استایل دیگر هیچ‌وقت کادر/باکس/پس‌زمینه دور کلمه نمی‌سازد؛ فقط
    حرکت ورود/خروج و رنگ متن (و در صورت لزوم، درخشش نور) طراحی می‌شود.
    برای فیلدهای نامعتبر/جاافتاده، به‌جای یک مقدار خنثی و همیشه‌یکسان، یک مقدار
    تصادفی و چشمگیر انتخاب می‌شود تا حتی در بدترین حالت (خطای هوش مصنوعی) هم
    خروجی «ساده و کسل‌کننده» به نظر نرسد.
    """
    if not isinstance(raw, dict):
        raw = {}

    entry_options = ["fall", "rise", "pop", "slide_left", "slide_right"]
    exit_options = ["fade", "shrink", "fall", "rise"]
    timing_options = ["elastic", "punch", "smooth"]
    glow_options = ["soft", "strong", "none"]
    valid_fonts = list(FONT_FILES_MAP.keys())
    vivid_color_pairs = [
        ("#FFFFFF", "#FFD700", "#7C4DFF"),
        ("#FFFFFF", "#00E5FF", "#FF2D95"),
        ("#F5F5F5", "#39FF14", "#8A2BE2"),
        ("#FFFFFF", "#FF6EC7", "#00B3FF"),
        ("#EAEAEA", "#FFEE58", "#FF3B30"),
        ("#FFFFFF", "#00FFC6", "#FF5E00"),
    ]

    entry_options_full = {"fall", "rise", "pop", "slide_left", "slide_right", "fade"}
    exit_options_full = {"fade", "shrink", "fall", "rise", "none"}
    timing_options_full = {"elastic", "smooth", "punch", "linear"}
    glow_options_full = {"none", "soft", "strong"}

    entry = raw.get("entry") if raw.get("entry") in entry_options_full else random.choice(entry_options)
    exit_type = raw.get("exit") if raw.get("exit") in exit_options_full else random.choice(exit_options)
    timing = raw.get("timing") if raw.get("timing") in timing_options_full else random.choice(timing_options)
    glow = raw.get("glow") if raw.get("glow") in glow_options_full else random.choice(glow_options)
    font = raw.get("font") if raw.get("font") in valid_fonts else random.choice(valid_fonts)

    try:
        stagger = float(raw.get("stagger", 0.06))
    except (TypeError, ValueError):
        stagger = 0.06
    stagger = max(0.0, min(0.12, stagger))
    if stagger == 0.0 and "stagger" not in raw:
        stagger = round(random.uniform(0.04, 0.09), 2)

    try:
        font_size = int(raw.get("fontSize", 60))
    except (TypeError, ValueError):
        font_size = 60
    font_size = max(30, min(90, font_size))

    fallback_primary, fallback_active, fallback_glow = random.choice(vivid_color_pairs)

    return {
        "entry": entry,
        "exit": exit_type,
        "timing": timing,
        "stagger": stagger,
        "glow": glow,
        "primaryColor": _hex_or_default(raw.get("primaryColor"), fallback_primary),
        "activeColor": _hex_or_default(raw.get("activeColor"), fallback_active),
        "glowColor": _hex_or_default(raw.get("glowColor") or raw.get("shapeColor"), fallback_glow),
        "font": font,
        "fontSize": font_size,
    }

@app.post("/api/generate-style")
def generate_style_api(req: StylePrompt):
    if not API_KEYS: raise HTTPException(500, "API Keys Missing")
    prompt = f"""شما یک طراح موشن‌گرافیک زیرنویس هستی. کار تو فقط طراحی «حرکت ورود کلمات» و «رنگ‌ها»ست — هیچ‌وقت دور متن یا دور کلمات کادر/باکس/حباب نمی‌سازی؛ فقط خود متن با یک انیمیشن و رنگ مشخص روی صحنه ظاهر می‌شود.

توضیح کاربر: "{req.description}"

قوانین جدی که باید دقیقاً رعایت کنی:
1) مهم‌ترین قانون: هرچه کاربر برای «جهت حرکت» گفته را دقیقاً همان اجرا کن. مثلاً:
   - «از بالا بیاد» یا «بریزه» → entry="fall"
   - «از پایین بیاد» یا «بلند شه» → entry="rise"
   - «از چپ بیاد» → entry="slide_left"
   - «از راست بیاد» → entry="slide_right"
   - «بپره تو» یا «پاپ‌آپ» → entry="pop"
   اگر کاربر جهتی نگفت، بر اساس حس‌وحال کلی یک جهت مناسب انتخاب کن.
2) رنگ: هرچه کاربر برای رنگ گفته را دقیقاً همان اجرا کن (مثلاً «قرمز» → یک قرمز واقعی مثل #FF3B30، «آبی» → یک آبی واقعی، «طلایی» → یک طلایی واقعی). اگر کاربر گفت «رنگ کل متن قرمز باشه» یعنی primaryColor باید قرمز باشد. اگر گفت «کلمه‌ای که گفته می‌شه فلان رنگ بشه» یعنی activeColor باید همان رنگ باشد. هرگز رنگ درخواستی کاربر را با یک رنگ «قشنگ‌تر» از نظر خودت جایگزین نکن.
3) glow (درخشش نور اطراف متن) را فقط وقتی روشن کن که کاربر واقعاً به نور/نئون/درخشش اشاره کرده باشد یا حس‌وحال آن (نئون، درخشان، فانتزی) از توضیحش برمی‌آید؛ در غیر این صورت glow="none".
4) اگر کلمه‌ای مثل «آبشاری»، «ریزان»، «موج» گفته شد: stagger را بالا (حدود 0.08 تا 0.12) بگذار.
5) اگر کلمه‌ای مثل «فنری»، «پرشی»، «باحال» گفته شد: timing را "elastic" یا "punch" بگذار؛ برای حس آرام و ساده timing="smooth" یا "linear" بگذار.
6) اگر کاربر توضیح ساده/مینیمالی داد (مثلاً «فقط متن سفید که آروم بیاد»)، رنگ‌ها را ساده نگه‌دار و glow="none" بگذار — زینت اضافه بدون درخواست کاربر اشتباه است.
7) هیچ‌وقت shape/کادر/باکس/پس‌زمینه دور کلمه طراحی نکن؛ فقط حرکت و رنگ خود متن مهم است.

فقط یک JSON با دقیقاً همین کلیدها برگردان (بدون هیچ توضیح اضافه، بدون Markdown):
- entry: یکی از ["fall", "rise", "pop", "slide_left", "slide_right", "fade"]  (نحوه ورود هر کلمه به صحنه)
- exit: یکی از ["fade", "shrink", "fall", "rise", "none"]  (نحوه خروج/فروکش هر کلمه بعد از گفته‌شدن)
- timing: یکی از ["elastic", "smooth", "punch", "linear"]  (منحنی حرکت)
- stagger: عددی بین 0 تا 0.12 (تاخیر آبشاری بین کلمات پشت‌سرهم؛ برای افکت آبشاری عدد بالاتر بده)
- glow: یکی از ["none", "soft", "strong"]  (درخشش نور اطراف متن؛ فقط اگر کاربر خواسته)
- primaryColor: کد رنگ هگز برای رنگ اصلی متن (دقیقاً مطابق درخواست کاربر)
- activeColor: کد رنگ هگز برای کلمه‌ای که همین الان گفته می‌شود (دقیقاً مطابق درخواست کاربر)
- glowColor: کد رنگ هگز برای نور اطراف متن (اگر glow فعال باشد)
- font: یکی از {list(FONT_FILES_MAP.keys())}
- fontSize: عددی بین 30 تا 90"""

    last_error = None
    for attempt in range(3): 
        try:
            genai.configure(api_key=random.choice(API_KEYS))
            model = genai.GenerativeModel(MODEL_NAME)
            res = model.generate_content(
                prompt,
                generation_config={
                    "response_mime_type": "application/json",
                    "temperature": 1.35,
                    "top_p": 0.97,
                }
            )
            data = json.loads(clean_json_response(res.text))
            design = _clamp_ai_design(data)
            return {"success": True, "design": design}
        except Exception as e:
            last_error = str(e)
            print(f"⚠️ تلاش {attempt + 1} برای ساخت استایل هوشمند ناموفق بود: {last_error}")
            continue
    # در صورت شکست کامل هوش مصنوعی، یک طراحی امن و پیش‌فرض برگردانده می‌شود، ولی صادقانه اعلام می‌شود که موفق نبوده
    print(f"❌ ساخت استایل هوشمند بعد از ۳ تلاش ناموفق ماند. آخرین خطا: {last_error}")
    return {"success": False, "design": _clamp_ai_design({}), "error": last_error}

# --- تابع ارسال فایل صوتی به Groq با پرامپت تقویت‌شده تکرارها (چندزبانه) ---
async def transcribe_audio_via_groq(audio_path: str, language: str = "fa"):
    global groq_key_index
    if not GROQ_API_KEYS:
        raise Exception("متغیر محیطی GROQ_API_KEYS در قسمت Secrets تنظیم نشده است.")
    
    lang_cfg = SUPPORTED_LANGUAGES.get(language, SUPPORTED_LANGUAGES[DEFAULT_LANGUAGE])
    
    # انتخاب چرخشی کلید
    current_key = GROQ_API_KEYS[groq_key_index % len(GROQ_API_KEYS)]
    groq_key_index += 1
    
    client = Groq(api_key=current_key)
    
    def call_groq():
        with open(audio_path, "rb") as file:
            return client.audio.transcriptions.create(
                file=(os.path.basename(audio_path), file.read()),
                model="whisper-large-v3",
                response_format="verbose_json",
                timestamp_granularities=["word", "segment"],
                temperature=0.0,
                language=lang_cfg["whisper_code"],
                prompt=lang_cfg["prompt"]
            )
            
    transcription = await asyncio.to_thread(call_groq)
    return transcription

# --- تابع بازگشتی هوشمند برای برش فایل‌های صوتی سنگین از نقاط سکوت (چندزبانه) ---
async def transcribe_audio_recursive(audio_path: str, start_time_offset: float = 0.0, language: str = "fa") -> list:
    file_size = os.path.getsize(audio_path)
    MAX_SIZE = 24 * 1024 * 1024  # 24 MB محدودیت امن

    if file_size <= MAX_SIZE:
        transcription = await transcribe_audio_via_groq(audio_path, language)
        
        # استخراج ساختار داده خروجی Groq
        if hasattr(transcription, "model_dump"):
            data = transcription.model_dump()
        elif hasattr(transcription, "dict"):
            data = transcription.dict()
        elif isinstance(transcription, dict):
            data = transcription
        else:
            try: data = dict(transcription)
            except: data = {}
            
        raw_word_items = []
        segments = data.get("segments", [])
        words_list = data.get("words", [])
        
        if words_list:
            raw_word_items = words_list
        elif segments:
            for seg in segments:
                text_val = seg.get("text", "").strip()
                if not text_val: continue
                if "words" in seg and seg["words"]:
                    raw_word_items.extend(seg["words"])
                else:
                    seg_start = float(seg.get("start", 0))
                    seg_end = float(seg.get("end", 0))
                    w_list = text_val.split()
                    if w_list:
                        duration = seg_end - seg_start
                        word_duration = duration / max(1, len(w_list))
                        for i, w_txt in enumerate(w_list):
                            w_start_time = seg_start + (i * word_duration)
                            raw_word_items.append({
                                "word": w_txt,
                                "start": round(w_start_time, 3),
                                "end": round(w_start_time + word_duration, 3)
                            })
        
        # اعمال آفست زمانی برای برش‌های بعدی که در جای درست قرار بگیرند
        adjusted_words = []
        for w in raw_word_items:
            if not isinstance(w, dict):
                word_text = getattr(w, "word", getattr(w, "text", ""))
                word_start = float(getattr(w, "start", getattr(w, "start_time", 0)))
                word_end = float(getattr(w, "end", getattr(w, "end_time", 0)))
            else:
                word_text = w.get("word", w.get("text", ""))
                word_start = float(w.get("start", w.get("start_time", 0)))
                word_end = float(w.get("end", w.get("end_time", 0)))
            
            adjusted_words.append({
                "word": word_text,
                "start": round(word_start + start_time_offset, 3),
                "end": round(word_end + start_time_offset, 3)
            })
        return adjusted_words

    else:
        # فایل سنگین‌تر از حد مجاز است، باید برش بخورد
        print(f"File size {file_size} > 24MB. Splitting audio...")
        audio = await asyncio.to_thread(AudioSegment.from_mp3, audio_path)
        mid_point_ms = len(audio) // 2

        # جستجو برای پیدا کردن نقطه سکوت در محدوده 40% تا 60% فایل
        search_start = int(len(audio) * 0.4)
        search_end = int(len(audio) * 0.6)
        search_chunk = audio[search_start:search_end]
        
        def find_silences():
            # تشخیص سکوت (سکوت بالاتر از 500 میلی‌ثانیه با آستانه -40dB)
            return detect_silence(search_chunk, min_silence_len=500, silence_thresh=-40)
            
        silences = await asyncio.to_thread(find_silences)
        
        if silences:
            # انتخاب سکوتی که نزدیک‌ترین فاصله را به وسط بخش مورد جستجو دارد
            best_silence = silences[len(silences)//2]
            split_point_ms = search_start + (best_silence[0] + best_silence[1]) // 2
        else:
            # اگر هیچ سکوتی پیدا نشد، دقیقاً از وسط برش می‌زنیم
            split_point_ms = mid_point_ms
            
        part1_path = audio_path.replace(".mp3", f"_part1_{int(time.time()*1000)}_{random.randint(100,999)}.mp3")
        part2_path = audio_path.replace(".mp3", f"_part2_{int(time.time()*1000)}_{random.randint(100,999)}.mp3")
        
        def export_parts():
            audio[:split_point_ms].export(part1_path, format="mp3", bitrate="64k")
            audio[split_point_ms:].export(part2_path, format="mp3", bitrate="64k")
            
        await asyncio.to_thread(export_parts)
        
        # فراخوانی بازگشتی هوش مصنوعی برای هر دو قسمت
        words1 = await transcribe_audio_recursive(part1_path, start_time_offset, language)
        words2 = await transcribe_audio_recursive(part2_path, start_time_offset + (split_point_ms / 1000.0), language)
        
        # پاکسازی فایل‌های تکه‌تکه‌شده
        try:
            os.remove(part1_path)
            os.remove(part2_path)
        except Exception as e:
            print(f"Cleanup error for split files: {e}")
            
        # تجمیع نتایج
        return words1 + words2

# --- پردازش موقت در صف پس‌زمینه (نسخه اصلاح شده بدون فیلتر متنی، چندزبانه و با پشتیبانی از فایل‌های سنگین) ---
async def bg_process_upload(task_id: str, raw_path: str, fixed_path: str, audio_path: str, language: str = "fa"):
    job = upload_jobs.get(task_id)
    if not job:
        return
    
    job.status = UploadJobStatus.PROCESSING
    try:
        # ۱. تبدیل ویدیوی خام به فرمت استاندارد 30fps h264
        proc1 = await asyncio.create_subprocess_exec(
            "ffmpeg", "-y", "-i", raw_path, "-r", "30", "-c:v", "libx264", 
            "-preset", "ultrafast", "-c:a", "copy", fixed_path,
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )
        await proc1.communicate()
        
        w, h, total_duration = get_video_info(fixed_path)
        
        # ۲. استخراج مستقیم صدا به صورت MP3 با نرخ بیت 64k
        proc2 = await asyncio.create_subprocess_exec(
            "ffmpeg", "-y", "-i", fixed_path, "-vn", "-acodec", "libmp3lame", 
            "-ar", "16000", "-ac", "1", "-b:a", "64k", audio_path,
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
        )
        await proc2.communicate()
        
        print(f"--- [BG Task {task_id}] Transcribing audio with Recursive Groq Logic (lang={language}) ---")
        
        # ۳. ارسال فایل صوتی به تابع هوشمند که فایل‌های سنگین را برش می‌دهد
        raw_word_items = await transcribe_audio_recursive(audio_path, 0.0, language)
        
        # پاکسازی فایل‌های موقت پایه
        if os.path.exists(audio_path):
            try: os.remove(audio_path)
            except: pass
        if os.path.exists(raw_path):
            try: os.remove(raw_path)
            except: pass

        if not raw_word_items:
            job.status = UploadJobStatus.FAILED
            job.error_message = "تبدیل گفتار به متن ناموفق بود. هیچ متنی در فایل شناسایی نشد."
            return

        # ۶. گروه‌بندی کلمات به صورت دسته‌های ۵ تایی استاندارد
        final_segs = []
        chunk_size = 5
        for k in range(0, len(raw_word_items), chunk_size):
            sub = raw_word_items[k:k+chunk_size]
            if not sub: continue
            sc_words = []
            for w in sub:
                sc_words.append({
                    "word": w["word"],
                    "start": round(w["start"], 3),
                    "end": round(w["end"], 3),
                    "highlight": False
                })
            
            if sc_words:
                final_segs.append({
                    "start": sc_words[0]["start"],
                    "end": sc_words[-1]["end"],
                    "text": " ".join([x["word"] for x in sc_words]),
                    "words": sc_words
                })

        lang_cfg = SUPPORTED_LANGUAGES.get(language, SUPPORTED_LANGUAGES[DEFAULT_LANGUAGE])
        suggested_style = {"primaryColor": "#FFFFFF", "outlineColor": "#000000", "font": lang_cfg["default_font"], "fontSize": 60, "backType": "solid"}

        job.result = {
            "file_id": task_id,
            "url": f"/temp/{task_id}.mp4",
            "width": w,
            "height": h,
            "segments": final_segs,
            "suggested_style": suggested_style,
            "language": language
        }
        job.status = UploadJobStatus.COMPLETED

    except Exception as e:
        if os.path.exists(audio_path):
            try: os.remove(audio_path)
            except: pass
        if os.path.exists(raw_path):
            try: os.remove(raw_path)
            except: pass
        job.status = UploadJobStatus.FAILED
        job.error_message = f"Processing Error: {str(e)}"

@app.post("/api/upload")
async def upload(background_tasks: BackgroundTasks, file: UploadFile = File(...), language: str = Form("fa")):
    task_id = str(uuid.uuid4())[:8]
    ext = file.filename.split('.')[-1]
    raw_path = f"{TEMP_DIR}/{task_id}_raw.{ext}"
    fixed_path = f"{TEMP_DIR}/{task_id}.mp4"
    audio_path = f"{TEMP_DIR}/{task_id}.mp3"
    lang = normalize_language(language)
    
    try:
        with open(raw_path, "wb") as f:
            shutil.copyfileobj(file.file, f)
            
        upload_jobs[task_id] = UploadJob(task_id, file.filename, lang)
        
        background_tasks.add_task(
            bg_process_upload, task_id, raw_path, fixed_path, audio_path, lang
        )
        
        return {"task_id": task_id, "status": UploadJobStatus.QUEUED, "language": lang}
    except Exception as e:
        if os.path.exists(raw_path):
            try: os.remove(raw_path)
            except: pass
        raise HTTPException(500, f"Failed to queue upload task: {str(e)}")

@app.get("/api/upload-status/{task_id}")
async def get_upload_status(task_id: str):
    job = upload_jobs.get(task_id)
    if not job:
        raise HTTPException(404, "Upload job not found")
    
    response = {"task_id": job.id, "status": job.status, "language": job.language}
    if job.status == UploadJobStatus.COMPLETED:
        response["result"] = job.result
    elif job.status == UploadJobStatus.FAILED:
        response["error"] = job.error_message
    return response

import glob

@app.delete("/api/delete-project/{file_id}")
async def delete_project_files(file_id: str):
    if "/" in file_id or "\\" in file_id or ".." in file_id:
        raise HTTPException(400, "Invalid file_id")
    
    raw_video_path = os.path.join(TEMP_DIR, f"{file_id}.mp4")
    if os.path.exists(raw_video_path):
        try: os.remove(raw_video_path)
        except Exception as e: print(f"Error removing raw video: {e}")
    
    final_patterns = os.path.join(TEMP_DIR, f"{file_id}_final_*.mp4")
    for f_path in glob.glob(final_patterns):
        try: os.remove(f_path)
        except Exception as e: print(f"Error removing final video {f_path}: {e}")
    
    return {"status": "success", "message": "Files deleted successfully"}

@app.post("/api/reupload")
async def reupload_video(file: UploadFile = File(...), file_id: str = Form(...)):
    if not file_id or '/' in file_id or '\\' in file_id: raise HTTPException(400, "Invalid file_id")
    target_path = os.path.join(TEMP_DIR, f"{file_id}.mp4")
    try:
        with open(target_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer)
    except Exception as e: raise HTTPException(500, f"Could not save file: {e}")
    finally: await file.close()
    return {"status": "success", "message": f"File {file_id}.mp4 restored."}

@app.post("/api/enqueue-render")
async def enqueue_render(req: ProcessRequest):
    if not os.path.exists(os.path.join(TEMP_DIR, f"{req.file_id}.mp4")):
        return JSONResponse(status_code=200, content={"error": "Video not found", "error_code": "VIDEO_NOT_FOUND"})
    job_id = str(uuid.uuid4())
    jobs_db[job_id] = Job(job_id, req)
    await render_queue.put(job_id)
    return {"job_id": job_id, "status": JobStatus.QUEUED}

@app.get("/api/job-status/{job_id}")
async def get_job_status(job_id: str):
    job = jobs_db.get(job_id)
    if not job: raise HTTPException(404, "Job not found")
    response = {"job_id": job.id, "status": job.status}
    if job.status == JobStatus.QUEUED:
        response["queue_position"] = sum(1 for j in jobs_db.values() if j.status == JobStatus.QUEUED and j.created_at < job.created_at) + 1
    elif job.status == JobStatus.COMPLETED: response["url"] = job.result_url # اصلاح نام متغیر COMPLETED به JobStatus.COMPLETED
    elif job.status == JobStatus.FAILED: response["error"] = job.error_message
    return response