File size: 40,063 Bytes
e8510d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import logging
import os
import sqlite3
import re
from datetime import datetime
import hashlib
import json
import math
from flask import Flask, jsonify, request
from flask_cors import CORS

# Import modules
from utils import date_to_words, custom_normalize, translate_date_to_words
from gematria import calculate_gematria, strip_diacritics
from deep_translator import GoogleTranslator

# --- Setup Logging ---
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

# --- Constants and Global Variables ---
DATABASE_FILE = 'gematria.db'
ELS_CACHE_DB = 'els_cache.db'
DATABASE_TIMEOUT = 60
ADJUSTMENT_CONSTANT = 137.035999177  # Use the more precise constant

# --- Available languages ---
LANGUAGES = {
    'English': 'en',
    'Arabic': 'ar',
    'German': 'de',
    'Spanish': 'es',
    'French': 'fr',
    'Hebrew': 'iw',  # Note: Google Translator uses 'iw' for Hebrew
    'Hindi': 'hi',
    'Italian': 'it',
    'Japanese': 'ja',
    'Korean': 'ko',
    'Dutch': 'nl',
    'Portuguese': 'pt',
    'Russian': 'ru',
    'Chinese (Simplified)': 'zh-CN',
    'Chinese (Traditional)': 'zh-TW',
}

# Initialize Flask app
app = Flask(__name__)
CORS(app)  # Enable Cross-Origin Resource Sharing

# --- Helper Functions ---
def get_query_hash(func, args, kwargs):
    """Generate a hash for caching query results"""
    key = (func.__name__, args, kwargs)
    logger.debug(f"Generating query hash for key: {key}")
    hash_value = hashlib.sha256(json.dumps(key).encode()).hexdigest()
    logger.debug(f"Generated hash: {hash_value}")
    return hash_value

def create_els_cache_table():
    """Create the ELS cache table if it doesn't exist"""
    if not os.path.exists(ELS_CACHE_DB):
        logger.debug(f"Creating ELS cache table in {ELS_CACHE_DB}")
        with sqlite3.connect(ELS_CACHE_DB) as conn:
            conn.execute('''
                CREATE TABLE IF NOT EXISTS els_cache (
                    query_hash TEXT PRIMARY KEY,
                    function_name TEXT,
                    args TEXT,
                    kwargs TEXT,
                    results TEXT
                )
            ''')
        logger.debug("ELS cache table created.")
    else:
        logger.debug(f"ELS cache table already exists in {ELS_CACHE_DB}")

def cached_process_json_files(func, *args, **kwargs):
    """Cache results of JSON file processing functions"""
    logger.debug(f"Entering cached_process_json_files with func: {func}, args: {args}, kwargs: {kwargs}")
    params = {
        "function": f"{func.__module__}.{func.__name__}"
    }
    arg_names = func.__code__.co_varnames[:func.__code__.co_argcount]
    for name, value in zip(arg_names, args):
        params[name] = value
    for name, value in kwargs.items():
        params[name] = value
    params_json = json.dumps(params)
    logger.debug(f"Parameters as JSON: {params_json}")
    query_hash = get_query_hash(func, params_json, "")
    create_els_cache_table()
    try:
        with sqlite3.connect(ELS_CACHE_DB, timeout=DATABASE_TIMEOUT) as conn:
            cursor = conn.cursor()
            cursor.execute(
                "SELECT results FROM els_cache WHERE query_hash = ?", (query_hash,)
            )
            result = cursor.fetchone()
            if result:
                logger.info(f"Cache hit for query: {query_hash}")
                logger.debug(f"Cached result: {result[0]}")
                return json.loads(result[0])
    except sqlite3.Error as e:
        logger.error(f"Database error checking cache: {e}")

    logger.info(f"Cache miss for query: {query_hash}")
    results = func(*args, **kwargs)
    logger.debug(f"Results from function call: {results}")

    try:
        with sqlite3.connect(ELS_CACHE_DB, timeout=DATABASE_TIMEOUT) as conn:
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO els_cache (query_hash, function_name, args, kwargs, results) VALUES (?, ?, ?, ?, ?)",
                (query_hash, params["function"], params_json, json.dumps({}), json.dumps(results)),
            )
            conn.commit()
            logger.debug("Cached results in database.")
    except sqlite3.Error as e:
        logger.error(f"Database error caching results: {e}")
    logger.debug(f"Exiting cached_process_json_files, returning: {results}")
    return results

