File size: 38,156 Bytes
3e0ae6f
a4c12eb
 
 
 
 
 
 
d3e90bd
a4c12eb
 
3e0ae6f
 
d3e90bd
3e0ae6f
d3e90bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e0ae6f
 
 
 
 
 
 
a4c12eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3e90bd
 
 
 
 
 
 
 
 
 
 
a4c12eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e0ae6f
a4c12eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e0ae6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4c12eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
736aec5
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
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, StreamingResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from scalar_fastapi import get_scalar_api_reference
import json
import os
import requests
import threading
import unicodedata
from pathlib import Path
from huggingface_hub import HfApi, hf_hub_download
import re

# Arabic diacritics and character normalization using unicodedata
def normalize_arabic(text: str) -> str:
    # First, handle common character substitutions
    substitutions = {
        '\u0671': '\u0627',  # alef wasla -> alef
        '\u0622': '\u0627',  # alef madda -> alef
        '\u0623': '\u0627',  # alef hamza above -> alef
        '\u0625': '\u0627',  # alef hamza below -> alef
        '\u0649': '\u064A',  # alef maksura -> yeh
        '\u0640': '',        # tatweel (stretch) -> remove
    }
    for old_char, new_char in substitutions.items():
        text = text.replace(old_char, new_char)
    # Normalize to NFD to separate base characters and diacritics
    normalized = unicodedata.normalize('NFD', text)
    # Filter out non-spacing marks (category Mn) which includes all diacritics
    return ''.join(
        char for char in normalized
        if unicodedata.category(char) != 'Mn'
    )

# Edition to filename mapping
EDITION_FILENAMES = {
    'uthmani': 'uthmani.json',
    'en.sahih': 'en.sahih.json',
    'ar.muyassar': 'ar.muyassar.json'
}

