File size: 69,297 Bytes
3788c3d
656dd4f
eb9c86f
 
b261f06
0f49bc6
eb9c86f
 
 
0f49bc6
 
f3e2734
 
df4c148
eb9c86f
 
 
8364b28
eb9c86f
953ae01
eb9c86f
 
 
 
 
 
 
 
 
 
 
5011bdb
eb9c86f
 
 
31b133a
 
eb9c86f
 
 
 
 
 
 
 
63fa54a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9c86f
 
 
 
 
 
 
 
 
 
 
3527e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9c86f
 
 
 
 
188975b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9c86f
 
 
 
 
 
 
 
188975b
953ae01
 
 
 
 
 
 
eb9c86f
 
 
188975b
 
8c2de5d
188975b
 
 
 
eb9c86f
 
188975b
 
 
ee247af
188975b
 
 
 
 
eb9c86f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3788c3d
eb9c86f
 
 
 
 
 
 
 
 
 
 
 
6ffec42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9c86f
 
 
 
 
 
 
 
 
 
 
 
 
73ee396
 
 
eb9c86f
 
 
 
 
 
3788c3d
 
 
eb9c86f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193a59e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9c86f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193a59e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9c86f
193a59e
 
eb9c86f
193a59e
 
 
 
 
 
 
eb9c86f
193a59e
 
 
eb9c86f
 
 
193a59e
 
 
 
 
 
 
 
 
 
 
eb9c86f
 
193a59e
 
 
 
 
 
 
eb9c86f
 
193a59e
 
 
 
 
 
 
 
eb9c86f
09938c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ffec42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9c86f
 
 
 
 
 
 
63fa54a
 
eb9c86f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73ee396
eb9c86f
 
 
73ee396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9c86f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63fa54a
eb9c86f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0b0ae3
0f49bc6
a0b0ae3
 
3527e92
 
 
 
 
a0b0ae3
 
 
 
 
 
3527e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0b0ae3
0acb762
 
 
 
 
 
 
 
c938f1b
0acb762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c938f1b
 
0acb762
 
 
 
c938f1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0acb762
c938f1b
a0b0ae3
 
fc9f58a
 
 
 
 
 
 
 
 
 
 
a0b0ae3
2ba574c
a0b0ae3
fc9f58a
 
 
 
03eeb0a
fc9f58a
03eeb0a
 
 
fc9f58a
03eeb0a
fc9f58a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03eeb0a
 
 
 
fc9f58a
03eeb0a
0f49bc6
b9ab76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13d2ea1
b9ab76d
 
 
 
 
13d2ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f49bc6
 
 
 
 
 
 
31b133a
0f49bc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31b133a
0f49bc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31b133a
0f49bc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e7930
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f1917
f0e7930
 
 
 
 
 
 
 
 
 
 
85f1917
 
f0e7930
 
 
85f1917
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e7930
85f1917
f0e7930
a197203
33608fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a197203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e181de5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af0c36d
 
 
 
 
 
 
 
19982ea
af0c36d
 
 
 
 
 
 
 
 
 
 
 
 
 
5466eea
 
 
 
6462954
5466eea
 
 
e68fb76
 
 
 
 
6e08b51
6462954
 
 
0ecabec
6e08b51
 
 
 
0320b05
5466eea
 
 
 
 
 
 
 
 
6462954
 
 
 
 
6e08b51
 
 
e68fb76
 
 
5466eea
 
 
 
 
0320b05
 
 
 
5466eea
 
 
8089e96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5466eea
 
 
 
 
 
 
 
 
 
 
 
4e17a7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5466eea
4e17a7b
5466eea
 
 
 
4e17a7b
 
5466eea
 
4e17a7b
 
 
5466eea
 
56209e3
0ecabec
5466eea
0e8d333
e68fb76
6e08b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0320b05
5466eea
a5949ae
 
6462954
6e08b51
 
5466eea
 
e68fb76
0e8d333
 
 
e68fb76
56209e3
 
 
0320b05
56209e3
 
 
 
0320b05
 
0ecabec
5466eea
 
73e1788
5466eea
742d105
 
 
 
 
 
 
 
 
 
 
 
9a68274
 
5466eea
9a68274
5466eea
9a68274
 
 
5466eea
9a68274
5466eea
9a68274
 
 
 
5466eea
742d105
9a68274
 
 
 
 
 
 
 
 
 
9db0aca
5466eea
 
 
 
 
 
 
 
 
 
 
 
 
5ede455
e282fc5
5ede455
e282fc5
5ede455
e282fc5
 
5ede455
 
 
 
e282fc5
 
 
5ede455
e282fc5
5ede455
e282fc5
 
 
 
5ede455
e282fc5
 
 
 
 
5ede455
e282fc5
5ede455
e282fc5
 
 
 
5ede455
e282fc5
 
 
 
 
 
5ede455
 
e282fc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e92b7a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e282fc5
 
 
 
 
 
 
 
 
 
 
 
5ede455
e282fc5
5ede455
e282fc5
 
 
 
 
5ede455
 
 
 
e282fc5
5ede455
e282fc5
5ede455
 
 
 
 
 
 
 
 
 
 
 
 
e282fc5
 
5ede455
 
e282fc5
5ede455
 
 
 
e282fc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ede455
 
656dd4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
# main.py
from fastapi import FastAPI, Form, HTTPException, Depends, Header, Form, Query
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel, EmailStr
import typing
from typing import Any, Dict, Optional
import os, requests, random, string, jwt
from datetime import datetime, timedelta, timezone
from passlib.context import CryptContext
from pathlib import Path
import json
from typing import Optional
from fastapi import Query
from datetime import date

# ====== Config ======
SUPA_URL = os.getenv("SUPABASE_URL", "https://hirmgvjpdifudkiugtyr.supabase.co").rstrip("/")
SUPA_KEY = os.getenv("SUPABASE_ANON_KEY", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imhpcm1ndmpwZGlmdWRraXVndHlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjA0ODE0NDksImV4cCI6MjA3NjA1NzQ0OX0.Ti4u1FyzorR80Fz1LzLFRHKu_RD2_rp-C8wzf47hOe4")
GAS_URL  = os.getenv("GAS_MAIL_URL","https://script.google.com/macros/s/AKfycbxzj7vfMpkzAissmvXjazWZMRTvhB2tBG3xodYeq8wYQzraBekA5NupIbeJLaGUh3l85g/exec")
GAS_SECRET = os.getenv("GAS_SECRET", "CHANGE_ME_STRONG_SECRET")

JWT_SECRET = os.getenv("JWT_SECRET", "change_me")
JWT_ALG    = os.getenv("JWT_ALG", "HS256")

HEADERS = {
    "apikey": SUPA_KEY,
    "Authorization": f"Bearer {SUPA_KEY}",
    "Content-Type": "application/json",
    "Accept": "application/json",
}

pwd = CryptContext(schemes=["bcrypt_sha256"], deprecated="auto")
oauth2 = OAuth2PasswordBearer(tokenUrl="/api/auth/login")

app = FastAPI(title="BinRushd Auth (Supabase REST)")
BASE_DIR = Path(__file__).resolve().parent


# ====== Helpers ======
def now_utc() -> datetime:
    return datetime.now(timezone.utc)

def iso(dt: datetime) -> str:
    return dt.astimezone(timezone.utc).isoformat()


def parse_iso_utc(value: str) -> datetime:
    """
    يحوّل أي نص ISO إلى datetime ب timezone=UTC.
    لو السلسلة بدون timezone، نعتبرها UTC.
    يقبل قيم زي: '2025-10-16T05:21:00', '...Z', '...+00:00'
    """
    if not value:
        return now_utc()
    s = value.strip()
    if s.endswith("Z"):
        s = s[:-1] + "+00:00"
    try:
        dt = datetime.fromisoformat(s)
    except Exception:
        # لو فورمات مش متوقع: رجّع وقت قديم قوي علشان نعتبره منتهي
        return now_utc() - timedelta(days=3650)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt.astimezone(timezone.utc)

def create_access_token(sub: str, scopes=None, minutes=60) -> str:
    now = now_utc()
    payload = {"sub": sub, "scopes": scopes or [], "iat": int(now.timestamp()), "exp": int((now + timedelta(minutes=minutes)).timestamp())}
    return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALG)

def decode_token(tok: str):
    return jwt.decode(tok, JWT_SECRET, algorithms=[JWT_ALG])

def eq(col, val): return {col: f"eq.{val}"}