def calculate_gematria_sum(text, date_words):
    """Calculate the gematria sum for input text and date words"""
    logger.debug(f"Entering calculate_gematria_sum with text: '{text}', date_words: '{date_words}'")
    if text or date_words:
        combined_input = f"{text} {date_words}"
        logger.info(f"Calculating Gematria sum for input: {combined_input}")
        numbers = re.findall(r'\d+', combined_input)
        logger.debug(f"Extracted numbers: {numbers}")
        text_without_numbers = re.sub(r'\d+', '', combined_input)
        logger.debug(f"Text without numbers: {text_without_numbers}")
        number_sum = sum(int(number) for number in numbers)
        logger.debug(f"Sum of numbers: {number_sum}")
        text_gematria = calculate_gematria(strip_diacritics(text_without_numbers))
        logger.debug(f"Gematria of text: {text_gematria}")
        total_sum = text_gematria + number_sum
        logger.debug(f"Calculated Gematria sum: {total_sum}")
        logger.debug(f"Exiting calculate_gematria_sum, returning: {total_sum}")
        return total_sum
    else:
        logger.debug("No input text or date words provided. Returning None.")
        return None

def get_first_els_result_genesis(gematria_sum, tlang="en"):
    """Gets the first ELS result from Genesis (book 1) using cached processing."""
    logger.debug(f"Entering get_first_els_result_genesis with gematria_sum: {gematria_sum}, tlang: {tlang}")
    import torah

    results = cached_process_json_files(
        torah.process_json_files,
        1,  # Only Genesis (book 1 to 1)
        1,  # Only Genesis (book 1 to 1)
        gematria_sum,  # Use gematria sum as step
        "1,-1",  # Default rounds_combination
        0,  # length
        tlang,
        True,  # strip_spaces
        True,  # strip_in_braces
        True,  # strip_diacritics_chk
    )

    if results:
        result = results[0]
        # Calculate gematria sum if not already present
        if "result_sum" not in result:
            result["result_sum"] = calculate_gematria(result["result_text"])

        # Add standard fields expected from daily_psalm
        if "book" not in result:
            result["book"] = "Torah 1."
        if "title" not in result:
            result["title"] = "Genesis"
        if "source_language" not in result:
            result["source_language"] = "iw"
        if "translated_text" not in result:
            result["translated_text"] = ""
        # Add step field to match expected structure in /api/all endpoint
        if "step" not in result:
            result["step"] = gematria_sum  # Use the provided gematria_sum as the step value

        logger.debug(f"First ELS result from Genesis: {result}")
        logger.debug(f"Exiting get_first_els_result_genesis, returning: {result}")
        return result
    else:
        logger.debug("No ELS results found in Genesis.")
        logger.debug("Exiting get_first_els_result_genesis, returning: None")
        return None

def get_first_els_result_matthew(gematria_sum, tlang="en"):
    """Gets the first ELS result from Matthew (book 40) using cached processing."""
    logger.debug(f"Entering get_first_els_result_matthew with gematria_sum: {gematria_sum}, tlang: {tlang}")
    import bible
    results = cached_process_json_files(
        bible.process_json_files,
        40, 40,  # Only Matthew (book 40 to 40)
        gematria_sum,  # Use gematria sum as step
        "1,-1",  # Default rounds_combination
        0,  # length
        tlang,
        True,  # strip_spaces
        True,  # strip_in_braces
        True   # strip_diacritics_value
    )
    
    if results:
        logger.debug(f"Got {len(results)} ELS results from Matthew")
        # Match daily_psalm by selecting the round 1 result first
        round_1_results = [r for r in results if r.get('round') == 1]
        if round_1_results:
            result = round_1_results[0]
            logger.debug(f"Selected round 1 result: {result}")
        else:
            result = results[0]
            logger.debug(f"No round 1 results found, selected first result: {result}")
            
        # Calculate gematria sum if not already present
        if 'result_sum' not in result:
            result['result_sum'] = calculate_gematria(result['result_text'])
        
        # Add standard fields expected from daily_psalm
        if 'book' not in result and 'book_title' in result:
            result['book'] = result['book_title']
        elif 'book' not in result and 'book_id' in result:
            result['book'] = f"Bible {result['book_id']}"
        if 'title' not in result and 'book_title' in result:
            result['title'] = result['book_title']
        elif 'title' not in result:
            result['title'] = "Matthew"
        if 'source_language' not in result:
            result['source_language'] = 'el'  # Greek for New Testament
        if 'translated_text' not in result:
            result['translated_text'] = ''
        
        logger.debug(f"First ELS result from Matthew: {result}")
        logger.debug(f"Exiting get_first_els_result_matthew, returning: {result}")
        return result
    else:
        logger.debug("No ELS results found in Matthew.")
        logger.debug("Exiting get_first_els_result_matthew, returning: None")
        return None