app = FastAPI(
    title="Kalamalah Quran API", 
    description="Official Kalamalah API for accessing Quran text and audio recitations", 
    version="1.0.0",
    docs_url=None,  # Disable default Swagger UI
    redoc_url=None  # Disable default ReDoc
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow all origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Environment configuration
USE_HF_CDN = os.getenv("USE_HF_CDN", "false").lower() == "true"
HF_DATASET_URL = "Kalamalah/cdn" # This will be the repo_id
HF_TOKEN = os.getenv("HF_TOKEN")

api = HfApi(token=HF_TOKEN)

# Base paths
BASE_DIR = Path(__file__).parent.parent
CDN_DIR = BASE_DIR / "cdn"
API_DATA_DIR = CDN_DIR / "api_data"
TIMING_DIR = API_DATA_DIR / "timing"
RECITERS_DIR = CDN_DIR / "reciters" / "audio"
MUSHAFS_DIR = CDN_DIR / "mushafs"
PROFILES_DIR = CDN_DIR / "reciters" / "profiles-images"
ATHAN_DIR = CDN_DIR / "reciters" / "athan"
BACKGROUND_AUDIO_DIR = CDN_DIR / "background_audio"
FONTS_DIR = CDN_DIR / "fonts"

# Simple keep-alive function using threading.Timer
def keep_alive():
    # Just a simple log to keep the app awake
    print("Kalamalah API keep-alive tick")
    # Schedule next tick in 20 seconds
    threading.Timer(20.0, keep_alive).start()

# Start keep-alive on app startup
@app.on_event("startup")
async def startup_event():
    keep_alive()

# Reciter info (based on existing data with more details)
RECITERS = {
    "haitham-al-dukhin": {
        "name": "Haitham Al Dokhin",
        "arabic_name": "هيثم الدخين",
        "types": ["murattal"],
        "description": "Haitham Aldokhin is a renowned Quran reciter known for his emotional and powerful recitations. He shares religious teachings, sermons, and recitations across platforms like Instagram, TikTok, and Twitter. His content often includes live events, collaborations with other reciters, and promotes religious tours. He has a strong presence in Arabic-speaking Muslim communities, with notable appearances in Australia and Qatar. Through his recitations, Haitham Al Dakhin inspires not only the Islamic community but also individuals worldwide seeking enlightenment and harmony. His enduring legacy will continue to guide and illuminate future generations, showing that the impact of spirituality transcends time.\n\nهيثم الدخين قارئ قرآن مشهور معروف بتلاواته المؤثرة والقوية. يشارك التعاليم الدينية والمواعظ والتلاوات عبر منصات مثل إنستغرام وتيك توك وتويتر. تشتمل محتوياته غالباً على أحداث حية وتعاون مع قراء آخرين وترويج جولات دينية. له حضور قوي في المجتمعات الإسلامية الناطقة بالعربية مع ظهور بارز في أستراليا وقطر. من خلال تلاواته ، يلهم هيثم الدخين ليس فقط المجتمع الإسلامي ولكن أيضاً الأفراد في جميع أنحاء العالم الذين يسعون للتنوير والوئام. وسيواصل إرثه الدائم توجيه وإنارة الأجيال القادمة ، مبيناً أن تأثير الروحانية يتجاوز الزمن.",
        "profile_image": "haitham-dokin-profile.jpg"
    },
    "abdul-rashid-sofi": {
        "name": "Abdul-Rasheed Sofi",
        "arabic_name": "عبد الرشيد الصوفي",
        "types": ["murattal"],
        "description": "Abdul-Rasheed Sofi is a respected Quran reciter with a unique style of recitation.",
        "profile_image": "abdulrasheed-sofi-profile.jpg"
    },
    "yasser-al-dossari": {
        "name": "Yasser Al-Dossari",
        "arabic_name": "ياسر الدوسري",
        "types": ["murattal"],
        "description": "Yasser Al Dossari is born in Riyadh in 1981. After the Hifdh of the Holy Qur’an at the tender age of 15 under eminent and noted Shaykhs like Sheikh Bakri Tarabishi, and Sheikh Ibrahim Al Akhdar, Yasser Al-Dosari graduated from Faculty of Sharia Imam Muhammad bin Saud Islamic University.\n\nولد ياسر الدوسري في الرياض عام 1981. بعد حفظ القرآن الكريم في سن الخامسة عشرة على يد مشايخ بارزين ومشهورين مثل الشيخ بكري الطرابيشي والشيخ إبراهيم الأخضر ، تخرج ياسر الدوسري من كلية الشريعة جامعة الإمام محمد بن سعود الإسلامية.",
        "profile_image": "yasser-aldosari-profile.png"
    },
    "abdul-baset": {
        "name": "Abdul Baset",
        "arabic_name": "عبد الباسط عبد الصمد",
        "types": ["mujawwad", "murattal"],
        "description": "Abdulbasit Abdusamad is a renowned Qur'an reciter born in 1927 in a village called Almara'za in Egypt. He learned the Holy Qur’an at an early age from Shaykh Mohamed El Amir and later from Mohamed Selim Hamada. He entered the National Radio Station in 1951.\n\nعبد الباسط عبد الصمد قارئ قرآن كريم مشهور ولد عام 1927 بقرية المراعزة بمصر. تعلم القرآن الكريم في سن مبكرة على يد الشيخ محمد الأمير ثم على يد محمد سليم حمادة. دخل محطة الإذاعة الوطنية عام 1951.",
        "profile_image": "abdelbasset-profile.png"
    },
    "khalil-al-husary": {
        "name": "Khalil Al-Husary",
        "arabic_name": "محمود خليل الحصري",
        "types": ["murattal", "muallim","mujawwad","ijazah"],
        "description": "Mahmoud Al-Hussary is a renowned reciter of the Qur'an. He was born in a village called Shubra Al-Namlah in Tanta, Egypt. Mahmoud entered the Quran School at the age of four. At 8, he had already memorized the whole Qur'an and at 12, he had learned the ten recitations of the Qur'an from Al-Azhar in 1958.\n\nمحمود الحصري قارئ قرآن كريم مشهور. ولد في قرية تسمى شبرا النملة في طنطا بمصر. دخل محمود مدرسة القرآن في سن الرابعة. في سن الثامنة ، كان قد حفظ القرآن كاملاً وفي سن الثانية عشرة ، تعلم التلاوات العشر للقرآن من الأزهر عام 1958.",
        "profile_image": "mahmoud-khalil-al-hussary-profile.png"
    },
    "siddiq-minshawi": {
        "name": "Siddiq Minshawi",
        "arabic_name": "محمد صديق المنشاوي",
        "types": ["murattal", "kids-repeat"],
        "description": "Muhammad Siddiq Al-Minshawi, also simply known as Al-Minshawy or Menshawy, born in Upper Egypt, was a Qur'anic reciter and a Hafiz. He is of the same generation as Shaykh Kamil Yusuf al-Bahtimi, and, in fact, he was also a protégé of Shaykh Muhammad Salâmah.\n\nمحمد صديق المنشاوي ، المعروف أيضاً ببساطة بالمنشاوي ، ولد في صعيد مصر ، وكان قارئاً للقرآن وحافظاً. وهو من نفس جيل الشيخ كامل يوسف البهتيمي ، وفي الواقع كان أيضاً تلميذاً للشيخ محمد سلامة.",
        "profile_image": "mohamed-siddiq-el-minshawi-profile.png"
    },
    "hani-ar-rifai": {
        "name": "Hani Ar-Rifai",
        "arabic_name": "هاني الرفاعي",
        "types": ["murattal"],
        "description": "Sheikh Hani Ar-Rifai was born in 1974 in the city of Jeddah, Saudi Arabia. He is currently the Imam and the Khateeb of Anani’s mosque in Jeddah. He is well-known for his unique voice filled with emotion, which attracts many listeners to his recitations of the Holy Qur’an.\n\nولد الشيخ هاني الرفاعي في عام 1974 في مدينة جدة بالمملكة العربية السعودية. وهو حالياً إمام وخطيب مسجد عناني بجدة. يشتهر بصوته الفريد المليء بالعاطفة ، والذي يجذب الكثير من المستمعين لتلاواته للقرآن الكريم.",
        "profile_image": "hani-ar-rifai-profile.jpeg"
    },
    "abdurrahmaan-as-sudais": {
        "name": "Abdurrahmaan As-Sudais",
        "arabic_name": "عبد الرحمن السديس",
        "types": ["murattal"],
        "description": "Abdul Rahman Ibn Abdul Aziz as-Sudais (عبد الرحمن السديس) was born in the city of Qassim, Saudi Arabia in 1962 (1382 A.H). He's originally from the Anza clan. He had memorized the Qur'an by the age of 12 growing up in Riyadh. \n \n Al-Sudais studied at the Al Muthana Bin Harith Elementary School and later at the Riyadh Scientific Institution, from which he graduated in 1979 with an excellent grade. He obtained a degree in Sharia from Riyadh University in 1983 and became an IFK (Islamic Fundamental Knowledge) lecturer after the conclusion of his study. He obtained his Master's in Islamic fundamentals from the Sharia College of Imam Muhammad bin Saud Islamic University in 1987 and received his PhD in Islamic Sharia from Umm al-Qura University in 1995 while working there as an assistant professor after serving at Riyadh University. \n\n He is respected for his precise, controlled, and particularly emotional recitation of the Qur'an in accordance with Tajweed – the rules of beautiful recitation. He was particularly called upon in the Ramadan Taraweeh prayers of 2006 (1427 AH) to recite the last few surahs of the Qur'an as well as to deliver the closing dua, which was followed by millions of Muslims in Mecca and around the World via TV or radio.\n\n\nIn 2005, he received the Islamic Personality of the Year award in the 9th annual Dubai International Holy Qur’an Award. He is the leading Imam at Masjidil Haram, Makkah.",
        "profile_image": "abdul-rahman-al-sudais-profile.png" 
    },
    "maher-al-muaiqly": {
        "name": "Maher Al-Muaiqly",
        "arabic_name": "ماهر المعيقلي",
        "types": ["murattal"],
        "description": "Shaykh Maher ibn Hamad ibn Muaiqel al-Muaiqly al-Balawi was born in Madinah, Saudi Arabia, in 1969. He is a prominent Saudi Arabian Imam and Qur'an reciter and has served as an Imam at the Masjid al-Haram in Makkah.\n\nولد الشيخ ماهر بن حمد بن معيقل المعيقلي البلوي في المدينة المنورة بالمملكة العربية السعودية عام 1969. وهو إمام وقارئ قرآن سعودي بارز وعمل إماماً في المسجد الحرام بمكة المكرمة.",
        "profile_image": "Maher-al-Muaiqly-profile.png"
    },
    "ahmed-al-ajamy": {
        "name": "Ahmed Al-Ajamy",
        "arabic_name": "أحمد العجمي",
        "types": ["murattal"],
        "description": "Shaykh Ahmed Ibn Ali Ibn Mohammed Al Sulaiman Al Ajmy was born in 1968 in Khobar, Saudi Arabia. He is a renowned Qur'an Reciter. He completed his primary education at Al Mohammedia Primary School, located in the southern part of Khobar.\n\nولد الشيخ أحمد بن علي بن محمد السليمان العجمي عام 1968 بالخبر بالمملكة العربية السعودية. وهو قارئ قرآن مشهور. أكمل تعليمه الابتدائي في مدرسة المحمدية الابتدائية الواقعة في الجزء الجنوبي من الخبر.",
        "profile_image": "Ahmed-ibn-Ali-al-Ajmy-profile.png"
    },
    "al-huzaifi": {
        "name": "Al-Huzaifi",
        "arabic_name": "الحوذيفي",
        "types": ["ayah-by-ayah"],
        "description": "Al-Huzaifi is known for his ayah-by-ayah recitation style.",
        "profile_image": None
    },
    "mishary-rashid-alafasy": {
        "name": "Mishary Rashid Alafasy",
        "arabic_name": "مشاري راشد العفاسي",
        "types": [],
        "description": "Sheikh Mishary bin Rashid Al-Afasy or Mishary Rashid Ghareeb Mohammed Rashed Al-Afasy is a Kuwaiti international-renewed Qari, he was born in Kuwait on September 5th, 1976 ( Sunday 11th of Ramadan 1396 H).\n\nالشيخ مشاري بن راشد العفاسي أو مشاري راشد غريب محمد راشد العفاسي هو قارئ كويتي مشهور عالمياً ، ولد في الكويت في 5 سبتمبر 1976 (الأحد 11 رمضان 1396 هـ).",
        "profile_image": "mishary-rashid-alafasy-profile.jpeg"
    }
}

# Load surahs data
SURAHS_DATA = None
try:
    with open(API_DATA_DIR / "surahs.json", "r", encoding="utf-8") as f:
        SURAHS_DATA = json.load(f)
except Exception:
    pass

# Scalar documentation endpoint
@app.get("/docs", include_in_schema=False)
async def scalar_html():
    return get_scalar_api_reference(
        title=app.title,
        openapi_url=app.openapi_url,
    )

# Health check endpoint
@app.get("/health")
async def health_check():
    return {"status": "healthy"}

# Root endpoint
@app.get("/")
async def root():
    return {
        "message": "Welcome to Kalamalah Quran API!",
        "docs": "/docs",
        "endpoints": {
            "quran": "/api/quran/{language}/{surah_number}[/{ayah_number}]",
            "surahs_list": "/api/surahs",
            "search": "/api/search",
            "reciters": "/api/reciters",
            "reciter": "/api/reciters/{reciter_name}",
            "audio": "/api/{reciter_name}/{type}/{surah_number}",
            "timing": "/api/timing/{reciter_name}/{type}/{surah_number}",
            "mushaf": "/api/mushaf/{mushaf_name}/{page_number}"
        }
    }

# Get list of all surahs
@app.get("/api/surahs")
async def get_surahs():
    if USE_HF_CDN:
        try:
            local_path = hf_hub_download(
                repo_id=HF_DATASET_URL,
                filename="api_data/surahs.json",
                repo_type="dataset",
                token=HF_TOKEN
            )
            with open(local_path, "r", encoding="utf-8") as f:
                data = json.load(f)
            if data and data.get("code") == 200:
                return JSONResponse(content=data["data"])
            raise HTTPException(status_code=404, detail="Surahs data not found")
        except Exception as e:
            print(f"Error fetching surahs from HF CDN: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to fetch surahs from CDN: {e}")
    else:
        if SURAHS_DATA and SURAHS_DATA.get("code") == 200:
            return JSONResponse(content=SURAHS_DATA["data"])
        raise HTTPException(status_code=404, detail="Surahs data not found")

# Search Quran endpoint
@app.get("/api/search")
async def search_quran(
    query: str = Query(..., description="Search query"),
    edition: str = Query("uthmani", description="Edition to search in: uthmani, en.sahih, ar.muyassar"),
    surah_number: int | None = Query(None, description="Search in a specific surah (1-114), or leave empty to search entire Quran"),
    with_tashkeel: bool = Query(False, description="Search with tashkeel (diacritics) enabled")
):
    # Validate edition
    if edition not in EDITION_FILENAMES:
        raise HTTPException(status_code=400, detail="Invalid edition. Choose from: uthmani, en.sahih, ar.muyassar")
    
    # Validate surah number if provided
    if surah_number is not None and (surah_number < 1 or surah_number > 114):
        raise HTTPException(status_code=400, detail="Invalid surah number. Must be between 1 and 114.")
    
    # Determine surahs to search
    surahs_to_search = list(range(1, 115)) if surah_number is None else [surah_number]
    
    results = []
    filename = EDITION_FILENAMES[edition]
    
    # Normalize query if searching without tashkeel (only for Arabic editions)
    normalized_query = normalize_arabic(query) if not with_tashkeel and edition in ["uthmani", "ar.muyassar"] else query
    
    for surah_num in surahs_to_search:
        surah_path = API_DATA_DIR / "surah" / str(surah_num) / filename
        if not surah_path.exists():
            continue
        try:
            with open(surah_path, "r", encoding="utf-8") as f:
                data = json.load(f)
            if data.get("code") == 200:
                ayahs = data["data"]["ayahs"]
                for ayah in ayahs:
                    ayah_text = ayah["text"]
                    # Normalize ayah text if needed
                    text_to_search = normalize_arabic(ayah_text) if not with_tashkeel and edition in ["uthmani", "ar.muyassar"] else ayah_text
                    # Check if query is in text (case-insensitive)
                    if normalized_query.lower() in text_to_search.lower():
                        results.append({
                            "surah_number": surah_num,
                            "surah_name": data["data"]["name"],
                            "surah_english_name": data["data"]["englishName"],
                            "ayah_number": ayah["numberInSurah"],
                            "text": ayah_text,
                            "juz": ayah["juz"],
                            "page": ayah["page"]
                        })
        except Exception as e:
            print(f"Error processing surah {surah_num}: {e}")
            continue
    
    return JSONResponse(content={"results": results, "count": len(results)})

# Get list of reciters
@app.get("/api/reciters")
async def get_reciters():
    return JSONResponse(content=RECITERS)

# Get a specific reciter's info
@app.get("/api/reciters/{reciter_name}")
async def get_reciter(reciter_name: str):
    if reciter_name not in RECITERS:
        raise HTTPException(status_code=404, detail="Reciter not found")
    return JSONResponse(content=RECITERS[reciter_name])

# Get timing data
@app.get("/api/timing/{reciter_name}/{recitation_type}/{surah_number}")
async def get_timing_data(reciter_name: str, recitation_type: str, surah_number: int):
    if reciter_name not in RECITERS:
        raise HTTPException(status_code=404, detail="Reciter not found")
    
    surah_str_padded = str(surah_number).zfill(3)
    
    # Try local timing first
    local_path = TIMING_DIR / reciter_name / recitation_type / f"{surah_str_padded}.json"
    if local_path.exists():
        try:
            with open(local_path, "r", encoding="utf-8") as f:
                data = json.load(f)
            return JSONResponse(content=data)
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"Failed to read timing data: {e}")
    
    # Try HF CDN if USE_HF_CDN is true
    if USE_HF_CDN:
        try:
            filename = f"api_data/timing/{reciter_name}/{recitation_type}/{surah_str_padded}.json"
            local_path = hf_hub_download(
                repo_id=HF_DATASET_URL,
                filename=filename,
                repo_type="dataset",
                token=HF_TOKEN
            )
            with open(local_path, "r", encoding="utf-8") as f:
                data = json.load(f)
            return JSONResponse(content=data)
        except Exception as e:
            print(f"Error fetching timing data from HF CDN: {e}")
    
    raise HTTPException(status_code=404, detail="Timing data not found")