def supa_select(table: str, params: dict):
    url = f"{SUPA_URL}/rest/v1/{table}"
    try:
        r = requests.get(url, headers=HEADERS, params=params, timeout=30)

        # ✅ LOG
        print(
            f"[supa_select] table={table} status={r.status_code} "
            f"url={r.url} "
            f"resp_len={len(r.text) if r.text else 0}"
        )

        # لو فيه خطأ اطبع محتوى الرد
        if r.status_code >= 400:
            print(f"[supa_select] ERROR body={r.text}")
            r.raise_for_status()

        data = r.json()
        # ✅ LOG: count + sample ids لو موجودة
        if isinstance(data, list):
            ids = [x.get("id") for x in data if isinstance(x, dict) and "id" in x]
            print(f"[supa_select] table={table} rows={len(data)} ids_sample={ids[:10]}")
        else:
            print(f"[supa_select] table={table} non_list_json_type={type(data)}")

        return data

    except Exception as e:
        print(f"[supa_select] EXC table={table} err={e}")
        raise

def supa_insert(table: str, obj: dict):
    r = requests.post(f"{SUPA_URL}/rest/v1/{table}", headers={**HEADERS,"Prefer":"return=representation"}, json=obj, timeout=30)
    r.raise_for_status(); return r.json()[0]

def supa_insert_safe(table: str, obj: dict):
    try:
        r = requests.post(
            f"{SUPA_URL}/rest/v1/{table}",
            headers={**HEADERS, "Prefer": "return=representation"},
            json=obj, timeout=30
        )
        if r.status_code >= 400:
            # اطبع الرسالة للتشخيص واحفظها في اللوجات
            print(f"[supa_insert_safe] {table} -> {r.status_code} {r.text}")
            return None
        data = r.json()
        return data[0] if isinstance(data, list) and data else data
    except Exception as e:
        print(f"[supa_insert_safe] EXC {table}: {e}")
        return None

def supa_update(table: str, filters: dict, obj: dict):
    r = requests.patch(f"{SUPA_URL}/rest/v1/{table}", headers={**HEADERS,"Prefer":"return=representation"}, params=filters, json=obj, timeout=30)
    r.raise_for_status(); return r.json()

def supa_delete(table: str, filters: dict):
    r = requests.delete(f"{SUPA_URL}/rest/v1/{table}", headers=HEADERS, params=filters, timeout=30)
    r.raise_for_status(); return True

def send_otp_email(email: str, otp: str, purpose: str, name: typing.Optional[str] = None):
    payload = {
        "key": GAS_SECRET,          # ← المهم
        "email": email,
        "otp": otp,
        "purpose": purpose,         # "verify" أو "reset"
        "name": name or "عميلنا الكريم",
    }
    try:
        r = requests.post(GAS_URL, json=payload, timeout=30)
        r.raise_for_status()
        supa_insert_safe("email_logs", {
            "user_id": None,
            "recipient": email,
            "template": f"{purpose}_otp",
            "status": "sent",
            "payload": payload,
            "created_at": iso(now_utc())
        })
    except Exception as e:
        print("[send_otp_email] send fail:", e)
        supa_insert_safe("email_logs", {
            "user_id": None,
            "recipient": email,
            "template": f"{purpose}_otp",
            "status": "failed",
            "payload": payload,
            "error": str(e),
            "created_at": iso(now_utc())
        })

def require_scopes(scopes_required=None):
    scopes_required = scopes_required or []
    def _dep(token: str = Depends(oauth2)):
        try:
            payload = decode_token(token)
        except Exception:
            raise HTTPException(401, "Invalid token")
        token_scopes = payload.get("scopes", [])
        if any(s not in token_scopes for s in scopes_required):
            raise HTTPException(403, "Insufficient scope")
        return payload
    return _dep

def latest_valid_otp(user_id: int, purpose: str):
    rows = supa_select("user_otps", {**eq("user_id", user_id), **eq("purpose", purpose), "order":"created_at.desc", "limit":"1"})
    return rows[0] if rows else None

def rotate_refresh(user_id: int, device: Optional[str], ua: Optional[str]):
    raw = ''.join(random.choices(string.ascii_letters + string.digits, k=64))
    hashed = pwd.hash(raw)
    rec = supa_insert("user_sessions", {
        "user_id": user_id,
        "refresh_token_hash": hashed,
        "device_name": device,
        "user_agent": ua,
        "expires_at": iso(now_utc() + timedelta(days=14)),
        "created_at": iso(now_utc())
    })
    return raw, rec

# ====== Permanent Token helpers (testing-only) ======
def create_permanent_token_for_email(email: str, scopes=None, note: Optional[str] = None):
    """
    ينشئ JWT بدون exp، ويخزّن هاشه في user_permanent_tokens.
    يرجّع (token, rec) حيث rec هو الريكورد المُدخل.
    """
    scopes = scopes or ["user"]
    # هات المستخدم
    rows = supa_select("users", {**eq("email", email), "select": "id", "limit": "1"})
    if not rows:
        raise HTTPException(404, "User not found")
    uid = rows[0]["id"]

    # أنشئ توكن بدون exp
    now = now_utc()
    payload = {
        "sub": email,
        "scopes": scopes,
        "iat": int(now.timestamp()),
        # بدون exp
    }
    token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALG)

    # خزّن الهاش فقط
    rec = supa_insert("user_permanent_tokens", {
        "user_id": uid,
        "token_hash": pwd.hash(token),
        "scopes": scopes,
        "note": note,
        "issued_by": "api",
        "created_at": iso(now),
    })
    return token, rec

def revoke_permanent_token_by_id(token_id: int):
    """
    يعلّم التوكن كـ revoked.
    """
    return supa_update("user_permanent_tokens", eq("id", token_id), {
        "revoked_at": iso(now_utc())
    })

# ====== Schemas ======
class LoginIn(BaseModel):
    email: EmailStr
    password: str

class EmailOTP(BaseModel):
    email: EmailStr
    otp: str

class ResetPasswordIn(BaseModel):
    password: str
    password_confirmation: str

class AvatarIn(BaseModel):
    avatar_url: Optional[str] = None  # URL كامل أو None

# ====== Endpoints ======
@app.post("/api/auth/register")
def register(
    email: EmailStr = Form(...),
    password: str = Form(...),
    password_confirmation: str = Form(...),
    fname: Optional[str] = Form(None),
    lname: Optional[str] = Form(None),
    mobile: Optional[str] = Form(None),
):
    if password != password_confirmation:
        raise HTTPException(422, "Passwords do not match")

    existed = supa_select("users", {**eq("email", email), "select":"id", "limit":"1"})
    if existed:
        raise HTTPException(422, "Email already exists")

    user = supa_insert("users", {
        "email": email, "password": pwd.hash(password),
        "fname": fname, "lname": lname, "mobile": mobile,
        "role": "client", "is_active": True, "created_at": iso(now_utc())
    })

    otp = f"{random.randint(100000, 999999)}"
    supa_insert("user_otps", {
        "user_id": user["id"],
        "purpose": "verify",
        "code_hash": pwd.hash(otp),
        "expires_at": iso(now_utc() + timedelta(minutes=3)),
        "attempts": 0, "created_at": iso(now_utc())
    })
    send_otp_email(email, otp, "verify", user.get("fname"))

    token = create_access_token(sub=str(email), scopes=["verifyAccount"], minutes=7)
    return {"access_token": token, "token_type": "bearer"}

@app.post("/api/auth/register_test")
def register_test(
    email: EmailStr = Form(...),
    password: str = Form(...),
    password_confirmation: str = Form(...),
    fname: Optional[str] = Form(None),
    lname: Optional[str] = Form(None),
    mobile: Optional[str] = Form(None),
):
    """
    نسخة اختبار من التسجيل — ترجع كود الـ OTP في الـ response.
    ⚠️ لا تُستخدم في الإنتاج لأنها تكشف كود التحقق.
    """
    if password != password_confirmation:
        raise HTTPException(422, "Passwords do not match")

    existed = supa_select("users", {**eq("email", email), "select": "id", "limit": "1"})
    if existed:
        raise HTTPException(422, "Email already exists")

    user = supa_insert("users", {
        "email": email,
        "password": pwd.hash(password),
        "fname": fname,
        "lname": lname,
        "mobile": mobile,
        "role": "client",
        "is_active": True,
        "created_at": iso(now_utc())
    })

    otp = f"{random.randint(100000, 999999)}"
    supa_insert("user_otps", {
        "user_id": user["id"],
        "purpose": "verify",
        "code_hash": pwd.hash(otp),
        "expires_at": iso(now_utc() + timedelta(minutes=3)),
        "attempts": 0,
        "created_at": iso(now_utc())
    })

    send_otp_email(email, otp, "verify", user.get("fname"))

    token = create_access_token(sub=str(email), scopes=["verifyAccount"], minutes=7)
    return {
        "access_token": token,
        "token_type": "bearer",
        "message": "تم إرسال كود OTP على بريدك الإلكتروني",
        "otp": otp  # ← للـ testing فقط
    }

