File size: 81,800 Bytes
ab34392
 
0c0e10a
 
ab34392
0c0e10a
 
 
 
 
ab34392
0c0e10a
 
ab34392
0c0e10a
 
ab34392
0c0e10a
 
ab34392
0c0e10a
ab34392
 
0c0e10a
 
 
 
ab34392
0c0e10a
ab34392
0c0e10a
 
 
ab34392
0c0e10a
9d921b8
0c0e10a
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
ab34392
 
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
 
0c0e10a
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
 
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
 
0c0e10a
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
ab34392
0c0e10a
 
ab34392
0c0e10a
 
 
 
 
ab34392
0c0e10a
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
ab34392
0c0e10a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab34392
 
0c0e10a
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
import os
import time
import math
import json
import asyncio
import subprocess
import uuid
import yt_dlp
from datetime import datetime, timedelta
from threading import Thread
from flask import Flask
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery

# --- Hugging Face को जगाए रखने के लिए Flask Server ---
app = Flask(__name__)
@app.route('/')
def health_check():
    return "Bot is running perfectly!"

def run_flask():
    app.run(host="0.0.0.0", port=7860)

# --- Telegram Bot की डिटेल्स (Environment Variables से) ---
BOT_TOKEN = os.getenv("BOT_TOKEN")  
API_ID = int(os.getenv("API_ID", "0"))         
API_HASH = os.getenv("API_HASH") 

bot = Client("LiveBot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)

# --- USER SESSION (Private Channel Download के लिए) ---
USER_SESSION = os.getenv("USER_SESSION")  
user_app = Client("UserAcc", api_id=API_ID, api_hash=API_HASH, session_string=USER_SESSION)

# --- ग्लोबल वेरिएबल्स ---
ADMIN_ID = 8806858506
GLOBAL_PASSWORD = "jitu@123"
PASSWORD_LIMIT = 999999  # डिफ़ॉल्ट लिमिट (Unlimted)
PASSWORD_USED_BY = {}    # जिन लोगों ने पासवर्ड इस्तेमाल किया है उनका डेटा
GLOBAL_LIMIT = 1  
user_data = {}
admin_state = None  

# --- मैसेज डिलीट करने के लिए नया डेटाबेस (टेम्परेरी) ---
sent_message_map = {} 
recent_admin_messages =[] 
GLOBAL_SCHEDULE_TIMES = [] # एडमिन के सेट किये गए प्री-डिफाइंड शेड्यूल्स 

# --- Data Persistence (बॉट रिस्टार्ट होने पर डेटा सेव रखने के लिए) ---
DATA_FILE = "bot_config.json"

def save_data():
    try:
        # सिर्फ ऑथेंटिकेटेड यूज़र्स का डेटा सेव करेंगे ताकि फाइल भारी न हो
        auth_users = {str(uid): info['name'] for uid, info in user_data.items() if info.get('authenticated')}
        with open(DATA_FILE, "w") as f:
            json.dump({
                "GLOBAL_PASSWORD": GLOBAL_PASSWORD,
                "PASSWORD_LIMIT": PASSWORD_LIMIT,
                "GLOBAL_LIMIT": GLOBAL_LIMIT,
                "PASSWORD_USED_BY": {str(k): v for k, v in PASSWORD_USED_BY.items()},
                "authenticated_users": auth_users,
                "GLOBAL_SCHEDULE_TIMES": GLOBAL_SCHEDULE_TIMES
            }, f)
    except Exception as e: pass

def load_data():
    global GLOBAL_PASSWORD, PASSWORD_LIMIT, GLOBAL_LIMIT, PASSWORD_USED_BY, user_data
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, "r") as f:
                data = json.load(f)
                GLOBAL_PASSWORD = data.get("GLOBAL_PASSWORD", "jitu@123")
                PASSWORD_LIMIT = data.get("PASSWORD_LIMIT", 999999)
                GLOBAL_LIMIT = data.get("GLOBAL_LIMIT", 1)
                PASSWORD_USED_BY = {int(k): v for k, v in data.get("PASSWORD_USED_BY", {}).items()}
                GLOBAL_SCHEDULE_TIMES = data.get("GLOBAL_SCHEDULE_TIMES", [])
                
                saved_users = data.get("authenticated_users", {})
                for uid, name in saved_users.items():
                    uid = int(uid)
                    if uid not in user_data:
                        user_data[uid] = {
                            'name': name,
                            'authenticated': True,
                            'step': 'PLATFORM',
                            'platform': None,
                            'rtmp_url': None,
                            'loop_hours': 0,
                            'orientation': 'landscape', 
                            'custom_image_path': None,
                            'custom_audio_path': None,
                            'video_url': None,
                            'schedule_time': None,
                            'processes':[], 
                            'stream_limit': GLOBAL_LIMIT, 
                            'file_path': None,
                            'manual_stop': False,
                            'join_date': get_ist_time(),
                            'last_online': get_ist_time(),
                            'total_streams': 0,
                            'last_stream': "Never"
                        }
        except Exception as e: pass

def get_ist_time():
    return datetime.utcnow() + timedelta(hours=5, minutes=30)

def format_date(dt):
    if isinstance(dt, str): return dt
    return dt.strftime("%d-%b-%Y %I:%M %p")

def get_video_duration(file_path):
    try:
        result = subprocess.run(
            ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL,
            text=True
        )
        return float(result.stdout.strip())
    except:
        return 0

def has_audio_stream(file_path):
    try:
        result = subprocess.run(
            ["ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=codec_type", "-of", "default=noprint_wrappers=1:nokey=1", file_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL,
            text=True
        )
        return bool(result.stdout.strip())
    except:
        return False

def update_schedule_dates():
    global GLOBAL_SCHEDULE_TIMES
    now_ist = get_ist_time().replace(tzinfo=None)
    updated = False
    new_times = []
    
    for time_str in GLOBAL_SCHEDULE_TIMES:
        try:
            dt_obj = datetime.strptime(time_str, "%d/%m/%Y %I:%M %p")
            while dt_obj <= now_ist:
                dt_obj += timedelta(days=1)
                updated = True
            new_times.append(dt_obj.strftime("%d/%m/%Y %I:%M %p"))
        except:
            new_times.append(time_str) 
            
    if updated:
        unique_times = list(dict.fromkeys(new_times))
        GLOBAL_SCHEDULE_TIMES.clear()
        GLOBAL_SCHEDULE_TIMES.extend(unique_times)
        save_data()

async def notify_admin(client, text):
    try:
        await client.send_message(ADMIN_ID, text)
    except:
        pass

def init_user(user_id, message=None):
    if user_id not in user_data:
        name = message.from_user.first_name if message else "Unknown"
        user_data[user_id] = {
            'name': name,
            'authenticated': False if user_id != ADMIN_ID else True, 
            'step': 'PASSWORD' if user_id != ADMIN_ID else 'PLATFORM',
            'platform': None,
            'rtmp_url': None,
            'loop_hours': 0,
            'orientation': 'landscape', 
            'custom_image_path': None, 
            'custom_audio_path': None, 
            'intro_audio_path': None,  # <--- NEW: शुरू में बजने वाला ऑडियो
            'watermark_text': None,    
            'video_url': None,         
            'schedule_time': None,     
            'processes':[], 
            'scheduled_tasks': {},     
            'stream_limit': GLOBAL_LIMIT, 
            'video_files': [],         # <--- NEW: Multi Video Playlist
            'manual_stop': False,
            'join_date': get_ist_time(),
            'last_online': get_ist_time(),
            'total_streams': 0,
            'last_stream': "Never"
        }
        if user_id != ADMIN_ID:
            asyncio.create_task(notify_admin(bot, f"🔔 **New User Joined!**\n👤 **Name:** {name}\n🆔 **ID:** `{user_id}`\n📅 **Date:** {format_date(get_ist_time())}"))
    else:
        user_data[user_id]['last_online'] = get_ist_time()
        if message:
            user_data[user_id]['name'] = message.from_user.first_name

def platform_keyboard():
    return InlineKeyboardMarkup([[InlineKeyboardButton("🔴 YouTube Live", callback_data="plat_youtube")],[InlineKeyboardButton("🟢 Rumble Live", callback_data="plat_rumble")],[InlineKeyboardButton("🔵 Custom/Other", callback_data="plat_custom")]])

def loop_keyboard():
    return InlineKeyboardMarkup([[InlineKeyboardButton("▶️ 1 Time (No Loop)", callback_data="loop_0")],[InlineKeyboardButton("⏳ 30 Mins", callback_data="loop_0.5"), InlineKeyboardButton("⏳ 1 Hour", callback_data="loop_1")],[InlineKeyboardButton("🔁 3 Hours", callback_data="loop_3"), InlineKeyboardButton("🔁 6 Hours", callback_data="loop_6")],[InlineKeyboardButton("🔁 12 Hours", callback_data="loop_12"), InlineKeyboardButton("🔁 24 Hours", callback_data="loop_24")]
    ])

def orientation_keyboard():
    return InlineKeyboardMarkup([[InlineKeyboardButton("🖥 Landscape (16:9)", callback_data="ori_landscape")],[InlineKeyboardButton("📱 Portrait / Shorts (9:16)", callback_data="ori_portrait")]])

def image_choice_keyboard():
    return InlineKeyboardMarkup([[InlineKeyboardButton("✅ Yes (Add Custom Photo)", callback_data="img_yes")],[InlineKeyboardButton("❌ No (Normal Black Bg)", callback_data="img_no")]])

def audio_choice_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("🎵 Intro Audio (शुरू में लगाएं)", callback_data="aud_intro")],
        [InlineKeyboardButton("🎵 Replace Full Audio (पूरा बदलें)", callback_data="aud_yes")],
        [InlineKeyboardButton("🔊 Keep Original Audio", callback_data="aud_no")]
    ])