# Get Quran text
@app.get("/api/quran/{language}/{surah_number}")
@app.get("/api/quran/{language}/{surah_number}/{ayah_number}")
async def get_quran_text(language: str, surah_number: int, ayah_number: int = None):
    if surah_number < 1 or surah_number > 114:
        raise HTTPException(status_code=404, detail="Surah not found")

    if USE_HF_CDN:
        edition_map = {
            "ar": "uthmani.json",
            "en": "en.sahih.json",
            "tafsir": "ar.muyassar.json"
        }
        file_name = edition_map.get(language, f"{language}.json")
        
        try:
            local_path = hf_hub_download(
                repo_id=HF_DATASET_URL,
                filename=f"api_data/surah/{surah_number}/{file_name}",
                repo_type="dataset",
                token=HF_TOKEN
            )
            with open(local_path, "r", encoding="utf-8") as f:
                data = json.load(f)
            
            if ayah_number:
                if data.get("code") == 200:
                    ayahs = data["data"]["ayahs"]
                    if 1 <= ayah_number <= len(ayahs):
                        return JSONResponse(content=ayahs[ayah_number - 1])
                raise HTTPException(status_code=404, detail="Ayah not found")
            
            return JSONResponse(content=data.get("data", data))
        except Exception as e:
            print(f"Error fetching Quran text from HF CDN: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to fetch Quran text from CDN: {e}")
    else:
        surah_dir = API_DATA_DIR / "surah" / str(surah_number)
        if not surah_dir.exists():
            raise HTTPException(status_code=404, detail="Surah not found")

        edition_map = {
            "ar": "uthmani.json",
            "en": "en.sahih.json",
            "tafsir": "ar.muyassar.json"
        }
        file_name = edition_map.get(language, f"{language}.json")
        file_path = surah_dir / file_name

        if not file_path.exists():
            json_files = list(surah_dir.glob("*.json"))
            if json_files:
                file_path = json_files[0]
            else:
                raise HTTPException(status_code=404, detail=f"Edition {language} not found for this surah")

        try:
            with open(file_path, "r", encoding="utf-8") as f:
                data = json.load(f)

            if ayah_number:
                if data.get("code") == 200:
                    ayahs = data["data"]["ayahs"]
                    if 1 <= ayah_number <= len(ayahs):
                        return JSONResponse(content=ayahs[ayah_number - 1])
                raise HTTPException(status_code=404, detail="Ayah not found")

            return JSONResponse(content=data.get("data", data))
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))