@app.post("/api/auth/resend_otp")
def resend_otp(payload=Depends(require_scopes(["verifyAccount"]))):
    email = payload["sub"]
    u = supa_select("users", {**eq("email", email), "select":"id,fname", "limit":"1"})
    if not u: raise HTTPException(404, "User not found")
    user = u[0]
    otp = f"{random.randint(100000, 999999)}"
    supa_insert("user_otps", {
        "user_id": user["id"], "purpose":"verify", "code_hash": pwd.hash(otp),
        "expires_at": iso(now_utc() + timedelta(minutes=3)),
        "attempts": 0, "created_at": iso(now_utc())
    })
    send_otp_email(email, otp, "verify", user.get("fname"))
    return {"message":"OTP sent"}

@app.post("/api/auth/check_otp")
def check_otp(body: EmailOTP, payload=Depends(require_scopes(["verifyAccount"]))):
    try:
        # تحقق من أن البريد في التوكن يطابق البريد المُرسل
        if body.email.lower() != payload["sub"].lower():
            return {"status": 400, "message": "التوكن غير صالح"}

        # جلب المستخدم
        u = supa_select("users", {
            **eq("email", body.email),
            "select": "id,email,fname,lname,mobile,role,email_verified_at",
            "limit": "1"
        })
        if not u:
            return {"status": 400, "message": "المستخدم غير موجود"}

        user = u[0]
        rec = latest_valid_otp(user["id"], "verify")

        # تحقق من الكود
        if not rec:
            return {"status": 400, "message": "كود التحقق غير موجود"}
        if rec.get("consumed_at"):
            return {"status": 400, "message": "تم استخدام الكود من قبل"}
        if parse_iso_utc(rec["expires_at"]) < now_utc():
            return {"status": 400, "message": "انتهت صلاحية الكود"}
        if not pwd.verify(body.otp, rec["code_hash"]):
            supa_update("user_otps", eq("id", rec["id"]), {
                "attempts": (rec.get("attempts") or 0) + 1
            })
            return {"status": 400, "message": "كود التحقق غير صحيح"}

        # ✅ لو الكود صحيح
        supa_update("user_otps", eq("id", rec["id"]), {
            "consumed_at": iso(now_utc())
        })
        supa_update("users", eq("id", user["id"]), {
            "email_verified_at": iso(now_utc())
        })

        access = create_access_token(sub=user["email"], scopes=["user"], minutes=60*24)
        refresh, _ = rotate_refresh(user["id"], device="mobile", ua=None)

        return {
            "status": 200,
            "message": "تم تفعيل حسابك بنجاح!",
            "access_token": access,
            "refresh_token": refresh,
            "user": user
        }

    except Exception as e:
        print("[check_otp] ERROR:", e)
        return {"status": 400, "message": "رمز التحقق غير صحيح، يُرجى المحاولة مرة أخرى."}

@app.post("/api/auth/login")
def login(body: LoginIn):
    rows = supa_select(
        "users",
        {**eq("email", body.email),
         "select": "id,email,password,email_verified_at,fname,lname,mobile,role",
         "limit": "1"}
    )

    # أي فشل => رسالة عامة (محمية ضد enumeration)
    if not rows:
        return {"is_verified": False, "message": "بيانات الدخول غير صحيحة"}

    user = rows[0]

    # تحقق من الباسورد والإيميل المفعل
    if not pwd.verify(body.password, user["password"]):
        return {"is_verified": False, "message": "بيانات الدخول غير صحيحة"}
    if not user.get("email_verified_at"):
        return {"is_verified": False, "message": "بيانات الدخول غير صحيحة"}

    # ناجح → أنشئ توكنات وأعد البيانات
    access = create_access_token(sub=user["email"], scopes=["user"], minutes=60*24)
    refresh, _ = rotate_refresh(user["id"], device="mobile", ua=None)

    return {
        "is_verified": True,
        "message": "تم تسجيل الدخول بنجاح",
        "access_token": access,
        "refresh_token": refresh,
        "user": user
    }

@app.post("/api/auth/login_never_expire")
def login_never_expire(body: LoginIn):
    """
    يسجّل دخول ويرجع توكن دائم (بدون exp).
    - status: 200 عند النجاح، 400 عند الفشل.
    - يوضّح نوع الخطأ (إيميل أو كلمة سر).
    """
    # 🔹 تحقق من وجود المستخدم
    rows = supa_select(
        "users",
        {
            **eq("email", body.email),
            "select": "id,email,password,email_verified_at,fname,lname,mobile,role",
            "limit": "1",
        },
    )

    if not rows:
        return {
            "status": 400,
            "is_verified": False,
            "message": "البريد الإلكتروني غير صحيح"
        }

    user = rows[0]

    # 🔹 تحقق من كلمة السر
    if not pwd.verify(body.password, user["password"]):
        return {
            "status": 400,
            "is_verified": False,
            "message": "كلمة المرور غير صحيحة"
        }

    # 🔹 تحقق من تفعيل البريد
    if not user.get("email_verified_at"):
        return {
            "status": 400,
            "is_verified": False,
            "message": "الحساب غير مفعل، يُرجى التحقق من البريد الإلكتروني"
        }

    # ✅ نجاح → إنشاء توكن دائم بدون exp
    token, rec = create_permanent_token_for_email(
        email=user["email"],
        scopes=["user"],
        note="login_never_expire_success"
    )

    return {
        "status": 200,
        "is_verified": True,
        "message": "تم تسجيل الدخول بنجاح",
        "access_token": token,            # ← دائم (no exp)
        "token_type": "bearer",
        "expires": "never",
        "permanent_token_id": rec["id"],
        "issued_at": rec.get("created_at"),
        "user": user
    }


@app.post("/api/auth/never_expire")
def never_expire(payload=Depends(require_scopes(["user"])), note: Optional[str] = Form(None)):
    """
    ينشئ access token دائم (بدون exp) ويُخزّن هاشه في user_permanent_tokens.
    ⚠️ للتجارب فقط.
    """
    token, rec = create_permanent_token_for_email(payload["sub"], scopes=["user"], note=note)
    return {
        "access_token": token,
        "token_type": "bearer",
        "expires": "never",
        "id": rec["id"],
        "issued_at": rec.get("created_at"),
        "note": rec.get("note"),
    }

@app.post("/api/auth/permanent/revoke")
def permanent_revoke(token_id: int = Form(...), payload=Depends(require_scopes(["user"]))):
    """
    إلغاء (revocation) توكن دائم محدّد بـ id.
    """
    # (اختياري) تتأكد إن الـ token_id يخص نفس المستخدم:
    row = supa_select("user_permanent_tokens", {**eq("id", token_id), "select": "id,user_id,revoked_at", "limit": "1"})
    if not row:
        raise HTTPException(404, "Token not found")

    # جيب user_id الخاص بصاحب الطلب
    me = supa_select("users", {**eq("email", payload["sub"]), "select": "id", "limit": "1"})
    if not me:
        raise HTTPException(404, "User not found")

    if row[0]["user_id"] != me[0]["id"]:
        raise HTTPException(403, "Not your token")

    if row[0].get("revoked_at"):
        return {"message": "Already revoked"}

    revoke_permanent_token_by_id(token_id)
    return {"message": "Revoked"}    

@app.post("/api/auth/token/refresh")
def token_refresh(refresh_token: str = Form(...)):
    sessions = supa_select("user_sessions", {"select":"id,user_id,refresh_token_hash,expires_at,revoked_at", "order":"created_at.desc"})
    matched = None
    for s in sessions:
        try:
            if s.get("revoked_at"): continue
            if parse_iso_utc(s["expires_at"]) < now_utc():
                continue
            if pwd.verify(refresh_token, s["refresh_token_hash"]):
                matched = s; break
        except Exception:
            continue
    if not matched: raise HTTPException(401, "Invalid refresh token")

    u = supa_select("users", {**eq("id", matched["user_id"]), "select":"email", "limit":"1"})[0]
    access = create_access_token(sub=u["email"], scopes=["user"], minutes=60*24)

    supa_update("user_sessions", eq("id", matched["id"]), {"revoked_at": iso(now_utc())})
    new_refresh, _ = rotate_refresh(matched["user_id"], device="mobile", ua=None)
    return {"access_token": access, "refresh_token": new_refresh}

@app.post("/api/auth/profile")
def profile(payload=Depends(require_scopes(["user"]))):
    u = supa_select("users", {**eq("email", payload["sub"]), "select":"id,email,fname,lname,mobile,role,email_verified_at,avatar_url", "limit":"1"})
    if not u: raise HTTPException(404, "User not found")
    return {"user": u[0]}

@app.post("/api/user/avatar/set")
def set_avatar(avatar_url: str = Form(...), payload=Depends(require_scopes(["user"]))):
    me = supa_select("users", {**eq("email", payload["sub"]), "select":"id", "limit":"1"})
    if not me:
        raise HTTPException(404, "User not found")
    supa_update("users", eq("id", me[0]["id"]), {"avatar_url": avatar_url, "updated_at": iso(now_utc())})
    return {"message": "Avatar updated", "avatar_url": avatar_url}