def watermark_choice_keyboard():
    return InlineKeyboardMarkup([[InlineKeyboardButton("✅ Yes (Moving Watermark)", callback_data="wm_yes")],[InlineKeyboardButton("❌ No Watermark", callback_data="wm_no")]])

def schedule_choice_keyboard():
    return InlineKeyboardMarkup([[InlineKeyboardButton("▶️ Start Now", callback_data="sch_now")],[InlineKeyboardButton("⏳ Schedule Time", callback_data="sch_later")]])

def more_video_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("➕ Add More Video", callback_data="vid_add")],
        [InlineKeyboardButton("✅ Done (Start Live)", callback_data="vid_done")]
    ])

def admin_keyboard():
    return InlineKeyboardMarkup([
        [InlineKeyboardButton("👥 Users List", callback_data="admin_users"), InlineKeyboardButton("🔴 Live Status", callback_data="admin_live")],
        [InlineKeyboardButton("🔑 Change Password", callback_data="admin_pass"), InlineKeyboardButton("⚙️ Set Limit", callback_data="admin_limit")],
        [InlineKeyboardButton("📅 Manage Schedule Times", callback_data="admin_sch_times")],
        [InlineKeyboardButton("📢 Broadcast / Send Msg", callback_data="admin_msg")],
        [InlineKeyboardButton("🗑 Delete Last 5 Broadcasts", callback_data="admin_del")]
    ])

# --- Live Progress Bar ---
async def progress_bar(current, total, msg, start_time, last_update):
    now = time.time()
    if now - last_update[0] > 3 or current == total:
        last_update[0] = now
        diff = now - start_time
        percentage = current * 100 / total
        speed = current / diff if diff > 0 else 0
        eta = round((total - current) / speed) if speed > 0 else 0
        
        current_mb = round(current / (1024 * 1024), 2)
        total_mb = round(total / (1024 * 1024), 2)
        speed_mb = round(speed / (1024 * 1024), 2)
        
        progress_str = "[{0}{1}]".format(''.join(["█" for _ in range(math.floor(percentage / 5))]), ''.join(["░" for _ in range(20 - math.floor(percentage / 5))]))
        eta_str = f"{eta} sec" if eta < 60 else f"{eta//60} min {eta%60} sec"
        
        text = f"📥 **Downloading Video...**\n\n{progress_str} **{round(percentage, 2)}%**\n📦 **Size:** `{current_mb} MB / {total_mb} MB`\n🚀 **Speed:** `{speed_mb} MB/s`\n⏳ **ETA:** `{eta_str}`"
        try: await msg.edit_text(text)
        except: pass

@bot.on_message(filters.command("admin"))
async def admin_cmd(client, message):
    if message.chat.id == ADMIN_ID:
        global admin_state
        admin_state = None
        await message.reply("👑 **Welcome to Admin Panel**\nChoose an option below:", reply_markup=admin_keyboard())

@bot.on_message(filters.command("start"))
async def start_cmd(client, message):
    user_id = message.chat.id
    init_user(user_id, message)
    if user_data[user_id]['authenticated']:
        user_data[user_id]['step'] = 'PLATFORM'
        await message.reply("**✅ Logged in!**\n👇 **Select platform:**", reply_markup=platform_keyboard())
    else:
        user_data[user_id]['step'] = 'PASSWORD'
        await message.reply("👋 **Welcome!**\n🔐 **Enter Password to continue:**")

@bot.on_message(filters.command("new"))
async def new_cmd(client, message):
    user_id = message.chat.id
    init_user(user_id, message)
    
    if not user_data[user_id]['authenticated']:
        user_data[user_id]['step'] = 'PASSWORD'
        return await message.reply("🔐 **Session Expired! Please enter the new password:**")
        
    user_data[user_id]['step'] = 'PLATFORM'
    user_data[user_id]['custom_image_path'] = None 
    user_data[user_id]['custom_audio_path'] = None
    user_data[user_id]['watermark_text'] = None
    user_data[user_id]['video_url'] = None
    user_data[user_id]['video_files'] = []  # <--- NEW
    await message.reply("🔄 **New Stream Setup!**\n👇 **Select platform:**", reply_markup=platform_keyboard())

@bot.on_message(filters.command("stop"))
async def stop_cmd(client, message):
    user_id = message.chat.id
    if user_id not in user_data: return
    
    active_procs = [p for p in user_data[user_id].get('processes', []) if (p['process'].poll() if isinstance(p, dict) else p.poll()) is None]
    
    if not active_procs:
        return await message.reply("⚠️ **No active stream found.**\n(आपकी कोई स्ट्रीम अभी नहीं चल रही है)")
        
    text = "🛑 **कौनसी स्ट्रीम बंद करनी है? चुनें:**\n\n"
    markup = []
    
    for idx, p in enumerate(active_procs, 1):
        plat = p.get('platform', 'Unknown')
        start_time_str = p['start_time'].strftime('%I:%M %p')
        p_id = p.get('id', 'unknown')
        text += f"**{idx}.** 🟢 {plat} | शुरू हुई: `{start_time_str}`\n"
        markup.append([InlineKeyboardButton(f"🛑 Stop {plat} (Stream {idx})", callback_data=f"user_stop_{p_id}")])
        
    await message.reply(text, reply_markup=InlineKeyboardMarkup(markup))

@bot.on_callback_query(filters.regex("^admin_"))
async def admin_callbacks(client, callback_query: CallbackQuery):
    if callback_query.message.chat.id != ADMIN_ID:
        return
    data = callback_query.data
    global admin_state
    global recent_admin_messages

    if data == "admin_users":
        total_users = len(user_data)
        text = f"👥 **Total Users:** `{total_users}`\n\n"
        for uid, info in user_data.items():
            if uid == ADMIN_ID: continue
            text += f"👤 **Name:** {info['name']}\n🆔 **ID:** `{uid}`\n📅 **Joined:** {format_date(info['join_date'])}\n🕒 **Last Online:** {format_date(info['last_online'])}\n🎬 **Streams Done:** {info['total_streams']}\n⏳ **Last Stream:** {format_date(info['last_stream'])}\n"
            text += "➖➖➖➖➖➖➖➖\n"
        if len(text) > 4000:
            for x in range(0, len(text), 4000):
                await client.send_message(ADMIN_ID, text[x:x+4000])
        else:
            await callback_query.message.reply(text)

    elif data == "admin_live":
        live_text = ""
        total_live = 0
        for uid, info in user_data.items():
            active_streams =[]
            for p in info.get('processes', []):
                if isinstance(p, dict) and p['process'].poll() is None:
                    active_streams.append(p)
                elif not isinstance(p, dict) and p.poll() is None: # Old format safety
                    active_streams.append({'process': p, 'start_time': get_ist_time(), 'end_time': "Unknown", 'loop_hours': 0, 'is_image': False})

            if active_streams:
                total_live += len(active_streams)
                live_text += f"👤 **Name:** {info['name']} (ID: `{uid}`)\n🌐 **Platform:** `{info.get('platform', 'Unknown')}`\n"
                
                for i, strm in enumerate(active_streams, 1):
                    mode_str = f"{strm['loop_hours']}h Loop" if strm['loop_hours'] > 0 else "1 Time"
                    if strm.get('is_image'): mode_str += " (🖼 Image)"
                    else: mode_str += " (🎥 Video)"
                    
                    st_str = strm['start_time'].strftime("%I:%M %p")
                    et_str = strm['end_time'].strftime("%I:%M %p") if isinstance(strm['end_time'], datetime) else str(strm['end_time'])
                    
                    live_text += f"  ➤ **Stream {i}:** Mode: `{mode_str}`\n"
                    live_text += f"      🟢 Start: `{st_str}` | 🔴 End: `{et_str}`\n"
                live_text += "➖➖➖➖➖➖\n"
        
        if not live_text:
            await callback_query.message.reply("❌ **No one is streaming right now.**")
        else:
            await callback_query.message.reply(f"🔴 **Live Streams ({total_live} total):**\n\n" + live_text)

    elif data == "admin_pass":
        markup = InlineKeyboardMarkup([
            [InlineKeyboardButton("🔑 Change Password", callback_data="admin_pass_change")],[InlineKeyboardButton("📊 Pass Analysis", callback_data="admin_pass_analysis")]
        ])
        await callback_query.message.edit_text("🔐 **Password Management**\nChoose an option below:", reply_markup=markup)

    elif data == "admin_pass_change":
        admin_state = "AWAIT_NEW_PASSWORD"
        await callback_query.message.reply("🔑 **Please send the NEW PASSWORD and LIMIT.**\n`उदाहरण: 5550 5` (इसका मतलब सिर्फ 5 लोग पासवर्ड यूज़ कर पाएंगे)")

    elif data == "admin_pass_analysis":
        limit_text = str(PASSWORD_LIMIT) if PASSWORD_LIMIT != 999999 else "Unlimited"
        if not PASSWORD_USED_BY:
            await callback_query.message.reply(f"📊 **Pass Analysis:**\n🔑 **Current Password:** `{GLOBAL_PASSWORD}`\n👥 **Limit:** `0 / {limit_text}`\n\nअभी तक किसी ने भी मौजूदा पासवर्ड का इस्तेमाल नहीं किया है।")
        else:
            text = f"📊 **Pass Analysis:**\n🔑 **Current Password:** `{GLOBAL_PASSWORD}`\n👥 **Limit:** `{len(PASSWORD_USED_BY)} / {limit_text}`\n\n"
            for uid, uname in PASSWORD_USED_BY.items():
                text += f"👤 **Name:** {uname}\n🆔 **ID:** `{uid}`\n➖➖➖➖➖➖\n"
            await callback_query.message.reply(text)

    elif data == "admin_limit":
        admin_state = "AWAIT_LIMIT"
        await callback_query.message.reply("⚙️ **Set Stream Limit Mode:**\n\n👉 **सबका लिमिट बदलने के लिए:** सिर्फ नंबर भेजें (e.g. `2`)\n👉 **किसी एक यूज़र का लिमिट बदलने के लिए:** ID और नंबर भेजें\n`उदाहरण: 384884848 2`")

    elif data == "admin_msg":
        admin_state = "AWAIT_BROADCAST"
        await callback_query.message.reply("📢 **Broadcast / Personal Message Mode!**\n\n"
                                           "👉 **सबको भेजने के लिए:** कोई भी Text, Photo या Video सीधा भेजें।\n"
                                           "👉 **किसी एक को भेजने के लिए:** ID स्पेस मेसेज लिखें।\n"
                                           "`उदाहरण: 8383838487 Hello kese ho`")
    
    elif data == "admin_sch_times":
        update_schedule_dates()
        markup = []
        for st in GLOBAL_SCHEDULE_TIMES:
            markup.append([InlineKeyboardButton(f"❌ Delete {st}", callback_data=f"admindelscht_{st}")])
        markup.append([InlineKeyboardButton("➕ Add New Time", callback_data="admin_sch_add")])
        markup.append([InlineKeyboardButton("🔙 Back", callback_data="admin_back")])
        await callback_query.message.edit_text("📅 **Manage Pre-defined Schedule Times:**\nये समय यूज़र्स को बटन के रूप में दिखेंगे। (पुराने समय अगले दिन पर शिफ्ट हो जाएंगे 🔄)", reply_markup=InlineKeyboardMarkup(markup))

    elif data == "admin_back":
        await callback_query.message.edit_text("👑 **Welcome to Admin Panel**\nChoose an option below:", reply_markup=admin_keyboard())

    elif data == "admin_sch_add":
        admin_state = "AWAIT_SCH_TIME"
        await callback_query.message.reply("📅 **कृपया नया शेड्यूल्ड समय भेजें:**\n\n**Format:** `DD/MM/YYYY hh:mm AM/PM`\n**Example:** `24/06/2026 05:50 AM`")

    elif data.startswith("admindelscht_"):
        time_to_del = data.replace("admindelscht_", "")
        if time_to_del in GLOBAL_SCHEDULE_TIMES:
            GLOBAL_SCHEDULE_TIMES.remove(time_to_del)
            save_data()
        await admin_callbacks(client, callback_query._client.callback_query(id=callback_query.id, from_user=callback_query.from_user, message=callback_query.message, data="admin_sch_times"))

    elif data == "admin_del":
        if not recent_admin_messages:
            return await callback_query.message.reply("❌ **No recent messages/broadcasts found to delete.**")
            
        deleted_ops = 0
        total_msgs = 0
        
        for _ in range(5):
            if not recent_admin_messages:
                break
            targets = recent_admin_messages.pop()
            deleted_ops += 1
            for uid, mid in targets:
                try:
                    await client.delete_messages(uid, mid)
                    total_msgs += 1
                except: pass
                
        await callback_query.message.reply(f"✅ **Deleted last {deleted_ops} broadcast(s)/message(s) from {total_msgs} users' chats!**")