def find_shortest_psalm_match(gematria_sum):
    """Finds the shortest Psalm entry in gematria.db."""
    logger.debug(f"Entering find_shortest_psalm_match with gematria_sum: {gematria_sum}")
    with sqlite3.connect(DATABASE_FILE) as conn:
        cursor = conn.cursor()
        cursor.execute('''
            SELECT words, chapter, verse
            FROM results
            WHERE gematria_sum = ? AND book = 'Psalms'
            ORDER BY LENGTH(words) ASC
            LIMIT 1
        ''', (gematria_sum,))
        result = cursor.fetchone()
        if result:
            # Create a proper dictionary to return
            psalm_match = {"words": result[0], "chapter": result[1], "verse": result[2], "phrase_length": None}
            logger.debug(f"Shortest Psalm match found: {result}")
            logger.debug(f"Exiting find_shortest_psalm_match, returning: {psalm_match}")
            return psalm_match

        logger.debug("No matching Psalm found.")
        logger.debug(f"Exiting find_shortest_psalm_match, returning: None")
        return None

def find_shortest_sura_match(gematria_sum):
    """Finds the shortest Sura entry in abjad.db."""
    logger.debug(f"Entering find_shortest_sura_match with gematria_sum: {gematria_sum}")
    import quran
    return quran.find_shortest_sura_match(gematria_sum, db_file='abjad.db')

def find_shortest_bible_match(gematria_sum):
    """Finds the shortest Bible verse in Revelation that matches the given gematria sum."""
    logger.debug(f"Finding shortest Bible match for gematria sum: {gematria_sum} in bible.db")
    try:
        with sqlite3.connect("bible.db") as conn:
            cursor = conn.cursor()
            cursor.execute('''
                SELECT words, book, chapter, verse, phrase_length, word_position
                FROM results
                WHERE gematria_sum = ? AND book = 'Revelation'
                ORDER BY LENGTH(words) ASC
                LIMIT 1
            ''', (gematria_sum,))
            
            result = cursor.fetchone()
            
            if result:
                logger.debug(f"Found Bible match: {result}")
                return {
                    "words": result[0],
                    "book": result[1],
                    "chapter": result[2],
                    "verse": result[3],
                    "phrase_length": result[4],
                    "word_position": result[5] if len(result) > 5 else None
                }
            else:
                logger.debug(f"No matching verse found in Revelation for gematria sum: {gematria_sum}")
                return None
                
    except sqlite3.Error as e:
        logger.error(f"Database error when finding Bible match: {e}")
        return None
    except Exception as e:
        logger.error(f"Unexpected error when finding Bible match: {e}")
        return None

# --- API Routes ---

@app.route('/')
def index():
    """API information endpoint"""
    return jsonify({
        "name": "Daily Psalms API",
        "version": "1.0",
        "endpoints": {
            "/api/psalm": "Find daily psalm",
            "/api/sura": "Find daily quran sura",
            "/api/bible": "Find daily bible verse",
            "/api/all": "Find all results (psalm, sura, bible) in a single request",
            "/api/languages": "List available languages"
        }
    })

@app.route('/api/languages')
def get_languages():
    """Return the list of available languages"""
    return jsonify(LANGUAGES)