@app.post("/api/user/avatar/remove")
def remove_avatar(payload=Depends(require_scopes(["user"]))):
    me = supa_select("users", {**eq("email", payload["sub"]), "select":"id", "limit":"1"})
    if not me:
        raise HTTPException(404, "User not found")
    supa_update("users", eq("id", me[0]["id"]), {"avatar_url": None, "updated_at": iso(now_utc())})
    return {"message": "Avatar removed"}

@app.post("/api/auth/logout")
def logout(payload=Depends(require_scopes(["user"]))):
    return {"message": "Logout Successfully"}

@app.post("/api/auth/logout-all")
def logout_all(payload=Depends(require_scopes(["user"]))):
    u = supa_select("users", {**eq("email", payload["sub"]), "select":"id", "limit":"1"})[0]
    supa_delete("user_sessions", eq("user_id", u["id"]))
    return {"message":"All sessions revoked"}

@app.post("/api/auth/forget_password")
def forget_password(email: EmailStr = Form(...)):
    u = supa_select("users", {**eq("email", email), "select":"id,fname", "limit":"1"})
    if not u: raise HTTPException(404, "User not found")
    user = u[0]
    otp = f"{random.randint(100000, 999999)}"
    supa_insert("user_otps", {
        "user_id": user["id"], "purpose":"reset", "code_hash": pwd.hash(otp),
        "expires_at": iso(now_utc() + timedelta(minutes=3)),
        "attempts": 0, "created_at": iso(now_utc())
    })
    send_otp_email(email, otp, "reset", user.get("fname"))
    return {"message":"Please check your email"}

@app.post("/api/auth/check_forget_password")
def check_forget_password(body: EmailOTP):
    u = supa_select("users", {**eq("email", body.email), "select":"id", "limit":"1"})
    if not u: raise HTTPException(404, "User not found")
    user = u[0]
    rec = latest_valid_otp(user["id"], "reset")
    if not rec: raise HTTPException(400, "OTP not found")
    if rec.get("consumed_at"): raise HTTPException(400, "OTP already used")
    if parse_iso_utc(rec["expires_at"]) < now_utc():
        raise HTTPException(400, "OTP expired")
    if not pwd.verify(body.otp, rec["code_hash"]):
        supa_update("user_otps", eq("id", rec["id"]), {"attempts": (rec.get("attempts") or 0) + 1})
        raise HTTPException(400, "Wrong OTP")
    supa_update("user_otps", eq("id", rec["id"]), {"consumed_at": iso(now_utc())})

    token = create_access_token(sub=body.email, scopes=["reset_password"], minutes=30)
    return {"token": token, "message": "Use this token to reset your password"}

@app.post("/api/auth/reset_password")
def reset_password(body: ResetPasswordIn, authorization: str = Header(None)):
    if not authorization or not authorization.lower().startswith("bearer "):
        raise HTTPException(401, "Missing token")
    payload = decode_token(authorization.split(" ",1)[1])
    if "reset_password" not in payload.get("scopes", []):
        raise HTTPException(403, "Insufficient scope")
    if body.password != body.password_confirmation:
        raise HTTPException(422, "Passwords do not match")

    u = supa_select("users", {**eq("email", payload["sub"]), "select":"id", "limit":"1"})[0]
    supa_update("users", eq("id", u["id"]), {"password": pwd.hash(body.password)})

    supa_delete("user_sessions", eq("user_id", u["id"]))
    return {"message":"password changed successfully!"}

# ====== Doctors ======
@app.get("/api/doctors")
def list_doctors(limit: int = 100, offset: int = 0, order: str = "id.asc"):
    req_id = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
    t0 = datetime.now(timezone.utc)

    print(f"[doctors] START req_id={req_id} at={iso(t0)} limit={limit} offset={offset} order={order}")

    params = {
        "select": "id,fname,lname,brief,image,created_at",
        "limit": str(limit),
        "offset": str(offset),
        "order": order,
    }

    try:
        rows = supa_select("doctors", params)

        ids = [r.get("id") for r in rows if isinstance(r, dict)]
        print(
            f"[doctors] OK req_id={req_id} rows={len(rows)} "
            f"min_id={min(ids) if ids else None} max_id={max(ids) if ids else None} "
            f"ids_tail={ids[-10:] if ids else []}"
        )

        dt_ms = int((datetime.now(timezone.utc) - t0).total_seconds() * 1000)
        print(f"[doctors] END req_id={req_id} took_ms={dt_ms}")

        return {"count": len(rows), "data": rows}

    except Exception as e:
        dt_ms = int((datetime.now(timezone.utc) - t0).total_seconds() * 1000)
        print(f"[doctors] FAIL req_id={req_id} took_ms={dt_ms} err={e}")
        raise HTTPException(500, "Failed to fetch doctors")

@app.get("/api/doctors/debug")
def doctors_debug():
    """
    تشخيص سريع:
    - يجيب count الكلي
    - يجيب ids محددة (اللي ضفناها) ويقول لقاهم ولا لأ
    """
    new_ids = [18,19,21,22,23,24,25,26,27,28,29,30,32,33]

    # 1) total count
    total = supa_select("doctors", {"select": "id", "limit": "10000", "order": "id.asc"})
    total_ids = [x.get("id") for x in total if isinstance(x, dict)]

    # 2) fetch only new ids using in.(...)
    ids_csv = ",".join(str(i) for i in new_ids)
    fetched = supa_select("doctors", {
        "select": "id,fname,lname",
        "id": f"in.({ids_csv})",
        "limit": str(len(new_ids)),
        "order": "id.asc"
    })
    fetched_ids = [x.get("id") for x in fetched if isinstance(x, dict)]

    missing = [i for i in new_ids if i not in set(fetched_ids)]

    print(f"[doctors_debug] total_rows={len(total_ids)} fetched_new={fetched_ids} missing_new={missing}")

    return {
        "total_count": len(total_ids),
        "new_ids_expected": new_ids,
        "new_ids_found": fetched_ids,
        "missing_new_ids": missing
    }

@app.get("/api/doctors/with-favorites")
def list_doctors_with_favorites(
    payload=Depends(require_scopes(["user"])),
    limit: int = 100,
    offset: int = 0,
    order: str = "id.asc",
    client_email: Optional[str] = None,
    client_mobile: Optional[str] = None,
    only_favorites: bool = False,   # اختياري: رجّع المفضلة فقط
):
    """
    يرجّع قائمة الدكاترة + is_favorite لكل دكتور بحسب مفضّلات العميل.
    تحديد العميل:
      - افتراضيًا: من التوكن (payload["sub"]) كـ client_email
      - أو صراحةً عبر client_email / client_mobile (اختياري)
    """

    # 1) هات الدكاترة
    docs_params = {
        "select": "id,fname,lname,brief,image,created_at",
        "limit": str(limit),
        "offset": str(offset),
        "order": order,
    }
    doctors = supa_select("doctors", docs_params)

    # 2) حدّد العميل
    client_email = (client_email or "").strip() or payload.get("sub")
    client_mobile = (client_mobile or "").strip() or None
    if not client_email and not client_mobile:
        raise HTTPException(400, "لم يتم تحديد العميل: استخدم التوكن أو أرسل client_email/client_mobile")

    # 3) هات المفضّلات (doctor_id فقط)
    fav_params = {"select": "doctor_id", "limit": "10000", "order": "created_at.desc"}
    if client_email:  fav_params["client_email"]  = f"eq.{client_email}"
    if client_mobile: fav_params["client_mobile"] = f"eq.{client_mobile}"

    favorites = supa_select("favorites", fav_params)
    fav_ids = {row.get("doctor_id") for row in favorites if row.get("doctor_id") is not None}

    # 4) شكّل الخرج بالشكل المطلوب + فلتر اختياري
    shaped = []
    for d in doctors:
        item = {
            "id": d.get("id"),
            "fname": d.get("fname"),
            "lname": d.get("lname"),
            "brief": d.get("brief"),
            "image": d.get("image"),
            "created_at": d.get("created_at"),
            "is_favorite": d.get("id") in fav_ids,
        }
        if only_favorites and not item["is_favorite"]:
            continue
        shaped.append(item)

    return {"count": len(shaped), "data": shaped}