# Get mushaf page
@app.api_route("/api/mushaf/{mushaf_name}/{page_number}", methods=["GET", "HEAD"], operation_id="getMushafPage")
async def get_mushaf_page(mushaf_name: str, page_number: int):
    if USE_HF_CDN:
        for ext in [".jpg", ".jpeg", ".png"]:
            filename = f"mushafs/{mushaf_name}/{page_number}{ext}"
            try:
                local_path = hf_hub_download(
                    repo_id=HF_DATASET_URL,
                    filename=filename,
                    repo_type="dataset",
                    token=HF_TOKEN
                )
                return FileResponse(local_path, media_type=f"image/{ext[1:]}")
            except Exception as e:
                print(f"Error fetching mushaf page from HF CDN: {e}")
                continue # Try next extension
        raise HTTPException(status_code=404, detail="Page not found")
    else:
        mushaf_dir = MUSHAFS_DIR / mushaf_name
        if not mushaf_dir.exists():
            raise HTTPException(status_code=404, detail="Mushaf not found")

        for ext in [".jpg", ".jpeg", ".png"]:
            page_path = mushaf_dir / f"{page_number}{ext}"
            if page_path.exists():
                return FileResponse(page_path, media_type=f"image/{ext[1:]}")

        raise HTTPException(status_code=404, detail="Page not found")