@app.route('/api/psalm', methods=['GET'])
def get_psalm():
    """Find a daily psalm based on name and date"""
    name = request.args.get('name', '')
    date_str = request.args.get('date', datetime.today().strftime('%Y-%m-%d'))
    adjusted_sum = request.args.get('adjusted_sum', 'true').lower() == 'true'
    language_display = request.args.get('language', 'English')
    
    try:
        # Convert date string to datetime
        date = datetime.strptime(date_str, "%Y-%m-%d")
        
        # Get language code
        language_code = LANGUAGES.get(language_display, 'en')
        
        # Get date in words and translate if needed
        if language_display == "English":
            date_words = date_to_words(date_str)
        else:
            try:
                date_words = translate_date_to_words(date, lang=language_code)
            except Exception as e:
                logger.warning(f"Failed to translate date to {language_display}, falling back to English: {e}")
                date_words = date_to_words(date_str)
        
        # If name is provided, translate it too
        if name and language_display != "English":
            try:
                translator = GoogleTranslator(source='auto', target=language_code)
                name = translator.translate(name)
            except Exception as e:
                logger.warning(f"Failed to translate name: {e}")
        
        # Calculate initial gematria sum
        initial_gematria_sum = calculate_gematria_sum(name, date_words)
        if initial_gematria_sum is None:
            return jsonify({"error": "Could not calculate initial Gematria sum"}), 400
        
        # Adjust gematria sum if requested
        if adjusted_sum:
            adjusted_sum_value = initial_gematria_sum + (initial_gematria_sum / ADJUSTMENT_CONSTANT)
            initial_gematria_sum = math.ceil(adjusted_sum_value)
            logger.debug(f"Adjusted Gematria Sum (using formula): {initial_gematria_sum}")
        
        # Get ELS result from Genesis (exactly like in daily_psalm)
        logger.debug(f"Entering get_first_els_result_genesis with gematria_sum: {initial_gematria_sum}, tlang: en")
        els_result = get_first_els_result_genesis(initial_gematria_sum, tlang='en')
        if not els_result:
            logger.debug("No ELS result found in Genesis.")
            return jsonify({"error": "No ELS result found in Genesis"}), 404
        
        # Calculate gematria sum for ELS result
        els_gematria_sum = calculate_gematria(els_result['result_text'])
        logger.debug(f"ELS Gematria sum: {els_gematria_sum}")
        
        # Find matching psalm
        logger.debug(f"Entering find_shortest_psalm_match with gematria_sum: {els_gematria_sum}")
        psalm_match = find_shortest_psalm_match(els_gematria_sum)
        if not psalm_match:
            logger.debug("No matching Psalm found.")
            return jsonify({"error": "No matching Psalm found for the ELS result"}), 404
        
        logger.debug(f"Psalm Match result: {psalm_match}")
        
        # Create the response
        response = {
            "input": {
                "name": name,
                "date": date_str,
                "date_words": date_words,
                "language": language_display,
                "language_code": language_code,
                "initial_gematria_sum": initial_gematria_sum
            },
            "els_result": {
                "text": els_result['result_text'],
                "step": els_result.get('step', 0),  # Default to 0 if step is not present
                "book": els_result.get('title', "Genesis"),
                "gematria_sum": els_result.get('result_sum', els_gematria_sum)
            },
            "psalm": {
                "words": psalm_match["words"],
                "chapter": psalm_match["chapter"],
                "verse": psalm_match["verse"],
                "reference": f"Psalms {psalm_match['chapter']}:{psalm_match['verse']}",
                "url": f"https://www.biblegateway.com/passage/?search=Psalms+{psalm_match['chapter']}&version=CJB"
            }
        }
        
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"Error finding psalm: {str(e)}", exc_info=True)
        return jsonify({"error": f"Error finding psalm: {str(e)}"}), 500