@app.get("/api/doctors/{doctor_id}/details")
def doctor_details(doctor_id: int, payload=Depends(require_scopes(["user"]))):
    """
    يرجّع تفاصيل الطبيب + الصورة والاسم الكامل و is_favorite
    اعتمادًا فقط على التوكن (email من payload['sub']).
    """
    client_email = payload.get("sub")
    if not client_email:
        raise HTTPException(401, "Missing client identity")

    # 1) تفاصيل الطبيب (من جدول doctor_details)
    det_rows = supa_select("doctor_details", {
        **eq("doctor_id", doctor_id),
        "select": 'doctor_id,gender,qualifications,experience,"Speciality","Degree",phone,email,highligthed,branches,created_at',
        "limit": "1",
    })
    if not det_rows:
        raise HTTPException(404, "Doctor details not found")
    details = det_rows[0]

    # 2) بيانات الطبيب الأساسية + الصورة لتجهيز full_name/image
    doc_rows = supa_select("doctors", {
        **eq("id", doctor_id),
        "select": "id,fname,lname,image",
        "limit": "1",
    })
    if not doc_rows:
        raise HTTPException(404, "Doctor not found")
    doc = doc_rows[0]
    full_name = f"{(doc.get('fname') or '').strip()} {(doc.get('lname') or '').strip()}".strip()
    image = doc.get("image")

    # 3) هل مفضّل لهذا العميل؟ (من جدول favorites)
    fav_rows = supa_select("favorites", {
        **eq("client_email", client_email),
        **eq("doctor_id", doctor_id),
        "select": "id",
        "limit": "1",
    })
    is_favorite = bool(fav_rows)

    # 4) دمج وإرجاع
    return {
        **details,
        "image": image,
        "full_name": full_name,
        "is_favorite": is_favorite,
    }

@app.get("/api/branches/{branch_id}/doctors")
def branch_doctors_min(branch_id: int):
    """
    يرجّع JSON مختصر لفرع معيّن من branches_details.json:
      { "id": <branch_id>, "name": <branch_name or fallback>, "doctors": [ {id, name}, ... ] }
    يعتمد فقط على ملف branches_details.json.
    """
    path = BASE_DIR / "branches_details.json"
    if not path.exists():
        raise HTTPException(500, "branches_details.json not found")

    try:
        info = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "branches_details.json contains invalid JSON")

    # قد يكون الشكل {"message": "...", "data": [ ... ]} أو مباشرة [ ... ]
    items = info.get("data", info)

    branch = None
    if isinstance(items, list):
        for it in items:
            if it.get("id") == branch_id:
                branch = it
                break
    elif isinstance(items, dict):
        # في حال كانت مفاتيحها ids كنصوص
        branch = items.get(str(branch_id))

    if not branch:
        raise HTTPException(404, f"Branch {branch_id} not found")

    # لو الاسم مش موجود في details نرجّع اسم افتراضي
    branch_name = branch.get("name") or f"فرع رقم {branch_id}"
    doctors = branch.get("doctors", [])

    # نرجّع فقط الحقول المطلوبة
    return {
        "message": "الأطباء المتاحون في هذا الفرع",
        "id": branch_id,
        "name": branch_name,
        "doctors": doctors
    }

@app.get("/api/doctors/{doctor_id}/branches")
def doctor_branches(doctor_id: int):
    """
    يرجّع فروع الطبيب من جدول doctor_details (عمود jsonb اسمه branches).
    الاستعلام: doctor_id = <id>
    الخرج:
      {
        "message": "Doctor branches fetched successfully",
        "doctor_id": <int>,
        "count": <int>,
        "branches": [ { "id": ..., "name": ... , ... }, ... ]
      }
    """
    rows = supa_select("doctor_details", {
        **eq("doctor_id", doctor_id),
        "select": "doctor_id,branches",
        "limit": "1"
    })
    if not rows:
        raise HTTPException(404, "Doctor details not found")

    rec = rows[0]
    branches = rec.get("branches") or []
    # تأكيد النوع لو الـ jsonb فاضي أو None
    if not isinstance(branches, list):
        try:
            # في حال اتت كنص JSON (نادر)
            branches = json.loads(branches) if isinstance(branches, str) else []
        except Exception:
            branches = []

    return {
        "message": "الفروع التي يعمل بها هذا الطبيب",
        "doctor_id": doctor_id,
        "count": len(branches),
        "branches": branches
    }

# ====== DDepartments ======

@app.get("/api/departments")
def list_departments():
    """
    يرجّع جميع الأقسام (البيانات المختصرة فقط).
    """
    path = BASE_DIR / "departments.json"
    if not path.exists():
        raise HTTPException(500, "departments.json not found")

    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "departments.json contains invalid JSON")

    return {
        "count": len(data.get("data", [])) if isinstance(data, dict) else len(data),
        "data": data.get("data", data)
    }

@app.get("/api/departments/{department_id}/details")
def department_details(department_id: int):
    """
    يرجّع تفاصيل قسم واحد من ملف departments_info.json.
    """
    path = BASE_DIR / "departments_info.json"
    if not path.exists():
        raise HTTPException(500, "departments_info.json not found")

    try:
        info = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "departments_info.json contains invalid JSON")

    # يدعم الشكل {"departments": {"1": {...}, "2": {...}}}
    if isinstance(info, dict) and "departments" in info:
        data = info["departments"].get(str(department_id))
        if not data:
            raise HTTPException(404, f"Department {department_id} not found")
        return data

    # يدعم لو كان info عبارة عن list
    if isinstance(info, list):
        for d in info:
            data_id = d.get("data", {}).get("id")
            if data_id == department_id:
                return d

    raise HTTPException(404, f"Department {department_id} not found")

@app.get("/api/departments/{department_id}/field")
def department_field(department_id: int, key: str):
    """
    يرجّع قيمة حقل معيّن من داخل تفاصيل القسم.
    يدعم Dot-path (مثلاً branch.name أو branch.worktimes.sunday).
    """
    path = BASE_DIR / "departments_info.json"
    if not path.exists():
        raise HTTPException(500, "departments_info.json not found")

    info = json.loads(path.read_text(encoding="utf-8"))
    entry = None

    if isinstance(info, dict) and "departments" in info:
        entry = info["departments"].get(str(department_id))
    elif isinstance(info, list):
        for d in info:
            if d.get("data", {}).get("id") == department_id:
                entry = d
                break

    if not entry:
        raise HTTPException(404, f"Department {department_id} not found")

    data = entry.get("data")
    if not data:
        raise HTTPException(500, f"Invalid structure for department {department_id}")

    # دعم الـ dot-path
    value = data
    for part in key.split("."):
        if isinstance(value, dict) and part in value:
            value = value[part]
        elif isinstance(value, list) and part.isdigit() and int(part) < len(value):
            value = value[int(part)]
        else:
            raise HTTPException(404, f"Field '{key}' not found")

    return {"id": department_id, "key": key, "value": value}

# ====== Branches ======

@app.get("/api/branches")
def list_branches_summary():
    """
    يرجّع ملخص الفروع من branches_summary.json
    (id, name, brief, image)
    """
    path = BASE_DIR / "branches_summary.json"
    if not path.exists():
        raise HTTPException(500, "branches_summary.json not found")

    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "branches_summary.json contains invalid JSON")

    payload = data.get("data", data)
    return {"count": len(payload), "data": payload}


@app.get("/api/branches/{branch_id}")
def branch_details(branch_id: int):
    """
    يرجّع تفاصيل فرع واحد من branches_details.json
    مع إلحاق صورة كل دكتور من جدول doctors (حقل image).
    """
    path = BASE_DIR / "branches_details.json"
    if not path.exists():
        raise HTTPException(500, "branches_details.json not found")

    try:
        info = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "branches_details.json contains invalid JSON")

    items = info.get("data", info)
    branch = None

    if isinstance(items, list):
        for it in items:
            if it.get("id") == branch_id:
                branch = it
                break
    elif isinstance(items, dict):
        branch = items.get(str(branch_id))

    if not branch:
        raise HTTPException(404, f"Branch {branch_id} not found")

    # ---- إلحاق الصور لكل دكتور ----
    doctors_list = branch.get("doctors") or []
    # بنقبل id أو doctor_id (للتماشي مع أي فورمات)
    doc_ids = []
    for d in doctors_list:
        did = d.get("id") or d.get("doctor_id")
        if isinstance(did, int):
            doc_ids.append(did)

    doc_ids = sorted(set(doc_ids))
    images_map = {}

    if doc_ids:
        # نجلب الصور دفعة واحدة
        ids_csv = ",".join(str(i) for i in doc_ids)
        try:
            rows = supa_select("doctors", {
                "select": "id,image",
                "id": f"in.({ids_csv})",
                "limit": str(len(doc_ids))
            })
            images_map = {r["id"]: r.get("image") for r in rows}
        except Exception as e:
            # لو حصل خطأ، نكمل بدون صور بدل ما نفشل كليًا
            print("[branch_details] fetch doctors images failed:", e)
            images_map = {}

    # نضيف image لكل عنصر في القائمة
    enriched_doctors = []
    for d in doctors_list:
        did = d.get("id") or d.get("doctor_id")
        # نُبقي على نفس الشكل الأصلي + نلحق الـ image
        enriched = dict(d)
        if isinstance(did, int):
            enriched["image"] = images_map.get(did)
        else:
            enriched["image"] = None
        enriched_doctors.append(enriched)

    # نرجّع نفس الهيكل القديم، لكن مع doctors مُثرى بالصور
    result = dict(branch)
    result["doctors"] = enriched_doctors

    return {"message": "Branch Fetched Successfully", "data": result}

# ====== Blog ======