# Get reciter audio
@app.api_route("/api/{reciter_name}/{recitation_type}/{surah_number}", methods=["GET", "HEAD"], operation_id="getReciterAudio")
async def get_reciter_audio(reciter_name: str, recitation_type: str, surah_number: int):
    if reciter_name not in RECITERS:
        raise HTTPException(status_code=404, detail="Reciter not found")

    if recitation_type not in RECITERS[reciter_name]["types"]:
        raise HTTPException(status_code=404, detail="Recitation type not available for this reciter")

    if recitation_type == "ayah-by-ayah" and reciter_name != "al-huzaifi":
        raise HTTPException(status_code=400, detail="Ayah-by-ayah only available for Al-Huzaifi")

    surah_str_padded = str(surah_number).zfill(3)
    surah_str_normal = str(surah_number)

    # Try to serve from local files first
    possible_local_paths = [
        RECITERS_DIR / reciter_name / recitation_type / f"{surah_str_padded}.mp3",
        RECITERS_DIR / reciter_name / recitation_type / f"{surah_str_normal}.mp3",
    ]

    old_dir_names = {
        "yasser-al-dossari": "yasser_ad-dossary/mp3",
        "abdul-baset": "abdul_baset",
        "khalil-al-husary": "khalil_al_husary",
        "siddiq-minshawi": "siddiq_minshawi"
    }

    if reciter_name in old_dir_names:
        old_base_dir = RECITERS_DIR / old_dir_names[reciter_name]
        if (old_base_dir / recitation_type).exists():
            possible_local_paths.append(old_base_dir / recitation_type / f"{surah_str_padded}.mp3")
            possible_local_paths.append(old_base_dir / recitation_type / f"{surah_str_normal}.mp3")
        else:
            possible_local_paths.append(old_base_dir / f"{surah_str_padded}.mp3")
            possible_local_paths.append(old_base_dir / f"{surah_str_normal}.mp3")

    for audio_path in possible_local_paths:
        if audio_path.exists():
            return FileResponse(audio_path, media_type="audio/mpeg")

    # If not found locally and USE_HF_CDN is true, try to fetch from HF CDN
    if USE_HF_CDN:
        print(f"[DEBUG] USE_HF_CDN is True. HF_TOKEN present: {bool(HF_TOKEN)}")
        surah_str_padded = str(surah_number).zfill(3)
        filename = f"reciters/audio/{reciter_name}/{recitation_type}/{surah_str_padded}.mp3"
        print(f"[DEBUG] Attempting to fetch from HF CDN: {filename}")
        try:
            local_path = hf_hub_download(
                repo_id=HF_DATASET_URL,
                filename=filename,
                repo_type="dataset",
                token=HF_TOKEN
            )
            print(f"[DEBUG] Successfully downloaded {filename} to {local_path}")
            return FileResponse(local_path, media_type="audio/mpeg")
        except requests.exceptions.HTTPError as e:
            print(f"HTTP Error fetching from HF CDN: {e.response.status_code} - {e.response.text}")
            raise HTTPException(status_code=e.response.status_code, detail=f"Failed to fetch audio from CDN: {e.response.status_code}")
        except requests.exceptions.RequestException as e:
            print(f"Network Error fetching from HF CDN: {e}")
            raise HTTPException(status_code=500, detail=f"Network error fetching audio from CDN: {e}")
        except Exception as e:
            print(f"Error fetching audio from HF CDN: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to fetch audio from CDN: {e}")

    raise HTTPException(status_code=404, detail="Audio file not found")