@app.route('/api/sura', methods=['GET'])
def get_sura():
    """Find a daily Quran sura based on name and date"""
    name = request.args.get('name', '')
    date_str = request.args.get('date', datetime.today().strftime('%Y-%m-%d'))
    adjusted_sum = request.args.get('adjusted_sum', 'true').lower() == 'true'
    language_display = request.args.get('language', 'English')
    
    try:
        # Import quran module
        import quran
        
        # Check if database is initialized
        with sqlite3.connect('abjad.db') as conn:
            cursor = conn.cursor()
            try:
                cursor.execute("SELECT COUNT(*) FROM results")
                count = cursor.fetchone()[0]
                
                if count == 0:
                    logger.warning("Quran database not initialized. Initializing database...")
                    # Initialize with a small number of entries
                    quran.initialize_quran_database('abjad.db', max_phrase_length=1)
            except sqlite3.OperationalError:
                logger.warning("Quran database not initialized. Initializing database...")
                # Initialize with a small number of entries
                quran.initialize_quran_database('abjad.db', max_phrase_length=1)
        
        # Convert date string to datetime
        date = datetime.strptime(date_str, "%Y-%m-%d")
        
        # Get language code
        language_code = LANGUAGES.get(language_display, 'en')
        
        # Get date in words and translate if needed
        if language_display == "English":
            date_words = date_to_words(date_str)
        else:
            try:
                date_words = translate_date_to_words(date, lang=language_code)
            except Exception as e:
                logger.warning(f"Failed to translate date to {language_display}, falling back to English: {e}")
                date_words = date_to_words(date_str)
        
        # If name is provided, translate it too
        if name and language_display != "English":
            try:
                translator = GoogleTranslator(source='auto', target=language_code)
                name = translator.translate(name)
            except Exception as e:
                logger.warning(f"Failed to translate name: {e}")
        
        # Calculate initial gematria sum
        initial_gematria_sum = calculate_gematria_sum(name, date_words)
        if initial_gematria_sum is None:
            return jsonify({"error": "Could not calculate initial Gematria sum"}), 400
        
        # Adjust gematria sum if requested
        if adjusted_sum:
            adjusted_sum_value = initial_gematria_sum + (initial_gematria_sum / ADJUSTMENT_CONSTANT)
            initial_gematria_sum = math.ceil(adjusted_sum_value)
            logger.debug(f"Adjusted Gematria Sum (using formula): {initial_gematria_sum}")
        
        # Get ELS result from Quran
        logger.debug(f"Finding ELS result in Quran with gematria_sum: {initial_gematria_sum}, tlang: en")
        els_result = quran.get_first_els_result_quran(initial_gematria_sum, tlang='en', cached_process_func=cached_process_json_files)
        if not els_result:
            logger.debug("No ELS result found in the Quran.")
            return jsonify({"error": "No ELS result found in the Quran"}), 404
        
        # Calculate gematria sum for ELS result
        els_gematria_sum = calculate_gematria(els_result['result_text'])
        logger.debug(f"ELS Gematria sum from Quran: {els_gematria_sum}")
        
        # Find matching sura
        logger.debug(f"Finding shortest Sura match with gematria_sum: {els_gematria_sum}")
        sura_match = find_shortest_sura_match(els_gematria_sum)
        if not sura_match:
            logger.debug("No matching Sura found.")
            return jsonify({"error": "No matching Sura found for the ELS result"}), 404
        
        logger.debug(f"Sura Match result: {sura_match}")
        
        # Create the response
        response = {
            "input": {
                "name": name,
                "date": date_str,
                "date_words": date_words,
                "language": language_display,
                "language_code": language_code,
                "initial_gematria_sum": initial_gematria_sum
            },
            "els_result": {
                "text": els_result['result_text'],
                "step": els_result['step'],
                "start_sura": els_result.get('start_sura'),
                "start_sura_name": els_result.get('start_sura_name'),
                "start_verse": els_result.get('start_verse'),
                "end_sura": els_result.get('end_sura'),
                "end_sura_name": els_result.get('end_sura_name'),
                "end_verse": els_result.get('end_verse'),
                "gematria_sum": els_gematria_sum
            },
            "sura": {
                "book": sura_match["book"],
                "chapter": sura_match["chapter"],
                "verse": sura_match["verse"],
                "words": sura_match["words"],
                "reference": f"Quran {sura_match['chapter']}:{sura_match['verse']}",
                "url": f"https://quran.com/{sura_match['chapter']}/{sura_match['verse']}"
            }
        }
        
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"Error finding sura: {str(e)}", exc_info=True)
        return jsonify({"error": f"Error finding sura: {str(e)}"}), 500