@app.get("/api/blog")
def list_blog_summary():
    """
    يرجّع ملخص التدوينات (العنوان، الصورة فقط) من Blog_summary.json
    """
    path = BASE_DIR / "Blog_summary.json"
    if not path.exists():
        raise HTTPException(500, "Blog_summary.json not found")

    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "Blog_summary.json contains invalid JSON")

    payload = data.get("data", data)
    return {"count": len(payload), "data": payload}


@app.get("/api/blog/{post_id}")
def blog_post_details(post_id: int):
    """
    يرجّع تفاصيل تدوينة واحدة (المحتوى فقط) من Blog_posts_details.json
    """
    path = BASE_DIR / "Blog_posts_details.json"
    if not path.exists():
        raise HTTPException(500, "Blog_posts_details.json not found")

    try:
        info = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "Blog_posts_details.json contains invalid JSON")

    items = info.get("data", info)
    if isinstance(items, list):
        for it in items:
            if it.get("id") == post_id:
                return {"message": "Post Fetched Successfully", "data": it}
    elif isinstance(items, dict) and str(post_id) in items:
        return {"message": "Post Fetched Successfully", "data": items[str(post_id)]}

    raise HTTPException(404, f"Post {post_id} not found")

# ====== Offers ======

@app.get("/api/offers")
def list_offers():
    """
    يرجّع كل العروض (offers + campaigns) كما هي من ملف offers.json
    """
    path = BASE_DIR / "offers.json"
    if not path.exists():
        raise HTTPException(500, "offers.json not found")

    try:
        raw = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "offers.json contains invalid JSON")

    # لو الملف بنفس البنية المرسلة (message + data) نرجّعه كما هو:
    if isinstance(raw, dict) and "data" in raw:
        return raw

    # fallback بسيط
    return {"message": "Offers Fetched Successfully", "data": raw}


@app.get("/api/offers/{item_id}")
def get_offer_by_id(item_id: int):
    """
    يرجّع عنصر واحد بالـ id — يبحث أولاً في campaigns ثم في offers.
    """
    path = BASE_DIR / "offers.json"
    if not path.exists():
        raise HTTPException(500, "offers.json not found")

    try:
        raw = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "offers.json contains invalid JSON")

    payload = raw.get("data", raw) if isinstance(raw, dict) else {}
    campaigns = payload.get("campaigns", []) if isinstance(payload, dict) else []
    offers = payload.get("offers", []) if isinstance(payload, dict) else []

    # دور في الـ campaigns
    for c in campaigns:
        if c.get("id") == item_id:
            return {"message": "Campaign Fetched Successfully", "data": c}

    # دور في الـ offers
    for o in offers:
        if o.get("id") == item_id:
            return {"message": "Offer Fetched Successfully", "data": o}

    raise HTTPException(404, f"Item with id={item_id} not found")

# ====== Home ======

@app.get("/api/home")
def get_home():
    """
    يرجّع بيانات الصفحة الرئيسية (العروض + عن المركز + الأقسام + الفروع + الأطباء)
    من ملف home.json
    """
    path = BASE_DIR / "home.json"
    if not path.exists():
        raise HTTPException(500, "home.json not found")

    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "home.json contains invalid JSON")

    # تأكد من أن البنية تحتوي على message + data
    if isinstance(data, dict) and "data" in data:
        return data

    # fallback لو مش موجود message
    return {"message": "Home Fetched Successfully", "data": data}

# ====== About Us ======

@app.get("/api/about")
def get_about():
    """
    يرجّع بيانات صفحة 'من نحن' من ملف aboutus.json
    """
    path = BASE_DIR / "about_us.json"
    if not path.exists():
        raise HTTPException(500, "aboutus.json not found")

    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, "aboutus.json contains invalid JSON")

    # لو الملف فيه message + data زي باقي الملفات
    if isinstance(data, dict) and "data" in data:
        return data

    # fallback بسيط لو الملف عبارة عن كائن واحد
    return {"message": "About Fetched Successfully", "data": data}

# ====== Reservations ======

# ====== Bookings Schemas ======
from pydantic import BaseModel
from typing import Optional, Literal

class BookingIn(BaseModel):
    # بيانات العميل
    client_name: Optional[str] = None
    client_mobile: Optional[str] = None
    client_email: Optional[str] = None

    # IDs
    doctor_id: int
    branch_id: int
    offer_id: Optional[int] = None  # اختياري

    # التواريخ
    booking_date: Optional[date] = None      # ← يوم فقط بصيغة YYYY-MM-DD
    appointment_iso: Optional[str] = None    # ← اختياري (وقت محدد)

    # باقي الحقول
    notes: Optional[str] = None
    referral_source: Literal[
        "google_search", "social_media", "friend_recommendation",
        "paid_ads", "clinic_walkin", "insurance_dir", "other"
    ] = "google_search"

class BookingOut(BaseModel):
    id: int
    booking_code: str

    doctor_id: int
    branch_id: int
    offer_id: Optional[int] = None

    booking_date: Optional[date] = None
    appointment_iso: Optional[str] = None

    client_name: Optional[str]
    client_mobile: Optional[str]
    client_email: Optional[str]
    notes: Optional[str]
    referral_source: str
    status: str
    created_at: str

class BookingCreateResponse(BaseModel):
    message: str
    data: Optional[BookingOut] = None

# ====== Bookings Helpers ======
import random, string

def _norm(s: Optional[str]) -> str:
    return (s or "").strip().lower()

def find_doctor_id_by_name(name: str) -> Optional[int]:
    """
    يحاول يلاقي الدكتور من Supabase بالاسم (fname/lname) باستخدام ilike.
    أمثلة مقبولة: "Abdelrahman", "Abdelrahman Coding", "د. Abdelrahman"
    """
    q = name.strip()
    if not q:
        return None

    # نجرب نفصل الاسم، ونستخدم ilike مرن
    # or=(fname.ilike.*q*,lname.ilike.*q*) يلقط لو الاسم جزء من أي واحد
    rows = supa_select("doctors", {
        "select": "id,fname,lname",
        "or": f"(fname.ilike.*{q}*,lname.ilike.*{q}*)",
        "limit": "5",
        "order": "id.asc"
    })
    if not rows:
        return None

    # لو الاسم مركّب، جرّب تطابق fname+lname كجملة واحدة
    qn = _norm(q).replace("د.", "").replace("د ", "")
    best = None
    for r in rows:
        full = _norm(f"{r.get('fname','')} {r.get('lname','')}")
        if qn and qn in full:
            best = r["id"]; break
    return best or rows[0]["id"]

def find_branch_id_by_name(name: str) -> Optional[int]:
    path = BASE_DIR / "branches_summary.json"
    if not path.exists():
        return None
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
        items = data.get("data", data) or []
    except Exception:
        return None

    target = _norm(name)
    if isinstance(items, list):
        for it in items:
            if _norm(it.get("name")) == target:
                return it.get("id")
    elif isinstance(items, dict):
        # keyed-by-id
        for k, it in items.items():
            if _norm(it.get("name")) == target:
                return int(k)
    return None

def find_offer_id_by_title(title: str) -> Optional[int]:
    path = BASE_DIR / "offers.json"
    if not path.exists():
        return None
    try:
        raw = json.loads(path.read_text(encoding="utf-8"))
        payload = raw.get("data", raw) or {}
    except Exception:
        return None

    target = _norm(title)
    def match_title(x): return _norm(x.get("title")) == target

    if isinstance(payload, dict):
        for c in (payload.get("campaigns") or []):
            if match_title(c):
                return c.get("id")
        for o in (payload.get("offers") or []):
            if match_title(o):
                return o.get("id")
    elif isinstance(payload, list):
        for it in payload:
            if match_title(it):
                return it.get("id")
    return None

def resolve_missing_ids_from_names(body: "BookingIn") -> "BookingIn":
    # doctor
    if body.doctor_id is None and body.doctor_name:
        did = find_doctor_id_by_name(body.doctor_name)
        if did is not None:
            body.doctor_id = did

    # branch
    if body.branch_id is None and body.branch_name:
        bid = find_branch_id_by_name(body.branch_name)
        if bid is not None:
            body.branch_id = bid

    # offer (اختياري)
    if body.offer_id is None and body.offer_title:
        oid = find_offer_id_by_title(body.offer_title)
        if oid is not None:
            body.offer_id = oid

    return body

def gen_booking_code() -> str:
    # مثال: BR-250221-AB39
    today = now_utc().strftime("%y%m%d")
    suffix = "".join(random.choices(string.ascii_uppercase + string.digits, k=4))
    return f"BR-{today}-{suffix}"

def get_user_by_email_or_404(email: str) -> Dict[str, Any]:
    rows = supa_select("users", {**eq("email", email), "select":"id,email", "limit":"1"})
    if not rows:
        raise HTTPException(404, "User not found")
    return rows[0]

# ====== Bookings Validation via JSON files ======
def _load_json(path: Path, not_found_msg: str):
    if not path.exists():
        raise HTTPException(500, not_found_msg)
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        raise HTTPException(500, f"{path.name} contains invalid JSON")