# Get reciter profile image
@app.api_route("/api/reciter-profile/{reciter_name}", methods=["GET", "HEAD"], operation_id="getReciterProfile")
async def get_reciter_profile(reciter_name: str):
    if reciter_name not in RECITERS:
        raise HTTPException(status_code=404, detail="Reciter not found")
    
    reciter = RECITERS[reciter_name]
    if not reciter["profile_image"]:
        raise HTTPException(status_code=404, detail="Profile image not available for this reciter")
    
    profile_filename = reciter["profile_image"]
    
    if USE_HF_CDN:
        try:
            filename = f"reciters/profiles-images/{profile_filename}"
            local_path = hf_hub_download(
                repo_id=HF_DATASET_URL,
                filename=filename,
                repo_type="dataset",
                token=HF_TOKEN
            )
            # Determine media type based on extension
            ext = Path(profile_filename).suffix.lower()
            media_type = "image/jpeg" if ext in [".jpg", ".jpeg"] else "image/png"
            return FileResponse(local_path, media_type=media_type)
        except Exception as e:
            print(f"Error fetching profile image from HF CDN: {e}")
            # Fall back to local
            pass
    
    # Try local file
    profile_path = PROFILES_DIR / profile_filename
    if profile_path.exists():
        ext = profile_path.suffix.lower()
        media_type = "image/jpeg" if ext in [".jpg", ".jpeg"] else "image/png"
        return FileResponse(profile_path, media_type=media_type)
    
    raise HTTPException(status_code=404, detail="Profile image not found")