@app.route('/api/bible', methods=['GET'])
def get_bible():
    """Find a daily Bible verse based on name and date"""
    name = request.args.get('name', '')
    date_str = request.args.get('date', datetime.today().strftime('%Y-%m-%d'))
    adjusted_sum = request.args.get('adjusted_sum', 'true').lower() == 'true'
    language_display = request.args.get('language', 'English')
    
    try:
        # Import bible module
        import bible
        
        # Convert date string to datetime
        date = datetime.strptime(date_str, "%Y-%m-%d")
        
        # Get language code
        language_code = LANGUAGES.get(language_display, 'en')
        
        # Get date in words and translate if needed
        if language_display == "English":
            date_words = date_to_words(date_str)
        else:
            try:
                date_words = translate_date_to_words(date, lang=language_code)
            except Exception as e:
                logger.warning(f"Failed to translate date to {language_display}, falling back to English: {e}")
                date_words = date_to_words(date_str)
        
        # If name is provided, translate it too
        if name and language_display != "English":
            try:
                translator = GoogleTranslator(source='auto', target=language_code)
                name = translator.translate(name)
            except Exception as e:
                logger.warning(f"Failed to translate name: {e}")
        
        # Calculate initial gematria sum
        initial_gematria_sum = calculate_gematria_sum(name, date_words)
        if initial_gematria_sum is None:
            return jsonify({"error": "Could not calculate initial Gematria sum"}), 400
        
        # Adjust gematria sum if requested
        if adjusted_sum:
            adjusted_sum_value = initial_gematria_sum + (initial_gematria_sum / ADJUSTMENT_CONSTANT)
            initial_gematria_sum = math.ceil(adjusted_sum_value)
            logger.debug(f"Adjusted Gematria Sum (using formula): {initial_gematria_sum}")
        
        # Get ELS result from Matthew
        logger.debug(f"Entering get_first_els_result_matthew with gematria_sum: {initial_gematria_sum}, tlang: en")
        els_result = get_first_els_result_matthew(initial_gematria_sum, tlang='en')
        if not els_result:
            logger.debug("No ELS result found in Matthew.")
            return jsonify({"error": "No ELS result found in Matthew"}), 404
        
        # Calculate gematria sum for ELS result
        els_gematria_sum = calculate_gematria(els_result['result_text'])
        logger.debug(f"ELS Gematria sum from Matthew: {els_gematria_sum}")
        
        # Use the ELS result to find a matching verse in Revelation
        bible_match = find_shortest_bible_match(els_gematria_sum)
        if not bible_match:
            logger.debug("No matching verse found in Revelation.")
            return jsonify({"error": "No matching verse found in Revelation for the ELS result"}), 404
        
        logger.debug(f"Bible Match result: {bible_match}")
        
        # Find the book of Revelation for the response
        logger.debug(f"Finding book of Revelation (book ID 66)")
        book_id = 66  # Revelation is typically book ID 66
        book_data = bible.process_bible_files(book_id, book_id)
        
        if not book_data or book_id not in book_data:
            return jsonify({"error": "Could not find the book of Revelation"}), 404
        
        # Use the chapter from the match
        chapter_index = bible_match["chapter"]
        
        # Get chapter data
        chapter = book_data[book_id]['text'][chapter_index - 1]
        
        # Create the response
        response = {
            "input": {
                "name": name,
                "date": date_str,
                "date_words": date_words,
                "language": language_display,
                "language_code": language_code,
                "initial_gematria_sum": initial_gematria_sum
            },
            "els_result": {
                "text": els_result['result_text'],
                "step": els_result['step'],
                "book": "Matthew",
                "gematria_sum": els_gematria_sum
            },
            "bible": {
                "book_id": book_id,
                "book_name": book_data[book_id]['title'],
                "chapter": chapter_index,
                "verse": bible_match["verse"],
                "words": bible_match["words"],
                "phrase_length": bible_match["phrase_length"],
                "word_position": bible_match["word_position"],
                "num_verses": len(chapter),
                "reference": f"{book_data[book_id]['title']} {chapter_index}:{bible_match['verse']}",
                "url": f"https://www.biblegateway.com/passage/?search={book_data[book_id]['title']}+{chapter_index}&version=CJB"
            }
        }
        
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"Error finding bible verse: {str(e)}", exc_info=True)
        return jsonify({"error": f"Error finding bible verse: {str(e)}"}), 500