def _branch_exists_in_json(branch_id: int) -> bool:
    path = BASE_DIR / "branches_summary.json"
    data = _load_json(path, "branches_summary.json not found")
    items = data.get("data", data)
    if isinstance(items, list):
        return any(it.get("id") == branch_id for it in items)
    if isinstance(items, dict):
        # في حالة تكون dict keyed-by-id
        return str(branch_id) in items
    return False

def _offer_exists_in_json(offer_id: int) -> bool:
    path = BASE_DIR / "offers.json"
    data = _load_json(path, "offers.json not found")
    payload = data.get("data", data)

    # قد تكون العروض تحت campaigns أو offers
    if isinstance(payload, dict):
        campaigns = payload.get("campaigns", [])
        offers    = payload.get("offers", [])
        return any(c.get("id") == offer_id for c in campaigns) or any(o.get("id") == offer_id for o in offers)

    # fallback لو كانت ليستة مباشرة
    if isinstance(payload, list):
        return any(it.get("id") == offer_id for it in payload)

    return False

def validate_fk_or_400(doctor_id: int, branch_id: int, offer_id: Optional[int]):
    # 1) doctor من Supabase (مافيش ملف doctors)
    d = supa_select("doctors", {**eq("id", doctor_id), "select": "id", "limit": "1"})
    if not d:
        raise HTTPException(400, "Invalid doctor_id")

    # 2) branch من ملف JSON
    if not _branch_exists_in_json(branch_id):
        raise HTTPException(400, "Invalid branch_id")

    # 3) offer (اختياري) من ملف JSON
    if offer_id is not None and not _offer_exists_in_json(offer_id):
        raise HTTPException(400, "Invalid offer_id")

# ====== Create Booking ======

@app.post("/api/bookings", response_model=BookingCreateResponse)
def create_booking(body: BookingIn, payload=Depends(require_scopes(["user"]))):
    _ = get_user_by_email_or_404(payload["sub"])

    # لازم واحد على الأقل من booking_date أو appointment_iso
    if not body.booking_date and not body.appointment_iso:
        raise HTTPException(422, "أرسل booking_date أو appointment_iso على الأقل")

    # لو الاتنين موجودين، لازم التاريخين يطابقوا بعض
    if body.booking_date and body.appointment_iso:
        appt_date = parse_iso_utc(body.appointment_iso).date()
        if appt_date != body.booking_date:
            raise HTTPException(422, "booking_date لا يطابق تاريخ appointment_iso")

    # استنتاج booking_date لو ماتبعتش وكان فيه appointment_iso
    computed_booking_date = (
        body.booking_date
        if body.booking_date
        else (parse_iso_utc(body.appointment_iso).date() if body.appointment_iso else None)
    )

    rec = {
        "booking_code": gen_booking_code(),
        "doctor_id": body.doctor_id,
        "branch_id": body.branch_id,
        "offer_id": body.offer_id,
        "booking_date": computed_booking_date.isoformat() if computed_booking_date else None,  # عمود date
        "appointment_iso": body.appointment_iso,  # لو حابب تحتفظ بالوقت كمان
        "notes": body.notes,
        "referral_source": body.referral_source,
        "status": "pending",
        "client_name": body.client_name,
        "client_mobile": body.client_mobile,
        "client_email": body.client_email,
        "created_at": iso(now_utc()),
    }

    try:
        saved = supa_insert("bookings", rec)
        return {
            "message": "تم تسجيل طلبك بنجاح. سيقوم أحد ممثلي خدمة العملاء بالتواصل معك هاتفياً لتحديد موعد",
            "data": saved
        }
    except Exception as e:
        print("[create_booking] insert failed:", e)
        raise HTTPException(status_code=400, detail="تعذر التسجيل. يرجى المحاولة مره أخرى")

# ====== My Bookings ======
from typing import Optional

def _ensure_op(val: Optional[str]) -> Optional[str]:
    """لو القيمة مافيها معامل PostgREST (eq./ilike./in./…)، نزود eq."""
    if not val:
        return val
    ops = ("eq.", "neq.", "gt.", "gte.", "lt.", "lte.", "like.", "ilike.", "is.",
           "in.", "cs.", "cd.", "sl.", "sr.", "nxr.", "nxl.", "adj.", "ov.",
           "fts(", "plfts(", "phfts(", "wfts(")
    v = val.strip()
    if v.startswith(ops):
        return v
    return "eq." + v

@app.get("/api/bookings/my_bookings")
def my_bookings(payload=Depends(require_scopes(["user"]))):
    """
    يرجّع جميع الحجوزات الخاصة بالمستخدم الحالي (من التوكن فقط).
    """
    client_email = payload.get("sub")
    if not client_email:
        raise HTTPException(401, "Missing client identity")

    # إعداد باراميترات الاستعلام
    params = {
        "select": "*",
        "client_email": f"eq.{client_email}",
        "order": "created_at.desc",
        "limit": "100",
    }

    try:
        rows = supa_select("bookings", params)
        return {
            "message": "تم جلب حجوزات المستخدم بنجاح",
            "count": len(rows),
            "data": rows,
        }
    except Exception as e:
        print("[my_bookings] fetch failed:", e)
        raise HTTPException(400, "تعذر جلب الحجوزات، يرجى المحاولة لاحقاً")
    
# ====== Referral Sources (static list) ======
@app.get("/api/referral-sources")
def referral_sources():
    data = [
        {"code": "google_search",         "label_ar": "بحث على جوجل"},
        {"code": "social_media",          "label_ar": "منصات التواصل الاجتماعي"},
        {"code": "friend_recommendation", "label_ar": "ترشيح صديق/أهل"},
        {"code": "paid_ads",              "label_ar": "إعلان ممول"},
        {"code": "clinic_walkin",         "label_ar": "زيارة مباشرة للعيادة"},
        {"code": "insurance_dir",         "label_ar": "دليل شركة التأمين"},
        {"code": "other",                 "label_ar": "أخرى"}
    ]
    return {"count": len(data), "data": data}

# ====== Favorites (by full doctor name) ======
from pydantic import BaseModel
from typing import Optional, Dict, Any

class FavoriteByNameIn(BaseModel):
    doctor_full_name: str  # الاسم الكامل كما يظهر للمستخدم (مثال: "محمد العتيبي")
    client_name: Optional[str] = None
    client_email: Optional[str] = None
    client_mobile: Optional[str] = None

def _norm_spaces(s: str) -> str:
    # يزيل مسافات مضاعفة ويقص الطرفين
    return " ".join((s or "").strip().split())

def _split_full_name(full_name: str):
    """
    يقسم الاسم الكامل لأول كلمة = fname والباقي = lname.
    أمثلة:
      "محمد العتيبي" -> ("محمد", "العتيبي")
      "عبدالرحمن بن خلف العلف" -> ("عبدالرحمن", "بن خلف العلف")
    """
    full = _norm_spaces(full_name)
    parts = full.split(" ", 1)
    if len(parts) == 1:
        return parts[0], ""  # لو حصل اسم واحد فقط
    return parts[0], parts[1]

def _get_doctor_by_full_name_or_404(full_name: str) -> Dict[str, Any]:
    """
    يبحث في جدول doctors بالمطابقة الدقيقة:
      fname == الجزء الأول
      lname == باقي الاسم
    لو ما لقاها، يحاول fallback بـ ilike على الاثنين معًا.
    """
    f, l = _split_full_name(full_name)
    # 1) مطابقة دقيقة
    rows = supa_select("doctors", {
        "select": "id,fname,lname",
        "fname": f"eq.{f}",
        "lname": f"eq.{l}",
        "limit": "1"
    })
    if rows:
        return rows[0]

    # 2) fallback مرن (يلتقط اختلافات بسيطة في المسافات/الصياغة)
    #   - نجيب أعلى 10 أسماء قريبة بالـ ilike ثم نفلتر في البايثون بتطابق كامل بعد التطبيع
    candidates = supa_select("doctors", {
        "select": "id,fname,lname",
        "or": f"(fname.ilike.*{f}*,lname.ilike.*{l}*)",
        "order": "id.asc",
        "limit": "10"
    })
    target = _norm_spaces(full_name)
    for r in candidates:
        composed = _norm_spaces(f"{r.get('fname','')} {r.get('lname','')}")
        if composed == target:
            return r

    raise HTTPException(404, "لم يتم العثور على الطبيب بالاسم الكامل المرسل")

# ====== Favorites: toggle ======
from pydantic import BaseModel
from typing import Optional

class ToggleFavoriteIn(BaseModel):
    doctor_id: int
    # اختياري لو حابب نخزنها مع السجل الجديد
    client_name: Optional[str] = None
    client_mobile: Optional[str] = None