# Get list of available athan files
@app.get("/api/athan")
async def get_athan_list():
    athan_files = []
    if ATHAN_DIR.exists():
        for file in ATHAN_DIR.iterdir():
            if file.is_file() and file.suffix.lower() == ".mp3":
                athan_files.append(file.name)
    return JSONResponse(content=athan_files)

# Get athan audio
@app.api_route("/api/athan/{filename}", methods=["GET", "HEAD"], operation_id="getAthan")
async def get_athan(filename: str):
    # Sanitize filename to prevent path traversal
    safe_filename = Path(filename).name
    if not safe_filename.endswith(".mp3"):
        raise HTTPException(status_code=400, detail="Invalid file type")
    
    if USE_HF_CDN:
        try:
            hf_filename = f"reciters/athan/{safe_filename}"
            local_path = hf_hub_download(
                repo_id=HF_DATASET_URL,
                filename=hf_filename,
                repo_type="dataset",
                token=HF_TOKEN
            )
            return FileResponse(local_path, media_type="audio/mpeg")
        except Exception as e:
            print(f"Error fetching athan from HF CDN: {e}")
            # Fall back to local
            pass
    
    # Try local file
    athan_path = ATHAN_DIR / safe_filename
    if athan_path.exists():
        return FileResponse(athan_path, media_type="audio/mpeg")
    
    raise HTTPException(status_code=404, detail="Athan file not found")

# Get list of available background audio files
@app.get("/api/background-audio")
async def get_background_audio_list():
    background_files = []
    if BACKGROUND_AUDIO_DIR.exists():
        for file in BACKGROUND_AUDIO_DIR.iterdir():
            if file.is_file() and file.suffix.lower() == ".mp3":
                background_files.append(file.name)
    return JSONResponse(content=background_files)

# Get background audio
@app.api_route("/api/background-audio/{filename}", methods=["GET", "HEAD"], operation_id="getBackgroundAudio")
async def get_background_audio(filename: str):
    # Sanitize filename to prevent path traversal
    safe_filename = Path(filename).name
    if not safe_filename.endswith(".mp3"):
        raise HTTPException(status_code=400, detail="Invalid file type")
    
    if USE_HF_CDN:
        try:
            hf_filename = f"background_audio/{safe_filename}"
            local_path = hf_hub_download(
                repo_id=HF_DATASET_URL,
                filename=hf_filename,
                repo_type="dataset",
                token=HF_TOKEN
            )
            return FileResponse(local_path, media_type="audio/mpeg")
        except Exception as e:
            print(f"Error fetching background audio from HF CDN: {e}")
            # Fall back to local
            pass
    
    # Try local file
    background_path = BACKGROUND_AUDIO_DIR / safe_filename
    if background_path.exists():
        return FileResponse(background_path, media_type="audio/mpeg")
    
    raise HTTPException(status_code=404, detail="Background audio file not found")