@bot.on_callback_query(filters.regex("^plat_"))
async def select_platform(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    init_user(user_id)
    
    if not user_data[user_id].get('authenticated'):
        return await callback_query.message.edit_text("🔐 **Session Expired! Please send /start and enter password.**")

    active_procs = [p for p in user_data[user_id].get('processes', []) if (p['process'].poll() if isinstance(p, dict) else p.poll()) is None]
    user_data[user_id]['processes'] = active_procs 
    limit = user_data[user_id].get('stream_limit', GLOBAL_LIMIT)
    
    if len(active_procs) >= limit:
        return await callback_query.message.edit_text(f"⚠️ **Limit Reached!**\nआप एक साथ सिर्फ {limit} स्ट्रीम चला सकते हैं। कृपया पहली स्ट्रीम खत्म होने का इंतज़ार करें।")

    data = callback_query.data
    if data == "plat_youtube":
        user_data[user_id]['platform'] = 'YouTube'
        text = "🔴 **YouTube Selected!**\n🔑 **Send YouTube Stream Key:**"
    elif data == "plat_rumble":
        user_data[user_id]['platform'] = 'Rumble'
        text = "🟢 **Rumble Selected!**\n🔑 **Send Rumble Stream Key (STATIC KEY):**"
    elif data == "plat_custom":
        user_data[user_id]['platform'] = 'Custom'
        text = "🔵 **Custom RTMP Selected!**\n🔗 **Send FULL RTMP URL + Key:**"
        
    user_data[user_id]['step'] = 'STREAM_KEY' if data != "plat_custom" else 'CUSTOM_URL'
    await callback_query.message.edit_text(text)

@bot.on_callback_query(filters.regex("^loop_"))
async def select_loop(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    init_user(user_id)
    
    if not user_data[user_id].get('authenticated'):
        return await callback_query.message.edit_text("🔐 **Session Expired! Please send /start and enter password.**")

    # Changed int() to float() to support 0.5 hours (30 Mins)
    hours = float(callback_query.data.split("_")[1])
    user_data[user_id]['loop_hours'] = hours
    user_data[user_id]['step'] = 'ORIENTATION'
    
    await callback_query.message.edit_text("📐 **Select Stream Orientation:**\nवीडियो कैसे चलाना है?", reply_markup=orientation_keyboard())

@bot.on_callback_query(filters.regex("^ori_"))
async def select_orientation(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    init_user(user_id)
    
    if not user_data[user_id].get('authenticated'):
        return await callback_query.message.edit_text("🔐 **Session Expired! Please send /start and enter password.**")

    data = callback_query.data
    if data == "ori_landscape":
        user_data[user_id]['orientation'] = 'landscape'
        user_data[user_id]['step'] = 'VIDEO_OR_URL'
        text = "🖥 **Landscape (16:9) Selected!**\n\n📥 **अब कोई Video File भेजें या डायरेक्ट Link (YouTube/Insta/FB) भेजें:**"
        await callback_query.message.edit_text(text)
    else:
        user_data[user_id]['orientation'] = 'portrait'
        user_data[user_id]['step'] = 'WAIT_IMAGE_CHOICE'
        text = "📱 **Portrait/Shorts (9:16) Selected!**\n\n🖼 **क्या आप वीडियो के ऊपर/नीचे खाली जगह पर कोई Custom Photo (Background) लगाना चाहते हैं?**"
        await callback_query.message.edit_text(text, reply_markup=image_choice_keyboard())

@bot.on_callback_query(filters.regex("^img_"))
async def select_image_choice(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    init_user(user_id)
    
    if not user_data[user_id].get('authenticated'):
        return await callback_query.message.edit_text("🔐 **Session Expired! Please send /start and enter password.**")

    data = callback_query.data
    if data == "img_yes":
        user_data[user_id]['step'] = 'AWAIT_IMAGE'
        text = "🖼 **Send your Custom Background Image (Photo)!**\n(यह फोटो आपके वीडियो के पीछे (Background) में दिखेगी)"
    else:
        user_data[user_id]['step'] = 'VIDEO_OR_URL'
        text = "⬛️ **No Image Selected (Black Background).**\n\n📥 **अब कोई Video File भेजें या डायरेक्ट Link (YouTube/Insta/FB) भेजें:**"

    await callback_query.message.edit_text(text)

@bot.on_callback_query(filters.regex("^aud_"))
async def select_audio_choice(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    data = callback_query.data
    if data == "aud_yes":
        user_data[user_id]['step'] = 'AWAIT_AUDIO'
        await callback_query.message.edit_text("🎵 **अपना Audio (MP3) फाइल भेजें जो पूरे वीडियो में चलेगा!**")
    elif data == "aud_intro":
        user_data[user_id]['step'] = 'AWAIT_INTRO_AUDIO'
        await callback_query.message.edit_text("🎵 **अपना Intro Audio (MP3) फाइल भेजें!**\n(यह वीडियो के शुरू में चलेगा, तब तक ओरिजिनल आवाज़ म्यूट रहेगी)")
    else:
        user_data[user_id]['step'] = 'SCHEDULE'
        await callback_query.message.edit_text("⏳ **स्ट्रीम अभी चालू करनी है या Schedule (शेड्यूल) करनी है?**", reply_markup=schedule_choice_keyboard())

@bot.on_callback_query(filters.regex("^wm_"))
async def select_watermark_choice(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    if callback_query.data == "wm_yes":
        user_data[user_id]['step'] = 'AWAIT_WATERMARK_TEXT'
        await callback_query.message.edit_text("✍️ **कृपया Watermark का Text भेजें:**\n(जैसे: Class PDF Telegram Pr Milengi)")
    else:
        user_data[user_id]['step'] = 'AUDIO_CHOICE'
        await callback_query.message.edit_text("🎵 **YouTube के लिए ऑडियो जरूरी है।**\nक्या आप अपना खुद का Audio (MP3) लगाना चाहते हैं?", reply_markup=audio_choice_keyboard())

@bot.on_callback_query(filters.regex("^vid_"))
async def video_step_choice(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    data = callback_query.data
    if data == "vid_add":
        user_data[user_id]['step'] = 'VIDEO_OR_URL'
        await callback_query.message.edit_text("📥 **अगला Video File या Archive.org Link भेजें:**\n(आप जितनी चाहें उतनी वीडियो/लिंक भेज सकते हैं)")
    elif data == "vid_done":
        user_data[user_id]['step'] = 'WATERMARK_CHOICE'
        if user_data[user_id].get('is_image_only'):
            await callback_query.message.edit_text("✨ **क्या आप फोटो पर चलता हुआ (Moving) नाम/वाटरमार्क लगाना चाहते हैं?**", reply_markup=watermark_choice_keyboard())
        else:
            await callback_query.message.edit_text("✨ **क्या आप वीडियो पर Watermark (जैसे 'Class PDF Telegram...') लगाना चाहते हैं?**\n(यह हर 1 मिनट में दिखाई देगा)", reply_markup=watermark_choice_keyboard())

@bot.on_callback_query(filters.regex("^sch_"))
async def select_schedule_choice(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    if callback_query.data == "sch_now":
        user_data[user_id]['step'] = 'READY'
        await callback_query.message.delete() 
        await process_stream_start(client, callback_query.message)
    else:
        user_data[user_id]['step'] = 'AWAIT_DATETIME'
        update_schedule_dates()
        markup = []
        for st in GLOBAL_SCHEDULE_TIMES:
            # Inline button format for specific times
            markup.append([InlineKeyboardButton(f"🗓 {st}", callback_data=f"set_schtime_{st}")])
        
        # बटन के बिना मैन्युअल एंट्री का निर्देश
        text = "📅 **Schedule Time चुनें या लिखें!**\n\n"
        if GLOBAL_SCHEDULE_TIMES:
            text += "👇 **एडमिन द्वारा दिए गए समय में से चुनें:**\n"
        text += "\n✍️ **या अपना खुद का समय लिखकर भेजें:**\n**Format:** `DD/MM/YYYY hh:mm AM/PM`\n**Example:** `24/06/2026 05:50 AM`"
        
        await callback_query.message.edit_text(text, reply_markup=InlineKeyboardMarkup(markup) if markup else None)

@bot.on_callback_query(filters.regex("^set_schtime_"))
async def select_predefined_time(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    time_str = callback_query.data.replace("set_schtime_", "")
    
    # Create fake message to pass to AWAIT_DATETIME logic
    class FakeMessage:
        def __init__(self, text, chat_id):
            self.text = text
            self.chat = type('Chat', (), {'id': chat_id})()
            self.id = callback_query.message.id
    
    await callback_query.message.edit_text(f"⏳ Processing schedule for {time_str}...")
    await handle_all_messages(client, FakeMessage(time_str, user_id))

@bot.on_message(filters.command("edit"))
async def edit_cmd(client, message):
    user_id = message.chat.id
    init_user(user_id, message)
    
    markup = []
    text = "🛠 **Manage Your Streams:**\nयहाँ से आप अपनी ग़लत बनी हुई या चल रही स्ट्रीम्स को Delete/Stop कर सकते हैं।\n\n"
    
    # Running streams
    active_procs = [p for p in user_data[user_id].get('processes', []) if p['process'].poll() is None]
    if active_procs:
        text += "🔴 **Running Streams:**\n"
        for idx, p in enumerate(active_procs, 1):
            p_id = p.get('id', 'unknown')
            plat = p.get('platform', 'Unknown')
            text += f"{idx}. 🟢 {plat} - Started: {p['start_time'].strftime('%I:%M %p')}\n"
            markup.append([InlineKeyboardButton(f"🛑 Stop Running: {plat} Stream {idx}", callback_data=f"user_stop_{p_id}")])
    
    # Scheduled streams
    scheduled = user_data[user_id].get('scheduled_tasks', {})
    if scheduled:
        text += "\n⏳ **Scheduled Streams:**\n"
        idx = 1
        for s_id, s_info in list(scheduled.items()):
            time_str = s_info['time_str']
            plat = s_info['config'].get('platform', 'Unknown')
            text += f"{idx}. 🗓 {plat} - Scheduled for: {time_str}\n"
            markup.append([InlineKeyboardButton(f"❌ Cancel Scheduled: {plat} {time_str}", callback_data=f"user_cancelsch_{s_id}")])
            idx += 1

    if not active_procs and not scheduled:
        text = "⚠️ **आपकी कोई भी स्ट्रीम अभी चल नहीं रही है और ना ही शेड्यूल है।**"

    await message.reply(text, reply_markup=InlineKeyboardMarkup(markup) if markup else None)

@bot.on_message(~filters.command(["start", "stop", "new", "admin", "edit"]))
async def handle_all_messages(client, message):
    user_id = message.chat.id
    init_user(user_id, message)
    step = user_data[user_id].get('step')

    # === Admin Reply to Delete ===
    if message.text == "/delete" and message.reply_to_message and user_id == ADMIN_ID:
        summary_id = message.reply_to_message.id
        if summary_id in sent_message_map:
            targets = sent_message_map[summary_id]
            deleted_count = 0
            for uid, mid in targets:
                try:
                    await client.delete_messages(uid, mid)
                    deleted_count += 1
                except: pass
            await message.reply(f"✅ **Message successfully deleted from {deleted_count} user(s) chat!**")
            del sent_message_map[summary_id] 
        else:
            await message.reply("❌ **Could not find message data. Already deleted or too old.**")
        return

    # === Admin State Handling ===
    if user_id == ADMIN_ID:
        global admin_state, GLOBAL_PASSWORD, GLOBAL_LIMIT, recent_admin_messages, PASSWORD_LIMIT, PASSWORD_USED_BY
        
        if admin_state == "AWAIT_NEW_PASSWORD" and message.text:
            parts = message.text.strip().split()
            GLOBAL_PASSWORD = parts[0]
            # अगर एडमिन ने स्पेस देकर नंबर लिखा है, तो उसे लिमिट सेट करें, नहीं तो अनलिमिटेड
            PASSWORD_LIMIT = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else 999999
            PASSWORD_USED_BY = {} # नया पासवर्ड आते ही पुरानी लिस्ट खाली कर दें
            admin_state = None
            
            limit_text = str(PASSWORD_LIMIT) if PASSWORD_LIMIT != 999999 else "Unlimited"
            await message.reply(f"✅ **Password Changed to:** `{GLOBAL_PASSWORD}`\n👥 **Max Users Allowed:** `{limit_text}`\n\nLogging everyone out...")
            for uid in user_data:
                if uid != ADMIN_ID:
                    user_data[uid]['authenticated'] = False
                    user_data[uid]['step'] = 'PASSWORD'
                    try:
                        await client.send_message(uid, "⚠️ **लॉगआउट अलर्ट! (Logout Alert)**\n\nएडमिन ने पासवर्ड बदल दिया है। कृपया `/start` दबाकर नया पासवर्ड डालें।")
                    except: pass
            save_data() # डेटाबेस अपडेट करें
            return

        elif admin_state == "AWAIT_LIMIT" and message.text:
            text = message.text.strip()
            parts = text.split()
            if len(parts) == 1 and parts[0].isdigit():
                GLOBAL_LIMIT = int(parts[0])
                for uid in user_data:
                    user_data[uid]['stream_limit'] = GLOBAL_LIMIT
                await message.reply(f"✅ **Global Stream Limit set to {GLOBAL_LIMIT} for everyone!**")
            elif len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
                target_id = int(parts[0])
                limit = int(parts[1])
                if target_id in user_data:
                    user_data[target_id]['stream_limit'] = limit
                    await message.reply(f"✅ **User `{target_id}` can now run {limit} streams at once!**")
                    try: await client.send_message(target_id, f"🎉 **Admin Alert:** Your concurrent stream limit has been increased to **{limit}**!")
                    except: pass
                else:
                    await message.reply("❌ **User not found in bot database!**")
            else:
                await message.reply("❌ **Invalid format!** Send something like `2` or `123456789 2`")
            admin_state = None
            save_data() # डेटाबेस अपडेट करें
            return

        elif admin_state == "AWAIT_BROADCAST":
            text_to_check = message.text or message.caption
            is_personal = False
            target_id = None
            content = None
            
            if text_to_check:
                parts = text_to_check.split(" ", 1)
                if len(parts) > 1 and parts[0].isdigit() and len(parts[0]) > 5:
                    is_personal = True
                    target_id = int(parts[0])
                    content = parts[1]
                    
            targets =[]
            
            if is_personal:
                try:
                    if message.text:
                        msg = await client.send_message(target_id, content)
                    else:
                        msg = await message.copy(target_id, caption=content)
                    targets.append((target_id, msg.id))
                    summary = await message.reply(f"✅ **Message sent privately to `{target_id}`!**\n_Reply to this message with `/delete` to remove it from their chat._")
                except Exception as e:
                    await message.reply(f"❌ **Failed to send.** Target might have blocked the bot.")
                    admin_state = None
                    return
            else:
                success = 0
                for uid in user_data:
                    if uid != ADMIN_ID:
                        try:
                            msg = await message.copy(uid)
                            targets.append((uid, msg.id))
                            success += 1
                        except: pass
                summary = await message.reply(f"✅ **Broadcast Sent successfully to {success} users!**\n_Reply to this message with `/delete` to remove it from all users._")
            
            if targets:
                sent_message_map[summary.id] = targets
                recent_admin_messages.append(targets)
                if len(recent_admin_messages) > 50:
                    recent_admin_messages.pop(0) 
            admin_state = None
            return

        elif admin_state == "AWAIT_SCH_TIME" and message.text:
            try:
                # Validation
                dt_obj = datetime.strptime(message.text.strip(), "%d/%m/%Y %I:%M %p")
                GLOBAL_SCHEDULE_TIMES.append(message.text.strip())
                save_data()
                await message.reply(f"✅ **Time Added Successfully!**\n`{message.text.strip()}`\n\nअब यह समय सभी यूज़र्स को बटन में दिखाई देगा।")
                admin_state = None
            except Exception as e:
                await message.reply("❌ **Invalid Format!**\nकृपया इस फॉर्मेट में भेजें: `24/06/2026 05:50 AM`")
            return

    # === Normal User Handling ===
    if not user_data[user_id]['authenticated'] and step != 'PASSWORD':
        user_data[user_id]['step'] = 'PASSWORD'
        return await message.reply("🔐 **Session Expired! Please enter password:**")

    # यहाँ हमने नए स्टेप्स (VIDEO_OR_URL, AWAIT_AUDIO और AWAIT_INTRO_AUDIO) को Add कर दिया है
    if not message.text and step not in['VIDEO_OR_URL', 'AWAIT_IMAGE', 'AWAIT_AUDIO', 'AWAIT_INTRO_AUDIO']:
        return

    if step == 'PASSWORD':
        if message.text == GLOBAL_PASSWORD:
            # चेक करें कि यूज़र पहले से लिस्ट में है या नहीं
            if user_id not in PASSWORD_USED_BY:
                if len(PASSWORD_USED_BY) >= PASSWORD_LIMIT:
                    return await message.reply("🚫 **Password Limit Reached!**\nयह पासवर्ड अपनी लिमिट पूरी कर चुका है। कृपया एडमिन से नया पासवर्ड लें।")
                # अगर लिमिट बची है, तो यूज़र को एनालिसिस लिस्ट में जोड़ दें
                PASSWORD_USED_BY[user_id] = user_data[user_id]['name']
                
            user_data[user_id]['authenticated'] = True
            user_data[user_id]['step'] = 'PLATFORM'
            save_data() # यूज़र लॉगिन सेव करें ताकि रीस्टार्ट होने पर लॉगिन न हटे
            await message.reply("**✅ Password Correct!**\n👇 **Select platform:**", reply_markup=platform_keyboard())
        else:
            await message.reply("❌ **Wrong Password! Try again.**")

    elif step == 'STREAM_KEY':
        key = message.text
        platform = user_data[user_id]['platform']
        if platform == 'YouTube':
            user_data[user_id]['rtmp_url'] = f"rtmp://a.rtmp.youtube.com/live2/{key}"
        elif platform == 'Rumble':
            user_data[user_id]['rtmp_url'] = f"rtmp://rtmp.rumble.com/live/{key}"
        user_data[user_id]['step'] = 'LOOP_CHOICE'
        await message.reply(f"✅ **Key Saved!**\n\n⏱ **How long do you want to stream?**", reply_markup=loop_keyboard())

    elif step == 'CUSTOM_URL':
        user_data[user_id]['rtmp_url'] = message.text
        user_data[user_id]['step'] = 'LOOP_CHOICE'
        await message.reply("✅ **Custom URL Saved!**\n\n⏱ **How long do you want to stream?**", reply_markup=loop_keyboard())
    
    elif step == 'AWAIT_IMAGE':
        if message.photo or message.document:
            msg = await message.reply("⏳ **Saving Image...**")
            image_path = await message.download()
            user_data[user_id]['custom_image_path'] = image_path
            user_data[user_id]['step'] = 'VIDEO_OR_URL'
            await msg.edit_text("✅ **Background Image Saved!**\n\n📥 **अब कोई Video File भेजें या डायरेक्ट Link (YouTube/Insta/FB) भेजें:**")
        else:
            await message.reply("⚠️ **Please send a valid Photo!**")

    elif step == 'VIDEO_OR_URL':
        user_data[user_id]['is_image_only'] = False
        
        # यूनीक नाम बनाना (ताकि दूसरी स्ट्रीम की वीडियो से मिक्स न हो)
        os.makedirs("downloads", exist_ok=True)  # <--- NEW: यह सुनिश्चित करेगा कि फोल्डर मौजूद है
        file_count = len(user_data[user_id].get('video_files', [])) + 1
        custom_filename = f"downloads/{user_id}_vid_{file_count}_{uuid.uuid4().hex[:6]}.mp4"
        
        if message.video or message.document:
            msg = await message.reply(f"⏳ **Downloading Video {file_count}...**")
            start_time = time.time()
            last_update = [start_time]
            file_path = await message.download(file_name=custom_filename, progress=progress_bar, progress_args=(msg, start_time, last_update))
            
            if 'video_files' not in user_data[user_id]: user_data[user_id]['video_files'] = []
            user_data[user_id]['video_files'].append(file_path)
            
            await msg.delete()
            await message.reply(f"✅ **Video {file_count} Saved!**\n\n🤔 **क्या आप और वीडियो जोड़ना चाहते हैं या Live चालू करें?**", reply_markup=more_video_keyboard())
            
        elif message.photo:
            msg = await message.reply("⏳ **Downloading Image...**")
            custom_img_name = f"downloads/{user_id}_img_{uuid.uuid4().hex[:6]}.jpg"
            file_path = await message.download(file_name=custom_img_name)
            user_data[user_id]['video_files'] = [file_path]
            user_data[user_id]['is_image_only'] = True
            await msg.delete()
            user_data[user_id]['step'] = 'WATERMARK_CHOICE'
            await message.reply("✨ **क्या आप फोटो पर चलता हुआ (Moving) नाम/वाटरमार्क लगाना चाहते हैं?**", reply_markup=watermark_choice_keyboard())
            
        elif message.text and "t.me/c/" in message.text:
            if not USER_SESSION:
                return await message.reply("❌ **String Session सेट नहीं है!**")
            msg = await message.reply(f"🔍 **प्राइवेट वीडियो ढूँढा जा रहा है...**")
            try:
                link_parts = message.text.strip().split('/')
                chat_id = int("-100" + link_parts[4])
                msg_id = int(link_parts[5])
                
                if not user_app.is_connected:
                    await user_app.start()
                
                target_msg = None
                messages = await user_app.get_messages(chat_id, range(max(1, msg_id - 10), msg_id + 11))
                for m in messages:
                    if m and not m.empty and (m.video or m.document):
                        target_msg = m
                        break
                        
                if not target_msg:
                    return await msg.edit_text("❌ **इस लिंक के आस-पास कोई Video नहीं मिला!**")
                    
                await msg.edit_text(f"⏳ **Private Video {file_count} Downloading...**")
                start_time = time.time()
                last_update = [start_time]
                file_path = await user_app.download_media(target_msg, file_name=custom_filename, progress=progress_bar, progress_args=(msg, start_time, last_update))
                
                if 'video_files' not in user_data[user_id]: user_data[user_id]['video_files'] = []
                user_data[user_id]['video_files'].append(file_path)
                
                await msg.delete()
                await message.reply(f"✅ **Private Video {file_count} Saved!**\n\n🤔 **क्या आप और वीडियो जोड़ना चाहते हैं या Live चालू करें?**", reply_markup=more_video_keyboard())
            except Exception as e:
                return await msg.edit_text(f"❌ **Error:** {str(e)}")
                
        elif message.text and ("http://" in message.text or "https://" in message.text):
            raw_text = message.text.strip()
            if "archive.org" in raw_text.lower():
                links = [w.strip() for w in raw_text.split() if ("http://" in w or "https://" in w)]
                if 'video_files' not in user_data[user_id]:
                    user_data[user_id]['video_files'] = []
                user_data[user_id]['video_url'] = None

                loop = asyncio.get_running_loop()
                saved_any = False

                for link in links:
                    file_count = len(user_data[user_id]['video_files']) + 1
                    out_prefix = f"downloads/{user_id}_vid_{file_count}_{uuid.uuid4().hex[:6]}"
                    msg = await message.reply(f"⏳ **Archive.org Video {file_count} Download शुरू हो रहा है...**")
                    try:
                        file_path = await asyncio.to_thread(download_archive_sync, link, out_prefix, loop, msg, file_count)
                        if file_path and os.path.exists(file_path) and os.path.getsize(file_path) > 1024:
                            user_data[user_id]['video_files'].append(file_path)
                            saved_any = True
                            await msg.delete()
                        else:
                            await msg.edit_text(f"❌ **Download Failed (Link {file_count}):** फाइल सेव नहीं हो पाई।")
                    except Exception as e:
                        for fname in os.listdir("downloads"):
                            if fname.startswith(os.path.basename(out_prefix)):
                                try: os.remove(os.path.join("downloads", fname))
                                except: pass
                        await msg.edit_text(f"❌ **Archive.org Download Error (Link {file_count}):** `{str(e)[:300]}`")

                if saved_any:
                    total_vids = len(user_data[user_id]['video_files'])
                    await message.reply(
                        f"✅ **Archive.org Video Saved! (Total Videos: {total_vids})**\n\n🤔 **क्या आप और वीडियो/लिंक जोड़ना चाहते हैं या Live चालू करें?**",
                        reply_markup=more_video_keyboard()
                    )
            else:
                user_data[user_id]['video_url'] = raw_text
                user_data[user_id]['step'] = 'WATERMARK_CHOICE'
                await message.reply("✨ **क्या आप वीडियो पर Watermark लगाना चाहते हैं?**", reply_markup=watermark_choice_keyboard())
        else:
            return await message.reply("⚠️ **कृपया सही Video, Photo या Link भेजें!**")

    elif step == 'AWAIT_WATERMARK_TEXT':
        user_data[user_id]['watermark_text'] = message.text.strip()
        user_data[user_id]['step'] = 'AUDIO_CHOICE'
        await message.reply(f"✅ **वाटरमार्क '{message.text.strip()}' सेव हो गया!**\n\n🎵 **YouTube के लिए ऑडियो जरूरी है।**\nक्या आप अपना खुद का Audio (MP3) फाइल लगाना चाहते हैं?", reply_markup=audio_choice_keyboard())

    elif step == 'AWAIT_AUDIO':
        if message.audio or message.video or message.document:
            msg = await message.reply("⏳ **Downloading Audio...**")
            audio_path = await message.download()
            user_data[user_id]['custom_audio_path'] = audio_path
            user_data[user_id]['step'] = 'SCHEDULE'
            await msg.edit_text("✅ **Full Audio Saved!**\n\n⏳ **स्ट्रीम अभी चालू करनी है या Schedule (शेड्यूल) करनी है?**", reply_markup=schedule_choice_keyboard())
        else:
            await message.reply("⚠️ **कृपया सही Audio File भेजें!**")

    elif step == 'AWAIT_INTRO_AUDIO':
        if message.audio or message.video or message.document:
            msg = await message.reply("⏳ **Downloading Intro Audio...**")
            intro_path = await message.download()
            user_data[user_id]['intro_audio_path'] = intro_path
            user_data[user_id]['step'] = 'SCHEDULE'
            await msg.edit_text("✅ **Intro Audio Saved!**\n\n⏳ **स्ट्रीम अभी चालू करनी है या Schedule (शेड्यूल) करनी है?**", reply_markup=schedule_choice_keyboard())
        else:
            await message.reply("⚠️ **कृपया सही Audio File भेजें!**")

    elif step == 'AWAIT_DATETIME':
        try:
            time_str = message.text.strip()
            dt_obj = datetime.strptime(time_str, "%d/%m/%Y %I:%M %p")
            now_ist = get_ist_time().replace(tzinfo=None)
            if dt_obj <= now_ist:
                # If pre-defined time is passed, allow it logically but warn if past
                try: 
                    await client.send_message(user_id, "⚠️ **समय (Time) भविष्य का होना चाहिए!** कृपया आगे का समय भेजें।")
                except:
                    await message.reply("⚠️ **समय (Time) भविष्य का होना चाहिए!** कृपया आगे का समय भेजें।")
                return
            
            user_data[user_id]['step'] = 'READY'
            delay = (dt_obj - now_ist).total_seconds()
            
            # --- Snapshot Configuration ---
            # (अगर यूज़र दूसरी स्ट्रीम बनायेगा तो पहली स्ट्रीम का डेटा डिलीट न हो)
            stream_config = {
                'video_files': user_data[user_id].get('video_files', []),
                'video_url': user_data[user_id].get('video_url'),
                'custom_audio_path': user_data[user_id].get('custom_audio_path'),
                'intro_audio_path': user_data[user_id].get('intro_audio_path'),
                'platform': user_data[user_id].get('platform', 'Custom'),
                'loop_hours': user_data[user_id].get('loop_hours', 0),
                'rtmp_url': user_data[user_id].get('rtmp_url'),
                'orientation': user_data[user_id].get('orientation', 'landscape'),
                'custom_image_path': user_data[user_id].get('custom_image_path'),
                'is_image_only': user_data[user_id].get('is_image_only', False),
                'watermark_text': user_data[user_id].get('watermark_text')
            }
            
            s_id = str(uuid.uuid4())[:8]
            task = asyncio.create_task(scheduled_stream_starter(client, message, delay, stream_config, s_id))
            
            user_data[user_id]['scheduled_tasks'][s_id] = {
                'task': task,
                'time_str': time_str,
                'config': stream_config
            }
            
            try:
                await client.send_message(user_id, f"✅ **Stream Scheduled!**\nयह वीडियो आटोमेटिकली `{time_str}` पर चालू हो जाएगा।\nअगर कोई गलती हुई हो तो `/edit` टाइप करें।")
            except:
                await message.reply(f"✅ **Stream Scheduled!**\nयह वीडियो आटोमेटिकली `{time_str}` पर चालू हो जाएगा।\nअगर कोई गलती हुई हो तो `/edit` टाइप करें।")
            
        except Exception as e:
            try:
                await client.send_message(user_id, "❌ **Invalid Format!**\nकृपया इस फॉर्मेट में भेजें: `24/06/2026 05:50 AM`")
            except:
                await message.reply("❌ **Invalid Format!**\nकृपया इस फॉर्मेट में भेजें: `24/06/2026 05:50 AM`")

@bot.on_callback_query(filters.regex("^user_cancelsch_"))
async def cancel_sch_callback(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    s_id = callback_query.data.replace("user_cancelsch_", "")
    if s_id in user_data[user_id].get('scheduled_tasks', {}):
        user_data[user_id]['scheduled_tasks'][s_id]['task'].cancel()
        del user_data[user_id]['scheduled_tasks'][s_id]
        await callback_query.message.edit_text("✅ **Scheduled Stream Cancelled / Delete हो गई!**\nअब आप `/new` से नई बना सकते हैं।")
    else:
        await callback_query.message.edit_text("❌ **यह शेड्यूल पहले ही कैंसिल हो चुका है या चल चुका है।**")

@bot.on_callback_query(filters.regex("^user_stop_"))
async def stop_running_callback(client, callback_query: CallbackQuery):
    user_id = callback_query.message.chat.id
    p_id = callback_query.data.replace("user_stop_", "")
    
    stopped = False
    for p in user_data[user_id].get('processes', []):
        if p.get('id') == p_id and p['process'].poll() is None:
            user_data[user_id]['manual_stop'] = True
            p['process'].terminate()
            stopped = True
            break
            
    if stopped:
        await callback_query.message.edit_text("✅ **Running Stream को सफलतापूर्वक बंद कर दिया गया है!**")
    else:
        await callback_query.message.edit_text("❌ **यह स्ट्रीम पहले ही बंद हो चुकी है।**")

async def scheduled_stream_starter(client, message, delay, stream_config, s_id):
    try:
        await asyncio.sleep(delay)
        user_id = message.chat.id
        # Remove from pending queue as it starts
        if s_id in user_data[user_id].get('scheduled_tasks', {}):
            del user_data[user_id]['scheduled_tasks'][s_id]
        await handle_video(client, message, stream_config)
    except asyncio.CancelledError:
        pass # Stream was cancelled by user

async def process_stream_start(client, message):
    await handle_video(client, message)

def download_archive_sync(url, out_prefix, loop, msg, file_count):
    last_update = [time.time()]

    async def safe_edit(text):
        try:
            await msg.edit_text(text)
        except Exception:
            pass

    def progress_hook(d):
        if d.get('status') == 'downloading':
            now = time.time()
            if now - last_update[0] > 4:
                last_update[0] = now
                downloaded = d.get('downloaded_bytes', 0)
                total = d.get('total_bytes') or d.get('total_bytes_estimate') or 0
                speed = d.get('speed') or 0
                eta = d.get('eta') or 0

                dl_mb = round(downloaded / (1024 * 1024), 2)
                speed_mb = round(speed / (1024 * 1024), 2) if speed else 0

                if total > 0:
                    pct = min(100.0, downloaded * 100 / total)
                    total_mb = round(total / (1024 * 1024), 2)
                    filled = math.floor(pct / 5)
                    bar = "█" * filled + "░" * (20 - filled)
                    eta_str = f"{int(eta)} sec" if eta < 60 else f"{int(eta)//60} min {int(eta)%60} sec"
                    text = (
                        f"📥 **Downloading Archive.org Video {file_count}...**\n\n"
                        f"[{bar}] **{round(pct, 2)}%**\n"
                        f"📦 **Size:** `{dl_mb} MB / {total_mb} MB`\n"
                        f"🚀 **Speed:** `{speed_mb} MB/s`\n"
                        f"⏳ **ETA:** `{eta_str}`"
                    )
                else:
                    text = (
                        f"📥 **Downloading Archive.org Video {file_count}...**\n\n"
                        f"📦 **Downloaded:** `{dl_mb} MB`\n"
                        f"🚀 **Speed:** `{speed_mb} MB/s`"
                    )
                asyncio.run_coroutine_threadsafe(safe_edit(text), loop)
        elif d.get('status') == 'finished':
            asyncio.run_coroutine_threadsafe(
                safe_edit(f"⏳ **Processing Archive.org Video {file_count}...**"), loop
            )

    ydl_opts = {
        'format': 'best[ext=mp4]/bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio/best',
        'outtmpl': f"{out_prefix}.%(ext)s",
        'merge_output_format': 'mp4',
        'noplaylist': True,
        'playlist_items': '1',
        'retries': 10,
        'fragment_retries': 10,
        'quiet': True,
        'no_warnings': True,
        'progress_hooks': [progress_hook],
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=True)
        if info and 'entries' in info and info['entries']:
            entry = next((e for e in info['entries'] if e), None)
        else:
            entry = info

        if entry:
            req_dl = entry.get('requested_downloads')
            if req_dl and isinstance(req_dl, list) and req_dl[0].get('filepath'):
                fp = req_dl[0]['filepath']
                if os.path.exists(fp):
                    return fp
            prep = ydl.prepare_filename(entry)
            if os.path.exists(prep):
                return prep
            mp4_prep = os.path.splitext(prep)[0] + ".mp4"
            if os.path.exists(mp4_prep):
                return mp4_prep

    dl_dir = os.path.dirname(out_prefix) or "."
    base_name = os.path.basename(out_prefix)
    for fname in os.listdir(dl_dir):
        if fname.startswith(base_name) and not fname.endswith(('.part', '.ytdl', '.temp')):
            full_path = os.path.join(dl_dir, fname)
            if os.path.exists(full_path) and os.path.getsize(full_path) > 1024:
                return full_path
    return None

def get_direct_url(url):
    ydl_opts = {'format': 'best', 'quiet': True, 'noplaylist': True}
    try:
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(url, download=False)
            return info.get('url', url)
    except:
        return url

async def handle_video(client, message, stream_config=None):
    user_id = message.chat.id
    config = stream_config if stream_config else user_data[user_id]
    
    user_data[user_id]['manual_stop'] = False
    try:
        msg = await client.send_message(user_id, "⏳ **Preparing Stream Environment...**")
    except:
        msg = await message.reply("⏳ **Preparing Stream Environment...**")
    
    video_files = config.get('video_files', [])
    video_url = config.get('video_url')
    custom_audio = config.get('custom_audio_path')
    intro_audio = config.get('intro_audio_path')
    
    valid_files = []
    concat_file = None
    input_source = None

    if video_url:
        await msg.edit_text("🔗 **Extracting direct stream link...**")
        input_source = await asyncio.to_thread(get_direct_url, video_url)
        if not input_source:
            return await msg.edit_text("❌ **Failed to extract link!**")
    elif video_files:
        valid_files = [vf for vf in video_files if os.path.exists(vf) and os.path.getsize(vf) > 1024]
        if not valid_files:
            return await msg.edit_text("❌ **Error:** Video files not found or corrupted! कृपया /new दबाकर दोबारा वीडियो भेजें।")
        if len(valid_files) == 1:
            input_source = valid_files[0]
            
    platform = config.get('platform', 'Custom')
    loop_hours = config.get('loop_hours', 0)
    rtmp_url = config.get('rtmp_url')
    orientation = config.get('orientation', 'landscape')
    image_path = config.get('custom_image_path')
    wm_text = config.get('watermark_text')
    is_image_only = config.get('is_image_only', False)
    
    user_data[user_id]['total_streams'] += 1
    user_data[user_id]['last_stream'] = get_ist_time()
    
    import random
    vid_duration = sum(get_video_duration(f) for f in valid_files) if valid_files else 3600
    if vid_duration <= 0:
        vid_duration = 3600
    
    # ANTI-BOT RANDOMIZER
    if loop_hours > 0:
        base_sec = loop_hours * 3600
        random_offset = random.randint(int(-0.1 * base_sec), int(0.1 * base_sec))
        actual_stream_seconds = max(60, base_sec + random_offset)
        total_stream_time = actual_stream_seconds
    else:
        total_stream_time = vid_duration
        actual_stream_seconds = vid_duration

    timing_logic = "between(t\\,60\\,75)+between(t\\,180\\,195)+(gte(t\\,480)*lt(mod(t-480\\,300)\\,15))"
    safe_text = wm_text.replace("'", "\\'").replace(":", "\\:") if wm_text else ""

    # --- FFMPEG Command Setup ---
    command = ["ffmpeg"]
    
    if is_image_only:
        command.extend(["-re", "-loop", "1", "-framerate", "30", "-i", input_source])
        if custom_audio:
            command.extend(["-stream_loop", "-1", "-i", custom_audio])
            command.extend(["-map", "0:v", "-map", "1:a:0?"])
        else:
            command.extend(["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100"])
            command.extend(["-map", "0:v", "-map", "1:a"])

        if orientation == 'portrait':
            vf_filter = "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:color=black"
        else:
            vf_filter = "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2:color=black"
        
        if wm_text:
            vf_filter += f",drawtext=text='{safe_text}':fontcolor=white@0.4:fontsize=40:x=(w-tw)/2+((w-tw)/2.5)*sin(t/10):y=(h-th)/2+((h-th)/2.5)*cos(t/15)"

        command.extend(["-vf", vf_filter])
        command.extend(["-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p"])
        command.extend(["-r", "30", "-g", "60", "-sc_threshold", "0"])
        command.extend(["-b:v", "3000k", "-maxrate", "3000k", "-minrate", "3000k", "-bufsize", "6000k", "-nal-hrd", "cbr"])
        command.extend(["-c:a", "aac", "-b:a", "128k", "-ar", "44100", "-ac", "2"])

    elif len(valid_files) > 1:
        # MULTI-VIDEO PLAYLIST: Normalized Concat Filter (480p/720p/1080p सब एक साथ बिना क्रैश के चलेंगे)
        playlist_files = list(valid_files)
        if loop_hours > 0 and vid_duration < actual_stream_seconds:
            repeats = min(20, math.ceil(actual_stream_seconds / vid_duration))
            playlist_files = valid_files * repeats
            total_stream_time = actual_stream_seconds

        # हर अलग फाइल का ऑडियो/ड्यूरेशन पहले ही जांच लें
        file_meta = {}
        for vf in valid_files:
            file_meta[vf] = {
                "has_audio": has_audio_stream(vf),
                "dur": max(1.0, get_video_duration(vf))
            }

        for vf in playlist_files:
            command.extend(["-i", vf])

        current_idx = len(playlist_files)
        idx_img = -1
        if orientation == 'portrait' and image_path and os.path.exists(image_path):
            command.extend(["-loop", "1", "-i", image_path])
            idx_img = current_idx
            current_idx += 1

        idx_aud = -1
        idx_intro = -1
        if custom_audio and os.path.exists(custom_audio):
            command.extend(["-stream_loop", "-1", "-i", custom_audio])
            idx_aud = current_idx
            current_idx += 1
        elif intro_audio and os.path.exists(intro_audio):
            command.extend(["-i", intro_audio])
            idx_intro = current_idx
            current_idx += 1

        # सभी वीडियो को एक बराबर Resolution (720p), 30fps, और 44100Hz Stereo में बदलें
        if orientation == 'portrait':
            seg_w, seg_h = (720, 406) if idx_img != -1 else (720, 1280)
        else:
            seg_w, seg_h = (1280, 720)

        fc_parts = []
        concat_labels = []
        for i, vf in enumerate(playlist_files):
            fc_parts.append(
                f"[{i}:v]scale={seg_w}:{seg_h}:force_original_aspect_ratio=decrease,"
                f"pad={seg_w}:{seg_h}:(ow-iw)/2:(oh-ih)/2:color=black,fps=30,format=yuv420p,setsar=1,setpts=PTS-STARTPTS[v{i}]"
            )
            if file_meta[vf]["has_audio"]:
                fc_parts.append(
                    f"[{i}:a]aresample=44100:async=1,aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,asetpts=PTS-STARTPTS[a{i}]"
                )
            else:
                dur_val = file_meta[vf]["dur"]
                fc_parts.append(f"anullsrc=channel_layout=stereo:sample_rate=44100:duration={dur_val:.2f}[a{i}]")
            concat_labels.append(f"[v{i}][a{i}]")

        n_segs = len(playlist_files)
        fc_parts.append(f"{''.join(concat_labels)}concat=n={n_segs}:v=1:a=1[cat_v][cat_a]")
        fc_parts.append("[cat_v]realtime=limit=5[rt_v]")
        fc_parts.append("[cat_a]arealtime=limit=5[rt_a]")
        v_label = "rt_v"

        if idx_img != -1:
            fc_parts.append(
                f"[{idx_img}:v]scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,setsar=1[bg]; "
                f"[bg][{v_label}]overlay=(W-w)/2:(H-h)/2[ov_v]"
            )
            v_label = "ov_v"

        if wm_text:
            fc_parts.append(
                f"[{v_label}]drawtext=text=' Telegram\\: {safe_text} ':fontcolor=white:fontsize=30:"
                f"box=1:boxcolor=#2AABEE@0.9:boxborderw=12:x=30:y=h-th-30:enable='{timing_logic}'[out_v]"
            )
            v_label = "out_v"

        if idx_aud != -1:
            command.extend(["-filter_complex", "; ".join(fc_parts), "-map", f"[{v_label}]", "-map", f"{idx_aud}:a:0?"])
            command.extend(["-shortest"])
        elif idx_intro != -1:
            intro_dur = get_video_duration(intro_audio)
            if intro_dur <= 0:
                intro_dur = 20
            fc_parts.append(
                f"[rt_a]volume=0:enable='between(t,0,{intro_dur})'[main_a]; "
                f"[{idx_intro}:a]aresample=44100,aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad[intro_a]; "
                f"[main_a][intro_a]amix=inputs=2:duration=first[mix_a]; [mix_a]volume=2[out_a]"
            )
            command.extend(["-filter_complex", "; ".join(fc_parts), "-map", f"[{v_label}]", "-map", "[out_a]"])
        else:
            command.extend(["-filter_complex", "; ".join(fc_parts), "-map", f"[{v_label}]", "-map", "[rt_a]"])

        command.extend(["-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p"])
        command.extend(["-r", "30", "-g", "60", "-sc_threshold", "0"])
        command.extend(["-b:v", "3000k", "-maxrate", "3000k", "-minrate", "3000k", "-bufsize", "6000k", "-nal-hrd", "cbr"])
        command.extend(["-c:a", "aac", "-b:a", "128k", "-ar", "44100", "-ac", "2"])

    else:
        # Single Video or Direct URL Logic
        command.append("-re")
        if loop_hours > 0:
            command.extend(["-stream_loop", "-1"])
        command.extend(["-fflags", "+genpts", "-i", input_source])

        single_has_audio = True if video_url else has_audio_stream(input_source)
        current_idx = 1
        idx_aud = -1
        idx_intro = -1
        idx_img = -1
        idx_null_a = -1

        if not single_has_audio and not custom_audio and not intro_audio:
            command.extend(["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100"])
            idx_null_a = current_idx
            current_idx += 1

        if custom_audio and os.path.exists(custom_audio):
            command.extend(["-stream_loop", "-1", "-i", custom_audio])
            idx_aud = current_idx
            current_idx += 1
        elif intro_audio and os.path.exists(intro_audio):
            command.extend(["-i", intro_audio])
            idx_intro = current_idx
            current_idx += 1

        if orientation == 'portrait' and image_path and os.path.exists(image_path):
            command.extend(["-loop", "1", "-i", image_path])
            idx_img = current_idx
            current_idx += 1

        if orientation == 'portrait':
            if idx_img != -1:
                v_chain = (
                    f"[{idx_img}:v]scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,setsar=1[bg]; "
                    f"[0:v]scale=720:406:force_original_aspect_ratio=decrease,pad=720:406:(ow-iw)/2:(oh-ih)/2:color=black,fps=30,format=yuv420p[fg]; "
                    f"[bg][fg]overlay=(W-w)/2:(H-h)/2"
                )
            else:
                v_chain = "[0:v]scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:color=black,fps=30,format=yuv420p"
        else:
            v_chain = "[0:v]scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2:color=black,fps=30,format=yuv420p"

        if wm_text:
            v_chain += f",drawtext=text=' Telegram\\: {safe_text} ':fontcolor=white:fontsize=30:box=1:boxcolor=#2AABEE@0.9:boxborderw=12:x=30:y=h-th-30:enable='{timing_logic}'"

        if idx_intro != -1:
            intro_dur = get_video_duration(intro_audio)
            if intro_dur <= 0:
                intro_dur = 20
            if single_has_audio:
                fc = (
                    f"{v_chain}[out_v]; "
                    f"[0:a]aresample=44100,aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,volume=0:enable='between(t,0,{intro_dur})'[main_a]; "
                    f"[{idx_intro}:a]aresample=44100,aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad[intro_a]; "
                    f"[main_a][intro_a]amix=inputs=2:duration=first[mix_a]; [mix_a]volume=2[out_a]"
                )
            else:
                fc = (
                    f"{v_chain}[out_v]; "
                    f"[{idx_intro}:a]aresample=44100,aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad[out_a]"
                )
            command.extend(["-filter_complex", fc, "-map", "[out_v]", "-map", "[out_a]"])
        else:
            command.extend(["-filter_complex", f"{v_chain}[out_v]", "-map", "[out_v]"])
            if idx_aud != -1:
                command.extend(["-map", f"{idx_aud}:a:0?", "-shortest"])
            elif idx_null_a != -1:
                command.extend(["-map", f"{idx_null_a}:a", "-shortest"])
            else:
                command.extend(["-map", "0:a?"])

        command.extend(["-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p"])
        command.extend(["-r", "30", "-g", "60", "-sc_threshold", "0"])
        command.extend(["-b:v", "3000k", "-maxrate", "3000k", "-minrate", "3000k", "-bufsize", "6000k", "-nal-hrd", "cbr"])
        command.extend(["-c:a", "aac", "-b:a", "128k", "-ar", "44100", "-ac", "2"])

    if loop_hours > 0:
        command.extend(["-t", str(int(actual_stream_seconds))])

    # Max muxing queue + RTMP 15-sec I/O Timeout ताकि कनेक्शन टूटने पर FFmpeg हैंग न हो
    command.extend(["-max_muxing_queue_size", "1024", "-rw_timeout", "15000000", "-f", "flv", rtmp_url])
    
    st_type = "🖼 Image" if is_image_only else "🎥 Video"
    live_msg = await msg.edit_text(f"🟢 **Live Started on {platform}!**\n📋 **Type:** `{st_type}`\n📐 **Mode:** `{orientation.capitalize()}`\n⏳ **Time Left:** `Calculating...`\n\n🔹 To stop, send /stop")
    
    log_file = f"ffmpeg_{user_id}_{uuid.uuid4().hex[:6]}.log"
    log_fp = open(log_file, "w", encoding="utf-8", errors="ignore")
    process_obj = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=log_fp)
    
    start_t = get_ist_time()
    end_t = start_t + timedelta(seconds=actual_stream_seconds) if loop_hours > 0 else "Auto (Depends on Video)"
    
    unique_p_id = str(uuid.uuid4())[:8]
    user_data[user_id]['processes'].append({
        'id': unique_p_id,
        'process': process_obj,
        'start_time': start_t,
        'end_time': end_t,
        'loop_hours': loop_hours,
        'is_image': is_image_only,
        'platform': platform
    })
    
    asyncio.create_task(monitor_stream(client, message.chat.id, process_obj, valid_files, concat_file, live_msg.id, loop_hours, platform, total_stream_time, image_path, custom_audio, intro_audio, log_file, log_fp))

async def monitor_stream(client, chat_id, process, video_files, concat_file, msg_id, loop_hours, platform, total_time, image_path, custom_audio, intro_audio=None, log_file=None, log_fp=None):
    start_time_ist = get_ist_time()
    last_ui_update = time.time()
    finishing_notified = False
    mode_text = f"🔁 {loop_hours} Hours Loop" if loop_hours > 0 else "▶️ 1-Time Play"
    
    while process.poll() is None:
        await asyncio.sleep(5)
        now_time = time.time()
        elapsed = (get_ist_time() - start_time_ist).total_seconds()

        # Watchdog: यदि स्ट्रीम तय समय से 10 मिनट ज्यादा अटक जाए तो फोर्स-स्टॉप करें
        if total_time > 0 and elapsed > (total_time + 600):
            try:
                process.terminate()
                await asyncio.sleep(5)
                if process.poll() is None:
                    process.kill()
            except: pass
            break

        if total_time > 0 and (now_time - last_ui_update > 60):
            last_ui_update = now_time
            rem_sec = total_time - elapsed
            
            if rem_sec > 60:
                h = int(rem_sec // 3600)
                m = int((rem_sec % 3600) // 60)
                time_left_str = f"{h}h {m}m" if h > 0 else f"{m}m"
                try:
                    await client.edit_message_text(
                        chat_id, msg_id,
                        f"🟢 **Live is RUNNING on {platform}!**\n"
                        f"⏱ **Loop:** `{mode_text}`\n"
                        f"⏳ **Time Left:** `{time_left_str}`\n\n"
                        f"🔹 Send /stop to end manually."
                    )
                except: pass
            elif not finishing_notified:
                finishing_notified = True
                try:
                    await client.edit_message_text(
                        chat_id, msg_id,
                        f"🟢 **Live is RUNNING on {platform}!**\n"
                        f"⏱ **Loop:** `{mode_text}`\n"
                        f"⏳ **Time Left:** `Finishing soon...`\n\n"
                        f"🔹 Send /stop to end manually."
                    )
                except: pass

    end_time_ist = get_ist_time()
    duration = end_time_ist - start_time_ist
    ret_code = process.returncode

    if log_fp:
        try: log_fp.close()
        except: pass

    error_tail = ""
    if ret_code not in (0, None) and log_file and os.path.exists(log_file):
        try:
            with open(log_file, "r", encoding="utf-8", errors="ignore") as f:
                lines = [ln.strip() for ln in f.readlines() if ln.strip()]
                if lines:
                    error_tail = "\n⚠️ **FFmpeg Log:** `" + " | ".join(lines[-2:])[-300:] + "`"
        except: pass

    try: await client.delete_messages(chat_id, msg_id)
    except: pass

    # Server Storage साफ़ करना
    try:
        for vf in video_files:
            if os.path.exists(vf): os.remove(vf)
        if concat_file and os.path.exists(concat_file): os.remove(concat_file)
        if image_path and os.path.exists(image_path): os.remove(image_path)
        if custom_audio and os.path.exists(custom_audio): os.remove(custom_audio)
        if intro_audio and os.path.exists(intro_audio): os.remove(intro_audio)
        if log_file and os.path.exists(log_file): os.remove(log_file)
        
        if chat_id in user_data:
            user_data[chat_id]['video_files'] = []
            user_data[chat_id]['file_path'] = None
    except: pass
    
    start_str = start_time_ist.strftime("%I:%M %p")
    end_str = end_time_ist.strftime("%I:%M %p")
    dur_str = str(duration).split('.')[0]
    
    is_manual = user_data.get(chat_id, {}).get('manual_stop', False)
    if is_manual:
        status_text = "🛑 **Live Stream Stopped Manually!**"
    elif ret_code not in (0, None):
        status_text = "⚠️ **Live Stream Stopped (Connection/Video Error)!**"
    else:
        status_text = "🔴 **Live Stream Ended Automatically!**"
    
    report_msg = (
        f"{status_text}\n\n"
        f"📊 **STREAM SUMMARY:**\n"
        f"🔸 **Platform:** `{platform}`\n"
        f"🟢 **Started at:** `{start_str}`\n"
        f"🔴 **Ended at:** `{end_str}`\n"
        f"⏱ **Total Runtime:** `{dur_str}`"
        f"{error_tail}\n\n"
        f"🗑 __Video, Audio & Image deleted safely.__"
    )
    
    await client.send_message(chat_id, report_msg)

if __name__ == "__main__":
    load_data() # बॉट स्टार्ट होते ही पुरानी सेटिंग्स और यूज़र्स वापस लोड करें
    Thread(target=run_flask).start() 
    bot.run()