@app.post("/api/favorites/toggle")
def toggle_favorite(body: ToggleFavoriteIn, payload=Depends(require_scopes(["user"]))):
    """
    يبدّل حالة المفضلة لطبيب معيّن للعميل (حسب التوكن).
    - لو السجل موجود (client_email + doctor_id) => نحذفه (is_favorite=false)
    - لو غير موجود => نضيفه (is_favorite=true)
    """
    client_email = payload.get("sub")
    if not client_email:
        raise HTTPException(401, "Missing client identity")

    # 1) تحقّق من وجود الطبيب (وحضّر الاسم للتخزين)
    doc_rows = supa_select("doctors", {**eq("id", body.doctor_id), "select": "id,fname,lname", "limit": "1"})
    if not doc_rows:
        raise HTTPException(404, "Doctor not found")
    doc = doc_rows[0]
    doc_full_name = f"{doc.get('fname','').strip()} {doc.get('lname','').strip()}".strip() or None

    # 2) هل المفضلة موجودة؟
    exists = supa_select("favorites", {
        "select": "id",
        **eq("client_email", client_email),
        **eq("doctor_id", body.doctor_id),
        "limit": "1"
    })

    if exists:
        # 3a) احذف = إلغاء المفضلة
        fav_id = exists[0]["id"]
        supa_delete("favorites", eq("id", fav_id))
        return {
            "message": "تم حذف الطبيب من المفضلة",
            "doctor_id": body.doctor_id,
            "is_favorite": False
        }

    # 3b) أضِف = تفعيل المفضلة
    rec = {
        "client_name":  (body.client_name or "").strip() or None,
        "client_email": client_email,
        "client_mobile": (body.client_mobile or "").strip() or None,
        "doctor_id": body.doctor_id,
        "doctor_name": doc_full_name,
        "created_at": iso(now_utc()),
    }
    try:
        supa_insert("favorites", rec)
        return {
            "message": "تمت إضافة الطبيب إلى المفضلة",
            "doctor_id": body.doctor_id,
            "is_favorite": True
        }
    except Exception as e:
        print("[favorites:toggle] insert failed:", e)
        raise HTTPException(400, "تعذر تعديل حالة المفضلة")

@app.post("/api/favorites/add-by-name")
def add_favorite_by_doctor_full_name(body: FavoriteByNameIn, payload=Depends(require_scopes(["user"]))):
    """
    يستقبل الاسم الكامل للطبيب فقط من الموبايل، ويضيفه للمفضلة:
      - يعمل lookup في جدول doctors (fname/lname) ويجيب id
      - يسجل في جدول favorites: client_* + doctor_id + doctor_name (نفس الاسم الكامل المرسل)
    """
    if not body.doctor_full_name or not _norm_spaces(body.doctor_full_name):
        raise HTTPException(422, "أرسل doctor_full_name")

    # 1) هات الدكتور بالاسم الكامل
    d = _get_doctor_by_full_name_or_404(body.doctor_full_name)

    # 2) إدراج المفضلة
    rec = {
        "client_name":  (body.client_name or "").strip() or None,
        "client_email": (body.client_email or "").strip() or None,
        "client_mobile": (body.client_mobile or "").strip() or None,
        "doctor_id": d["id"],
        "doctor_name": _norm_spaces(body.doctor_full_name),
        "created_at": iso(now_utc()),
    }
    try:
        saved = supa_insert("favorites", rec)
        return {"message": "تمت الإضافة إلى المفضلة", "data": saved}
    except Exception as e:
        print("[favorites:add-by-name] insert failed:", e)
        raise HTTPException(400, "تعذر إضافة المفضلة")

@app.get("/api/favorites/by-contact")
def favorites_by_contact(
    payload=Depends(require_scopes(["user"])),
    select: str = "*",
    client_mobile: Optional[str] = None,
    client_email: Optional[str] = None,
    order: str = "created_at.desc",
    limit: int = 100,
    offset: int = 0,
):
    """
    يرجّع مفضلات عميل بالموبايل/الإيميل.
    يدعم تمثيل معاملات PostgREST:
      ?client_mobile=eq.+9665...
      ?client_email=ilike.*@gmail.com
    ولو تبعت القيمة بدون معامل هنضيف eq. تلقائيًا.
    """
    if not client_mobile and not client_email:
        raise HTTPException(400, "أرسل client_mobile أو client_email على الأقل")

    def _ensure_op(v: Optional[str]) -> Optional[str]:
        if not v: return v
        ops = ("eq.","neq.","gt.","gte.","lt.","lte.","like.","ilike.","is.","in.",
               "cs.","cd.","sl.","sr.","nxr.","nxl.","adj.","ov.","fts(","plfts(","phfts(","wfts(")
        vv = v.strip()
        return vv if vv.startswith(ops) else "eq." + vv

    params = {
        "select": select,
        "order": order,
        "limit": str(limit),
        "offset": str(offset),
    }
    if client_mobile:
        params["client_mobile"] = _ensure_op(client_mobile)
    if client_email:
        params["client_email"] = _ensure_op(client_email)

    rows = supa_select("favorites", params)
    return {"message": "Favorites fetched successfully", "count": len(rows), "data": rows}

# ====== Terms AR/EN ======
TERMS_AR = """
مقدمة
مرحبًا بك في تطبيق Binrushd Medical Center، التطبيق الرسمي لمركز بن رشد التخصصي للعيون. باستخدامك لهذا التطبيق، فإنك توافق على الشروط والأحكام التالية، لذا يُرجى قراءتها بعناية قبل الاستخدام.

1. الهدف من التطبيق
يتيح التطبيق للمستخدمين:

التعرف على خدمات المركز وأقسامه الطبية.

استعراض معلومات الأطباء والمواعيد المتاحة.

حجز المواعيد وإرسال طلبات الحجز إلكترونيًا.

2. الاستخدام المسموح

يلتزم المستخدم باستخدام التطبيق لأغراض شخصية فقط.

يُمنع استخدام التطبيق لأي غرض تجاري أو دعائي أو غير قانوني.

يجب تقديم معلومات صحيحة ودقيقة عند التسجيل أو الحجز.

3. الخصوصية وحماية البيانات

يلتزم مركز بن رشد بالحفاظ على سرية بيانات المستخدم وعدم مشاركتها مع أي طرف ثالث إلا عند الضرورة لتقديم الخدمة أو بناءً على المتطلبات القانونية.

يحتفظ المركز بحق استخدام بيانات الاستخدام لتحسين الخدمات وتجربة المستخدم.

4. المواعيد والخدمات الطبية

تأكيد الحجز لا يُعدّ تشخيصًا طبيًا ولا يضمن توافر الطبيب في جميع الأوقات.

يحتفظ المركز بحق تعديل أو إلغاء المواعيد عند الضرورة مع إخطار المستخدم.

5. حقوق الملكية الفكرية
جميع محتويات التطبيق (النصوص، الصور، الشعارات، التصميمات) مملوكة لمركز بن رشد ولا يجوز نسخها أو استخدامها دون إذن خطي مسبق.

6. التعديلات
يحق لمركز بن رشد تعديل هذه الشروط في أي وقت، وتعتبر النسخة المنشورة في التطبيق هي السارية وقت الاستخدام.

7. التواصل
للاستفسارات أو الدعم الفني، يمكن التواصل عبر البريد الإلكتروني: info@binrushd.net
"""

TERMS_EN = """
Introduction
Welcome to the Binrushd Medical Center mobile application — the official app of Binrushd Eye Specialty Center. By using this application, you agree to the following terms and conditions. Please read them carefully before using the app.

1. Purpose of the Application
This app allows users to:

Learn more about the medical services and departments of the center.

View doctors’ profiles and available appointment slots.

Book appointments and send booking requests electronically.

2. Permitted Use

The app is intended for personal, non-commercial use only.

You may not use the app for any unlawful or unauthorized purpose.

Users must provide accurate and truthful information when registering or booking.

3. Privacy and Data Protection

Binrushd Medical Center is committed to protecting user data and will not share it with third parties except when required to provide services or comply with legal obligations.

Usage data may be analyzed to improve the quality of services and user experience.

4. Appointments and Medical Services

Appointment booking does not constitute a medical diagnosis and does not guarantee doctor availability at all times.

The center reserves the right to modify or cancel appointments when necessary and will inform users accordingly.

5. Intellectual Property Rights
All content in the app (texts, images, logos, and designs) is owned by Binrushd Medical Center and may not be copied or reused without prior written consent.

6. Modifications
Binrushd Medical Center reserves the right to modify these terms at any time. The latest version published in the app shall be deemed the valid one.

7. Contact
For inquiries or support, please contact: info@binrushd.net
"""

@app.get("/api/terms")
def get_terms(lang: str = Query("ar", description="لغة الشروط: ar أو en")):
    if lang.lower() == "en":
        return {"language": "en", "title": "Terms and Conditions", "content": TERMS_EN.strip()}
    else:
        return {"language": "ar", "title": "الشروط والأحكام", "content": TERMS_AR.strip()}