# Get fonts CSS (like Google Fonts)
@app.get("/api/fonts.css")
async def get_fonts_css(family: str = None, display: str = "swap"):
    # Define available fonts (support both simple and neat names)
    available_fonts = {
        "kitab": {
            "family": "Kitab",
            "files": [
                ("Kitab-Regular.woff2", "woff2"),
                ("Kitab-Regular.ttf", "truetype")
            ],
            "local": ["kitab"]
        },
        "Kitab": {
            "family": "Kitab",
            "files": [
                ("Kitab-Regular.woff2", "woff2"),
                ("Kitab-Regular.ttf", "truetype")
            ],
            "local": ["kitab"]
        },
        "uthmani": {
            "family": "Uthmani",
            "files": [
                ("Uthmani-Regular.ttf", "truetype"),
                ("Uthmani-Regular.woff2", "woff2")
            ],
            "local": []
        },
        "Uthmani": {
            "family": "Uthmani",
            "files": [
                ("Uthmani-Regular.ttf", "truetype"),
                ("Uthmani-Regular.woff2", "woff2")
            ],
            "local": []
        },
        "sfPro": {
            "family": "SF-ProUI",
            "files": [
                ("SF-ProUI.ttf", "truetype"),
                ("SF-ProUI.woff2", "woff2")
            ],
            "local": []
        },
        "SF-ProUI": {
            "family": "SF-ProUI",
            "files": [
                ("SF-ProUI.ttf", "truetype"),
                ("SF-ProUI.woff2", "woff2")
            ],
            "local": []
        },
        "sfArabic": {
            "family": "SF-ArabicUI",
            "files": [
                ("SF-ArabicUI.ttf", "truetype"),
                ("SF-ArabicUI.woff2", "woff2")
            ],
            "local": []
        },
        "SF-ArabicUI": {
            "family": "SF-ArabicUI",
            "files": [
                ("SF-ArabicUI.ttf", "truetype"),
                ("SF-ArabicUI.woff2", "woff2")
            ],
            "local": []
        }
    }
    
    # Parse font families from query parameter
    selected_fonts = []
    seen_families = set()
    if family:
        # Split by | and clean up
        font_names = [f.strip() for f in family.split("|")]
        for font_name in font_names:
            if font_name in available_fonts:
                font_obj = available_fonts[font_name]
                if font_obj['family'] not in seen_families:
                    selected_fonts.append(font_obj)
                    seen_families.add(font_obj['family'])
    else:
        # If no family specified, return all unique fonts (only neat names)
        for font_key in ["Kitab", "Uthmani", "SF-ProUI", "SF-ArabicUI"]:
            selected_fonts.append(available_fonts[font_key])
    
    # Generate CSS
    css_parts = []
    for font in selected_fonts:
        src_parts = []
        # Add local references
        for local_name in font.get("local", []):
            src_parts.append(f'local("{local_name}")')
        # Add file references with absolute URL
        for filename, format_type in font["files"]:
            src_parts.append(f'url("https://api.kalamalah.com/api/fonts/{filename}") format("{format_type}")')
        
        font_face = f"""@font-face {{
    font-family: "{font['family']}";
    font-display: {display};
    src: {', '.join(src_parts)};
}}"""
        css_parts.append(font_face)
    
    css_content = "\n\n".join(css_parts)
    return Response(content=css_content, media_type="text/css")

# Get font file
@app.api_route("/api/fonts/{filename}", methods=["GET", "HEAD"], operation_id="getFontFile")
async def get_font_file(filename: str):
    # Sanitize filename to prevent path traversal
    safe_filename = Path(filename).name
    
    if USE_HF_CDN:
        try:
            hf_filename = f"fonts/{safe_filename}"
            local_path = hf_hub_download(
                repo_id=HF_DATASET_URL,
                filename=hf_filename,
                repo_type="dataset",
                token=HF_TOKEN
            )
            # Determine media type based on extension
            ext = Path(safe_filename).suffix.lower()
            if ext == ".woff2":
                media_type = "font/woff2"
            elif ext == ".ttf":
                media_type = "font/ttf"
            else:
                media_type = "application/octet-stream"
            return FileResponse(local_path, media_type=media_type)
        except Exception as e:
            print(f"Error fetching font from HF CDN: {e}")
            # Fall back to local
            pass
    
    # Try local file
    font_path = FONTS_DIR / safe_filename
    if font_path.exists():
        ext = font_path.suffix.lower()
        if ext == ".woff2":
            media_type = "font/woff2"
        elif ext == ".ttf":
            media_type = "font/ttf"
        else:
            media_type = "application/octet-stream"
        return FileResponse(font_path, media_type=media_type)
    
    raise HTTPException(status_code=404, detail="Font file not found")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)