@app.route('/api/all', methods=['GET'])
def get_all():
    """Return results from psalm, sura and bible in a single request"""
    name = request.args.get('name', '')
    date_str = request.args.get('date', datetime.today().strftime('%Y-%m-%d'))
    adjusted_sum = request.args.get('adjusted_sum', 'true').lower() == 'true'
    language_display = request.args.get('language', 'English')
    
    try:
        # Convert date string to datetime
        date = datetime.strptime(date_str, "%Y-%m-%d")
        
        # Get language code
        language_code = LANGUAGES.get(language_display, 'en')
        
        # Get date in words and translate if needed
        if language_display == "English":
            date_words = date_to_words(date_str)
        else:
            try:
                date_words = translate_date_to_words(date, lang=language_code)
            except Exception as e:
                logger.warning(f"Failed to translate date to {language_display}, falling back to English: {e}")
                date_words = date_to_words(date_str)
        
        # If name is provided, translate it too
        translated_name = name
        if name and language_display != "English":
            try:
                translator = GoogleTranslator(source='auto', target=language_code)
                translated_name = translator.translate(name)
                logger.debug(f"Translated name in {language_display}: {translated_name}")
            except Exception as e:
                logger.warning(f"Failed to translate name: {e}")
        
        # Calculate initial gematria sum
        initial_gematria_sum = calculate_gematria_sum(translated_name, date_words)
        if initial_gematria_sum is None:
            return jsonify({"error": "Could not calculate initial Gematria sum"}), 400
        
        # Adjust gematria sum if requested
        if adjusted_sum:
            adjusted_sum_value = initial_gematria_sum + (initial_gematria_sum / ADJUSTMENT_CONSTANT)
            initial_gematria_sum = math.ceil(adjusted_sum_value)
            logger.debug(f"Adjusted Gematria Sum (using formula): {initial_gematria_sum}")
        
        # Prepare response dictionary with input data
        response = {
            "input": {
                "name": name,
                "date": date_str,
                "date_words": date_words,
                "language": language_display,
                "language_code": language_code,
                "initial_gematria_sum": initial_gematria_sum
            }
        }
        
        # Get Psalm result
        try:
            logger.debug(f"Getting psalm result with gematria_sum: {initial_gematria_sum}")
            # Get ELS result from Genesis
            logger.debug(f"Entering get_first_els_result_genesis with gematria_sum: {initial_gematria_sum}, tlang: en")
            genesis_result = get_first_els_result_genesis(initial_gematria_sum, tlang='en')
            if genesis_result and 'result_text' in genesis_result:
                logger.debug(f"First ELS result from Genesis: {genesis_result}")
                
                # Calculate gematria sum for ELS result
                genesis_gematria_sum = calculate_gematria(genesis_result['result_text'])
                logger.debug(f"ELS Gematria sum: {genesis_gematria_sum}")
                
                # Find matching psalm
                logger.debug(f"Entering find_shortest_psalm_match with gematria_sum: {genesis_gematria_sum}")
                psalm_match = find_shortest_psalm_match(genesis_gematria_sum)
                logger.debug(f"Psalm match result: {psalm_match}")
                if psalm_match and isinstance(psalm_match, dict):
                    response["psalm"] = {
                        "words": psalm_match.get("words", ""),
                        "chapter": psalm_match.get("chapter", 0),
                        "verse": psalm_match.get("verse", 0),
                        "reference": f"Psalms {psalm_match.get('chapter', 0)}:{psalm_match.get('verse', 0)}",
                        "url": f"https://www.biblegateway.com/passage/?search=Psalms+{psalm_match.get('chapter', 0)}&version=CJB",
                        "els_result": {
                            "text": genesis_result.get('result_text', ''),
                            "step": genesis_result.get('step', initial_gematria_sum),  # Use initial_gematria_sum as default
                            "book": genesis_result.get('title', "Genesis"),
                            "gematria_sum": genesis_result.get('result_sum', genesis_gematria_sum)
                        }
                    }
                else:
                    response["psalm"] = {
                        "error": "No matching Psalm found for the ELS result"
                    }
            else:
                response["psalm"] = {
                    "error": "No ELS result found in Genesis"
                }
        except Exception as e:
            logger.error(f"Error finding psalm: {str(e)}", exc_info=True)
            response["psalm"] = {
                "error": f"Error finding psalm: {str(e)}"
            }
        
        # Get Sura result
        try:
            logger.debug(f"Getting sura result with gematria_sum: {initial_gematria_sum}")
            import quran
            
            # Get ELS result from Quran
            logger.debug(f"Finding ELS result in Quran with gematria_sum: {initial_gematria_sum}, tlang: en")
            quran_result = quran.get_first_els_result_quran(initial_gematria_sum, tlang='en', cached_process_func=cached_process_json_files)
            if quran_result and 'result_text' in quran_result:
                logger.debug(f"First ELS result from Quran: {quran_result}")
                
                # Calculate gematria sum for ELS result
                quran_gematria_sum = calculate_gematria(quran_result['result_text'])
                logger.debug(f"ELS Gematria sum from Quran: {quran_gematria_sum}")
                
                # Find matching sura
                logger.debug(f"Finding shortest Sura match with gematria_sum: {quran_gematria_sum}")
                sura_match = find_shortest_sura_match(quran_gematria_sum)
                if sura_match:
                    response["sura"] = {
                        "book": sura_match["book"],
                        "chapter": sura_match["chapter"],
                        "verse": sura_match["verse"],
                        "words": sura_match["words"],
                        "reference": f"Quran {sura_match['chapter']}:{sura_match['verse']}",
                        "url": f"https://quran.com/{sura_match['chapter']}/{sura_match['verse']}",
                        "els_result": {
                            "text": quran_result['result_text'],
                            "step": quran_result['step'],
                            "start_sura": quran_result.get('start_sura'),
                            "start_sura_name": quran_result.get('start_sura_name'),
                            "start_verse": quran_result.get('start_verse'),
                            "end_sura": quran_result.get('end_sura'),
                            "end_sura_name": quran_result.get('end_sura_name'),
                            "end_verse": quran_result.get('end_verse'),
                            "gematria_sum": quran_gematria_sum
                        }
                    }
                else:
                    response["sura"] = {
                        "error": "No matching Sura found for the ELS result"
                    }
            else:
                response["sura"] = {
                    "error": "No ELS result found in the Quran"
                }
        except Exception as e:
            logger.error(f"Error finding sura: {str(e)}", exc_info=True)
            response["sura"] = {
                "error": f"Error finding sura: {str(e)}"
            }
        
        # Get Bible result
        try:
            logger.debug(f"Getting bible result with gematria_sum: {initial_gematria_sum}")
            import bible
            
            # Get ELS result from Matthew
            logger.debug(f"Entering get_first_els_result_matthew with gematria_sum: {initial_gematria_sum}, tlang: en")
            matthew_result = get_first_els_result_matthew(initial_gematria_sum, tlang='en')
            if matthew_result and 'result_text' in matthew_result:
                logger.debug(f"First ELS result from Matthew: {matthew_result}")
                
                # Calculate gematria sum for ELS result
                matthew_gematria_sum = calculate_gematria(matthew_result['result_text'])
                logger.debug(f"ELS Gematria sum from Matthew: {matthew_gematria_sum}")
                
                # Use the ELS result to find a matching verse in Revelation
                bible_match = find_shortest_bible_match(matthew_gematria_sum)
                if not bible_match:
                    logger.debug("No matching verse found in Revelation.")
                    response["bible"] = {
                        "error": "No matching verse found in Revelation for the ELS result"
                    }
                    # Skip the rest of the bible processing
                    return jsonify(response)
                
                logger.debug(f"Bible Match result: {bible_match}")
                
                # Find the book of Revelation for response
                logger.debug(f"Finding book of Revelation (book ID 66)")
                book_id = 66  # Revelation is typically book ID 66
                book_data = bible.process_bible_files(book_id, book_id)
                
                if book_data and book_id in book_data:
                    # Use the chapter from the match
                    chapter_index = bible_match["chapter"]
                    
                    # Get chapter data
                    chapter = book_data[book_id]['text'][chapter_index - 1]
                    
                    response["bible"] = {
                        "book_id": book_id,
                        "book_name": book_data[book_id]['title'],
                        "chapter": chapter_index,
                        "verse": bible_match["verse"],
                        "words": bible_match["words"],
                        "phrase_length": bible_match["phrase_length"],
                        "word_position": bible_match["word_position"],
                        "num_verses": len(chapter),
                        "reference": f"{book_data[book_id]['title']} {chapter_index}:{bible_match['verse']}",
                        "url": f"https://www.biblegateway.com/passage/?search={book_data[book_id]['title']}+{chapter_index}&version=CJB",
                        "els_result": {
                            "text": matthew_result['result_text'],
                            "step": matthew_result['step'],
                            "book": "Matthew",
                            "gematria_sum": matthew_gematria_sum
                        }
                    }
                else:
                    response["bible"] = {
                        "error": "Could not find the book of Revelation"
                    }
            else:
                response["bible"] = {
                    "error": "No ELS result found in Matthew"
                }
        except Exception as e:
            logger.error(f"Error finding bible verse: {str(e)}", exc_info=True)
            response["bible"] = {
                "error": f"Error finding bible verse: {str(e)}"
            }
        
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"Error in get_all: {str(e)}", exc_info=True)
        return jsonify({"error": f"Error getting combined results: {str(e)}"}), 500