File size: 44,757 Bytes
379c0ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, request, jsonify, send_file
import sqlite3
import json
import html
from datetime import datetime
import sys
import re
import time
from flask_cors import CORS

app = Flask(__name__, static_folder='.', static_url_path='')
CORS(app)

@app.route('/')
def index():
    return send_file('index.html')

@app.route('/reader')
def reader():
    return send_file('reader.html')

DB_PATH = "story-database.sqlite"

FTS_SPECIAL_PATTERN = re.compile(r'[()*:+|]|\b(AND|OR|NOT|NEAR)\b', re.IGNORECASE)
# Note: '-' is NOT special here. Hyphenated queries like "The-Golden-Mind-Control"
# are routed through the safe word-splitting path in _build_fts_unit, which treats
# '-' and '_' as word separators so they behave like "The Golden Mind Control".

def get_db_connection():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    # Performance pragmas for the server
    conn.execute("PRAGMA mmap_size = 4294967296;") # 4GB mmap
    conn.execute("PRAGMA cache_size = 20000;")     # Increase cache
    
    # Add REGEXP support
    def regexp(expr, item):
        if item is None:
            return False
        reg = re.compile(expr, re.IGNORECASE)
        return reg.search(item) is not None
    
    conn.create_function("REGEXP", 2, regexp)
    return conn

# Internal Settings
USE_SYNOPSIS_FALLBACK = False # If True, use story["synopsis"] if Intro chapter is missing

def parse_date_to_timestamp(date_str):
    if not date_str:
        return 0
    date_str = date_str.strip()
    try:
        dt = datetime.strptime(date_str, "%m-%d-%Y")
        return int(dt.timestamp())
    except:
        return 0

def normalize_date_for_sql(date_str, is_before=False):
    if not date_str: return None
    date_str = date_str.strip('"() ')
    if re.match(r'^\d{4}$', date_str):
        return f"{date_str}1231" if is_before else f"{date_str}0101"
    m = re.match(r'^(\d{1,2})-(\d{1,2})-(\d{4})$', date_str)
    if m:
        mm = m.group(1).zfill(2)
        dd = m.group(2).zfill(2)
        yyyy = m.group(3)
        return f"{yyyy}{mm}{dd}"
    m = re.match(r'^(\d{4})-(\d{1,2})-(\d{1,2})$', date_str)
    if m:
        yyyy = m.group(1)
        mm = m.group(2).zfill(2)
        dd = m.group(3).zfill(2)
        return f"{yyyy}{mm}{dd}"
    return None

def resolve_public_story_id(story_row):
    for key in ("url", "url_backup", "extra_url"):
        value = story_row[key] if key in story_row.keys() else ""
        if not value: continue
        match = re.search(r'item_id/(\d+)', value)
        if match: return match.group(1)
    base_id = str(story_row["base_id"])
    leading_digits = re.match(r'^(\d+)', base_id)
    return leading_digits.group(1) if leading_digits else base_id

def parse_query_to_groups(raw_query):
    if not raw_query: return []
    tokens = re.findall(r'"[^"]+"|[^\s|]+|\|', raw_query)
    expanded_tokens = []
    for t in tokens:
        if t == '|':
            expanded_tokens.append(t)
            continue
        is_quoted = t.startswith('"') and t.endswith('"')
        inner = t[1:-1] if is_quoted else t
        if '|' in inner:
            branches = [b.strip() for b in inner.split('|') if b.strip()]
            if is_quoted: expanded_tokens.append([f'"{b}"' for b in branches])
            else: expanded_tokens.append(branches)
        else:
            expanded_tokens.append(t)
    final_groups = []
    i = 0
    while i < len(expanded_tokens):
        t = expanded_tokens[i]
        if t == '|':
            i += 1
            continue
        current_group = t if isinstance(t, list) else [t]
        while i + 1 < len(expanded_tokens) and expanded_tokens[i+1] == '|':
            i += 2
            if i < len(expanded_tokens):
                next_t = expanded_tokens[i]
                if isinstance(next_t, list): current_group.extend(next_t)
                elif next_t != '|': current_group.append(next_t)
            else: break
        final_groups.append(current_group)
        i += 1
    return final_groups

def build_fts_query(raw_query):
    raw_query = (raw_query or '').strip()
    if not raw_query: return ''
    if re.search(r'\bAND\b', raw_query, re.IGNORECASE):
        tokens = re.findall(r'"[^"]+"|\S+', raw_query)
        parts = []
        current_part = []
        for token in tokens:
            if token.upper() == 'AND':
                if current_part:
                    parts.append(" ".join(current_part))
                    current_part = []
            else: current_part.append(token)
        if current_part: parts.append(" ".join(current_part))
        if len(parts) > 1:
            branches = []
            for p in parts:
                unit = _build_fts_unit(p)
                if unit: branches.append(f"({unit})")
            if branches: return " AND ".join(branches)
    return _build_fts_unit(raw_query)

def _build_fts_unit(raw_query):
    raw_query = raw_query.strip()
    if not raw_query: return ''
    if FTS_SPECIAL_PATTERN.search(raw_query) and '|' not in raw_query: return raw_query
    groups = parse_query_to_groups(raw_query)
    if not groups: return ''
    safe_terms = []
    for group in groups:
        unit_branches = []
        for term in group:
            if term.startswith('"') and term.endswith('"') and len(term) >= 2:
                phrase = term[1:-1].strip()
                if phrase: unit_branches.append(f'"{phrase}"')
                continue
            cleaned = re.sub(r'[^0-9A-Za-z]+', ' ', term).strip()  # '-' and '_' become word separators
            if not cleaned: continue
            parts = [f'{piece}*' for piece in cleaned.split()]
            if parts: unit_branches.append(" ".join(parts))
        if unit_branches:
            if len(unit_branches) > 1: safe_terms.append("(" + " OR ".join(unit_branches) + ")")
            else: safe_terms.append(unit_branches[0])
    return ' AND '.join(safe_terms)

def build_like_clause_groups(raw_query):
    raw_query = (raw_query or '').strip()
    if not raw_query: return []
    if re.search(r'\bAND\b', raw_query, re.IGNORECASE):
        tokens = re.findall(r'"[^"]+"|\S+', raw_query)
        parts = []
        current_part = []
        for token in tokens:
            if token.upper() == 'AND':
                if current_part:
                    parts.append(" ".join(current_part))
                    current_part = []
            else: current_part.append(token)
        if current_part: parts.append(" ".join(current_part))
        if len(parts) > 1:
            res = []
            for p in parts: res.extend(parse_query_to_groups(p))
            return res
    return parse_query_to_groups(raw_query)

def build_like_clause_main(raw_query):
    groups = build_like_clause_groups(raw_query)
    res = []
    for g in groups:
        for t in g: res.append(t.strip('"'))
        for t in g: res.append(t) # Keep original term, including quotes if present
    return list(set(res))

def build_term_pattern(term, prefix_match=False):
    """Compile a regex for a single query term.



    Runs of spaces, hyphens ('-') and underscores ('_') are treated as

    equivalent separators, so queries typed as "The-Golden-Mind-Control"

    or "The_Golden_Mind_Control" match text containing "The Golden Mind

    Control" (and any mix of spaces/hyphens/underscores in between).

    """
    words = [w for w in re.split(r'[\s_\-]+', term) if w]
    if not words: return None
    gap = r'[\s_\-]+'
    body = gap.join(re.escape(w) for w in words)
    pattern = (r'\b' if words[0][0].isalnum() else '') + body
    if prefix_match:
        pattern += r'\w*'  # Prefix match for unquoted terms (aligns with FTS 'word*')
    elif words[-1][-1].isalnum():
        pattern += r'\b'
    return re.compile(pattern, re.IGNORECASE)

def compile_logic(groups):
    """Turn parsed query groups into regexes: one list of patterns per OR group."""
    res = []
    for group in groups:
        pats = []
        for p in group:
            term = p.strip().lower().strip('"')
            if not term: continue
            quoted = p.startswith('"') and p.endswith('"')
            pat = build_term_pattern(term, prefix_match=not quoted)
            if pat: pats.append(pat)
        res.append(pats)
    return res

def clean_chapter_content(content):
    if not content: return ''
    text = str(content).strip()
    def extract_raw(raw):
        if not raw or not isinstance(raw, str): return raw
        raw = raw.strip()
        if not (raw.startswith('{') or '"html"' in raw): 
            return raw.replace('\\n', '\n').replace('\\r', '\r')
        try:
            parsed = json.loads(raw)
            if isinstance(parsed, dict) and 'html' in parsed: return extract_raw(parsed['html'])
        except: pass
        m = re.search(r'"html"\s*:\s*"(.*?)"(?=\s*[,}])', raw, re.DOTALL)
        if m:
            val = m.group(1).replace('\\"', '"').replace('\\n', '\n').replace('\\r', '\r').replace('\\t', '\t')
            return extract_raw(val)
        return raw
    cleaned = extract_raw(text)
    if '<' in cleaned and '>' in cleaned:
        cleaned = re.sub(r'(?i)(<br\s*/?>)[\n\r]+', r'\1', cleaned)
        cleaned = re.sub(r'(?i)[\n\r]+(<br\s*/?>)', r'\1', cleaned)
        block_tags = 'div|p|h[1-6]|ul|ol|li|section|article|blockquote'
        cleaned = re.sub(rf'(?i)(</?(?:{block_tags})[^>]*>)[\n\r]+', r'\1', cleaned)
        cleaned = re.sub(rf'(?i)[\n\r]+(</?(?:{block_tags})[^>]*>)', r'\1', cleaned)
    return cleaned

def extract_search_operator(query_text, operator_name):
    pattern = re.compile(rf'{re.escape(operator_name)}(?:\[([^\]]+)\])?:\s*("[^"]+"|\([^)]+\)|\S+)', re.IGNORECASE)
    match = pattern.search(query_text or '')
    if not match: return None, None, query_text
    arg = match.group(1)
    value = match.group(2).strip()
    cleaned = pattern.sub(' ', query_text, count=1)
    cleaned = re.sub(r'\s+', ' ', cleaned).strip()
    return value or None, arg, cleaned

def normalize_snippet_text(content):
    if not content: return ''
    text = clean_chapter_content(content)
    text = html.unescape(text)
    text = text.replace('\\n', ' ').replace('\\r', ' ').replace('\n', ' ').replace('\r', ' ')
    text = re.sub(r'(?i)<br\s*/?>', ' ', text)
    text = re.sub(r'(?i)</p\s*>', ' ', text)
    text = re.sub(r'(?i)<p[^>]*>', ' ', text)
    text = re.sub(r'(?i)</?(i|em|b|strong|u|span|div)[^>]*>', '', text)
    text = re.sub(r'<[^>]+>', ' ', text)
    text = re.sub(r'\s+', ' ', text).strip()
    return text

def highlight_query_terms(snippet, query_parts):
    if not snippet: return ''
    highlighted = snippet
    unique_parts = []
    seen = set()
    for part in sorted(query_parts or [], key=len, reverse=True):
        normalized = part.strip().lower()
        if not normalized or normalized in seen: continue
        seen.add(normalized)
        unique_parts.append(part.strip())
    for part in unique_parts:
        pattern = build_term_pattern(part, prefix_match=False)
        if pattern:
            highlighted = pattern.sub(lambda m: f'<mark>{m.group(0)}</mark>', highlighted)
    return highlighted

def build_text_match_sql(alias, groups, include_story_fields=False):
    if not groups: return "1=1", []
    if groups and not isinstance(groups[0], list): groups = [[t] for t in groups]
    group_clauses = []
    params = []
    for group in groups[:8]:
        branch_clauses = []
        for part in group[:8]:
            like_value = f"%{part.strip('\"')}%"
            current = [f"{alias}.chapter_title LIKE ?", f"{alias}.chapter_content LIKE ?"]
            current_params = [like_value, like_value]
            if include_story_fields:
                current.extend(["s.title LIKE ?", "s.synopsis LIKE ?"])
                current_params.extend([like_value, like_value])
            branch_clauses.append("(" + " OR ".join(current) + ")")
            params.extend(current_params)
        group_clauses.append("(" + " OR ".join(branch_clauses) + ")")
    return " AND ".join(group_clauses), params

def make_like_snippet(content, query_parts, radius=200):
    if not content: return 'No text preview available.'
    text = normalize_snippet_text(content)
    unique_parts = sorted(list(set(p.lower().strip('"') for p in query_parts if p.strip())), key=len, reverse=True)
    if not unique_parts: return (text[:radius].strip() + "...") if len(text) > radius else text
    all_matches = []
    for part in unique_parts:
        pattern = build_term_pattern(part, prefix_match=False)
        if not pattern: continue
        for m in pattern.finditer(text):
            all_matches.append({'start': m.start(), 'end': m.end(), 'term': part})
            if len(all_matches) > 100: break
    if not all_matches: return (text[:radius].strip() + "...") if len(text) > radius else text
    all_matches.sort(key=lambda x: x['start'])
    clusters = []
    if all_matches:
        curr = {'start': all_matches[0]['start'], 'end': all_matches[0]['end'], 'terms': {all_matches[0]['term']}}
        for m in all_matches[1:]:
            if m['start'] <= curr['end'] + 60:
                curr['end'] = max(curr['end'], m['end'])
                curr['terms'].add(m['term'])
            else:
                clusters.append(curr)
                curr = {'start': m['start'], 'end': m['end'], 'terms': {m['term']}}
        clusters.append(curr)
    for c in clusters:
        c['score'] = len(c['terms'])
        c['bonus'] = 1.0 / (1.0 + c['start'] / 1000.0)
    selected_clusters = []
    actual_terms = set(m['term'] for m in all_matches)
    remaining_terms = set(unique_parts).intersection(actual_terms)
    pool = list(clusters)
    while remaining_terms and pool:
        best_c = None
        max_new_terms = -1
        for c in pool:
            new_terms = len(c['terms'].intersection(remaining_terms))
            if new_terms > max_new_terms:
                max_new_terms = new_terms
                best_c = c
            elif new_terms == max_new_terms and best_c and (c['score'] + c['bonus'] > best_c['score'] + best_c['bonus']):
                best_c = c
        if best_c and max_new_terms > 0:
            selected_clusters.append(best_c)
            remaining_terms -= best_c['terms']
            pool.remove(best_c)
        else: break
    if len(selected_clusters) < 4:
        clusters.sort(key=lambda x: x['score'] + x['bonus'], reverse=True)
        for c in clusters:
            if len(selected_clusters) >= 4: break
            if any(abs(c['start'] - s['start']) < 80 for s in selected_clusters): continue
            selected_clusters.append(c)
    selected_clusters.sort(key=lambda x: x['start'])
    pieces = []
    context_radius = max(20, radius // 8)
    for i, c in enumerate(selected_clusters):
        w_start = max(0, c['start'] - context_radius)
        w_end = min(len(text), c['end'] + context_radius)
        if w_start > 0:
            space_idx = text.find(' ', w_start, c['start'])
            if space_idx != -1: w_start = space_idx + 1
            else:
                back_space = text.rfind(' ', max(0, w_start - 20), w_start)
                if back_space != -1: w_start = back_space + 1
        if w_end < len(text):
            space_idx = text.rfind(' ', c['end'], w_end)
            if space_idx != -1: w_end = space_idx
            else:
                fwd_space = text.find(' ', w_end, min(len(text), w_end + 20))
                if fwd_space != -1: w_end = fwd_space
        if i > 0 and w_start < selected_clusters[i-1]['end_display']: w_start = selected_clusters[i-1]['end_display']
        if w_start >= w_end: continue
        piece = text[w_start:w_end]
        prefix = "... " if w_start > 0 else ""
        suffix = " ..." if w_end < len(text) else ""
        pieces.append(f"{prefix}{piece.strip()}{suffix}")
        c['end_display'] = w_end
    snippet = "".join(pieces)
    snippet = re.sub(r'\.\.\.\s*\.\.\.', '...', snippet)
    snippet = re.sub(r'\.\.\.\.\.\.', '...', snippet)
    snippet = re.sub(r'\s+', ' ', snippet)
    return highlight_query_terms(snippet.strip(), query_parts)

@app.route('/api/story/<base_id>', methods=['GET'])
def get_story(base_id):
    if base_id.endswith('.html'): base_id = base_id[:-5]
    conn = get_db_connection()
    story = conn.execute("SELECT * FROM stories WHERE base_id = ?", (base_id,)).fetchone()
    actual_chapter_id = None
    if not story:
        cid_match = conn.execute("SELECT base_id, map_id FROM chapters WHERE map_id LIKE ?", (f"%-{base_id}",)).fetchone()
        if cid_match:
            actual_story_id = cid_match["base_id"]
            actual_chapter_id = cid_match["map_id"].split("-", 1)[1] if "-" in cid_match["map_id"] else cid_match["map_id"]
            story = conn.execute("SELECT * FROM stories WHERE base_id = ?", (actual_story_id,)).fetchone()
        if not story:
            cid_search = f"%{base_id}%"
            story_match = conn.execute("SELECT * FROM stories WHERE url LIKE ? OR image LIKE ?", (cid_search, cid_search)).fetchone()
            if story_match: story = story_match
    if not story:
        conn.close()
        return jsonify({'error': 'Story not found'}), 404
    base_id = story["base_id"]
    chapters_raw = conn.execute("SELECT * FROM chapters WHERE base_id = ?", (base_id,)).fetchall()
    conn.close()
    public_story_id = resolve_public_story_id(story)
    story_data = {
        "info": {
            "id": public_story_id, "pretty_title": story["title"], "description": story["synopsis"] if USE_SYNOPSIS_FALLBACK else "",
            "author_name": story["author_name"] if "author_name" in story.keys() else story["authorcutename"],
            "author_id": story["author_raw_name"] if "author_raw_name" in story.keys() else story["authorid"],
            "created": parse_date_to_timestamp(story["date"]), "source_url": story["url"] if "url" in story.keys() else "",
            "resolved_chapter_id": actual_chapter_id
        }, "chapters": {}
    }
    for c in chapters_raw:
        full_map_id = c["map_id"]
        parts = full_map_id.split("-", 1)
        suffix = parts[1] if len(parts) > 1 else full_map_id
        choices_list = []
        if c["choices"]:
            for choice_str in c["choices"].split("||||"):
                cleaned = re.sub(r'^\d+\.\s*', '', choice_str.strip())
                if cleaned: choices_list.append(cleaned)
        html_content = clean_chapter_content(c["chapter_content"])
        if suffix == 'Intro': story_data["info"]["description"] = html_content
        story_data["chapters"][suffix] = {
            "id": c["map_id"], "title": c["chapter_title"], "content": html_content,
            "created": parse_date_to_timestamp(c["date"]), "choices": choices_list,
            "author_name": c["author_name"] if "author_name" in c.keys() else story["authorcutename"],
            "author_id": c["author_raw_name"] if "author_raw_name" in c.keys() else story["authorid"]
        }
    return jsonify(story_data)

@app.route('/api/author/<authorid>', methods=['GET'])
def get_by_author(authorid):
    conn = get_db_connection()
    try: stories = conn.execute("SELECT * FROM stories WHERE author_raw_name = ?", (authorid,)).fetchall()
    except sqlite3.OperationalError: stories = conn.execute("SELECT * FROM stories WHERE authorid = ?", (authorid,)).fetchall()
    conn.close()
    return jsonify([dict(s) for s in stories])

@app.route('/api/author_chapters/<authorid>', methods=['GET'])
def get_author_chapters(authorid):
    page, limit = int(request.args.get('page', 1)), int(request.args.get('limit', 500))
    query, offset = request.args.get('q', '').strip(), (page - 1) * limit
    sort = request.args.get('sort', 'date-desc')
    date_sort_expr = "substr(c.date, 7, 4) || substr(c.date, 1, 2) || substr(c.date, 4, 2)"
    order_map = {'date-asc': f"{date_sort_expr} ASC", 'title-asc': "c.chapter_title ASC", 'title-desc': "c.chapter_title DESC"}
    order_by = order_map.get(sort, f"{date_sort_expr} DESC")
    conn = get_db_connection()
    try:
        if query:
            count_res = conn.execute("SELECT COUNT(*) FROM chapters_fts f JOIN chapters c ON f.rowid = c.id WHERE c.author_raw_name = ? AND chapters_fts MATCH ?", (authorid, query)).fetchone()
            total_count = count_res[0]
            results = conn.execute(f"SELECT c.map_id, c.base_id, c.chapter_title, c.chapter_content, c.date as created, s.title as story_title, c.author_name as author_name FROM chapters_fts f JOIN chapters c ON f.rowid = c.id JOIN stories s ON c.base_id = s.base_id WHERE c.author_raw_name = ? AND chapters_fts MATCH ? ORDER BY (c.chapter_content IS NULL OR c.chapter_content = '' OR c.chapter_content = '{{}}') ASC, {order_by} LIMIT ? OFFSET ?", (authorid, query, limit, offset)).fetchall()
        else:
            count_res = conn.execute("SELECT COUNT(*) FROM chapters WHERE author_raw_name = ?", (authorid,)).fetchone()
            total_count = count_res[0]
            results = conn.execute(f"SELECT c.map_id, c.base_id, c.chapter_title, c.chapter_content, c.date as created, s.title as story_title, c.author_name as author_name FROM chapters c JOIN stories s ON c.base_id = s.base_id WHERE c.author_raw_name = ? ORDER BY (c.chapter_content IS NULL OR c.chapter_content = '' OR c.chapter_content = '{{}}') ASC, {order_by} LIMIT ? OFFSET ?", (authorid, limit, offset)).fetchall()
    except:
        count_res = conn.execute("SELECT COUNT(*) FROM stories WHERE authorid = ?", (authorid,)).fetchone()
        total_count = count_res[0]
        results = conn.execute("SELECT c.map_id, c.base_id, c.chapter_title, c.chapter_content, c.date as created, s.title as story_title, s.authorcutename as author_name FROM chapters c JOIN stories s ON c.base_id = s.base_id WHERE s.authorid = ? ORDER BY c.date DESC LIMIT ? OFFSET ?", (authorid, limit, offset)).fetchall()
    conn.close()
    return jsonify({'chapters': [{**dict(r), 'chapter_content': clean_chapter_content(r['chapter_content'])} for r in results], 'total': total_count, 'page': page, 'limit': limit, 'query': query})

CATEGORIES = {
    "Fanfic Stories": {"title_only": "Isekai|Konosuba|Kanto's Ghost|Scooby-Doo|Genshin Impact|Assassin's Creed|The Highschool|Persona|Yugi Moto|Yu-Yi-Yh|My hero academia|X-Men|VTubers|Disney|X Men|Lion King|Ace Attorney|Fanfic Stories|Tails|My little pony|TV Series Change/Transform|Anime", "general_search": "Tomb Raider|Code Geass|Dinotopia|Dragon Quest|Big Bang Theory|dragonball Z|Ace Attorney|Super Smash Bros|Yaoi Cartoon|Ben 10|Alex Russo|Isekai|KirbyKnights|NRDD|Zootopia|Simpson's|Sakura Wars|Ranma|Ben & Gwen|Yu Gi Oh|Simpsons|Ranma 1/2|Sailor Moon|Naruto|Power Rangers|Heroes|Sonic|Rugrats|RWBY|My Little Poney|dragon ball|digimon|hentai|Harry Potter|Scooby doo|Wonder Woman|Mass Effect|Family Guy|Wizards of Waverly Place|Pokegirls|Pokemorph|pokémon|pokemon|poke-dex|pokéflute|pokemons|pokémons|pikachu|pokechange|mario|wario|Zelda|Princess Zelda|Maburaho|Yu-gi-oh|yugioh|Yu-Gi-Oh|DC cinematic universe|Marvel|Marvel's|superhero|super heroine|Star Fox|Batman|Spider-Man|X-Men Evolution|Final Fantasy|Star Trek|Star Wars|icarly|Sherlock Holmes"},
    "Role Swap": {"title_only": "", "general_search": "trading places|gender swap|role swap|life swap|switch roles|switched roles|swaps roles|swapped roles|swapped places|trade lives|switch lives|trade palces|trading places|swapping places|swapping roles|switching places|role reversal|swap roles"},
    "Body Parts Swap": {"title_only": "", "general_search": "head swap|head swapping"},
    "Body Swap": {"title_only": "", "general_search": "swapping bodies|transplant|bodyswap|body swap|body switch|switch bodies|switched bodies|swaps bodies|swap bodies|swapped bodies"},
    "Giant/Expanasion/Growth Fetish": {"title_only": "Colossal|Growing Boy|titans|Muscle|Big Little Girls|Giantess|BIG GIRLS|Fatties|Growth|Expansion|Growth|Grew|Giant|Male Giant|Weight|Fat|Expansion|Size|Expansions|Big Girls|GTS|Big Boys|giant animals|get fat|muscle growth|expansion stories|fat girls", "general_search": "muscle growth|expansion stories|Macrophiles|Giantess Island|giant-ess|giant guys|giantess|amazonian|amazonians|Amazon Invasion|Female Growth |giants|giant's house|female expansion|female expansions|male expansions|women gain weight|fat disney|gts|weight gaining|women expand|wwe|weight gain|gts|gt/wg|weight gaining|weighty women|fatties|growing girls|size story|big fat|feet growth|size ray|giant kids|giant men"},
    "Shrink Fetish": {"title_only": "Short Life|Tiny|Shrink|Shrunk", "general_search": "Small Town Swaps|shrinkgrowth|shrinking|shrunken|shruken|shrink ray|tiny life"},
    "Feet Fetish": {"title_only": "Foot|Feet", "general_search": "teen feet|feet growth|foot fetish|footslave|teen feet|girl feet|female feet"},
    "Vore": {"title_only": "", "general_search": "vore|vorarephilia|cannibal|cockvore|cartoon vore"},
    "Tights/Pantyhose Fetish": {"title_only": "", "general_search": "tights|pantyhose|nylon|stockings|hosery|nylons"},
    "Adult Baby": {"title_only": "", "general_search": "ABDL|ab-dl|adult baby|adult babies|diapers|diaper|diaperpalooza"},
    "Ticklish": {"title_only": "", "general_search": "Tickling Women|ticklish|tickle|tickles|tickle feetish"},
    "Fart": {"title_only": "fart|smelly", "general_search": ""},
    "Furry": {"title_only": "", "general_search": "furry|furries|Zootopia|muscle growth|expansion stories"},
    "Gay": {"title_only": "Gay|LGBTQ+", "general_search": ""}
}

@app.route('/api/stories', methods=['GET'])
def get_stories():
    page, limit = int(request.args.get('page', 1)), int(request.args.get('limit', 100))
    offset, q = (page - 1) * limit, request.args.get('q', '').strip()
    sort = request.args.get('sort', 'created_desc')
    include_cats = [c for c in request.args.get('categories', '').split(',') if c]
    exclude_cats = [c for c in request.args.get('exclude_categories', '').split(',') if c]
    conn = get_db_connection()
    where_clauses, params = [], []
    if q:
        where_clauses.append("(base_id LIKE ? OR title LIKE ? OR synopsis LIKE ? OR author_name LIKE ? OR author_raw_name LIKE ?)")
        lq = f"%{q}%"
        params.extend([lq, lq, lq, lq, lq])
    for cat_name in include_cats:
        if cat_name in CATEGORIES:
            cat = CATEGORIES[cat_name]
            clauses = []
            if cat["title_only"]: clauses.append("title REGEXP ?"); params.append(cat["title_only"])
            if cat["general_search"]: clauses.append("(title REGEXP ? OR synopsis REGEXP ?)"); params.extend([cat["general_search"], cat["general_search"]])
            if clauses: where_clauses.append("(" + " OR ".join(clauses) + ")")
    for cat_name in exclude_cats:
        if cat_name in CATEGORIES:
            cat = CATEGORIES[cat_name]
            if cat["title_only"]: where_clauses.append("NOT (title REGEXP ?)"); params.append(cat["title_only"])
            if cat["general_search"]: where_clauses.append("NOT (title REGEXP ? OR synopsis REGEXP ?)"); params.extend([cat["general_search"], cat["general_search"]])
    where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""
    count_res = conn.execute(f"SELECT COUNT(*) FROM stories {where_sql}", params).fetchone()
    total_count = count_res[0]
    sort_map = {'title_asc': 'title ASC', 'title_desc': 'title DESC', 'chapters_desc': 'chapter_count DESC', 'chapters_asc': 'chapter_count ASC', 'created_desc': 'date DESC', 'created_asc': 'date ASC', 'modified_desc': 'last_modified DESC', 'modified_asc': 'last_modified ASC'}
    order_by = sort_map.get(sort, 'date DESC')
    results = conn.execute(f"SELECT base_id as id, title, author_name as authorcutename, author_raw_name as authorid, synopsis, date, chapter_count as chapterCount, last_modified as lastmodified FROM stories {where_sql} ORDER BY {order_by} LIMIT ? OFFSET ?", params + [limit, offset]).fetchall()
    conn.close()
    return jsonify({'stories': [dict(r) for r in results], 'total': total_count, 'page': page, 'limit': limit})

@app.route('/api/author_contributions/<authorid>', methods=['GET'])
def get_author_contributions(authorid):
    page, limit = int(request.args.get('page', 1)), int(request.args.get('limit', 100))
    sort = request.args.get('sort', 'date-desc')
    offset = (page - 1) * limit
    conn = get_db_connection()
    
    # Sort mapping
    date_sort_expr = "substr(s.date, 7, 4) || substr(s.date, 1, 2) || substr(s.date, 4, 2)"
    sort_map = {
        'date-desc': f"{date_sort_expr} DESC",
        'date-asc': f"{date_sort_expr} ASC",
        'contrib-desc': "contribution_count DESC, " + date_sort_expr + " DESC",
        'contrib-asc': "contribution_count ASC, " + date_sort_expr + " DESC"
    }
    order_by = sort_map.get(sort, f"{date_sort_expr} DESC")

    # Find unique base_ids where author wrote a chapter, and join with stories metadata
    query = f"""

        SELECT s.base_id as id, s.title, s.author_name as authorcutename, s.author_raw_name as authorid, 

               s.synopsis, s.date, s.chapter_count as chapterCount, s.last_modified as lastmodified,

               COUNT(c.map_id) as contribution_count

        FROM stories s

        JOIN chapters c ON s.base_id = c.base_id

        WHERE c.author_raw_name = ?

        GROUP BY s.base_id

        ORDER BY {order_by}

        LIMIT ? OFFSET ?

    """
    results = conn.execute(query, (authorid, limit, offset)).fetchall()
    
    count_query = "SELECT COUNT(DISTINCT base_id) FROM chapters WHERE author_raw_name = ?"
    total_count = conn.execute(count_query, (authorid,)).fetchone()[0]
    
    conn.close()
    return jsonify({'stories': [dict(r) for r in results], 'total': total_count, 'page': page, 'limit': limit})

@app.route('/api/related_authors/<authorid>', methods=['GET'])
def get_related_authors(authorid):
    filter_type, limit = request.args.get('filter', 'general'), int(request.args.get('limit', 50))
    conn = get_db_connection()
    where_clause = "WHERE c1.author_raw_name = ? AND c2.author_raw_name != ? AND c2.author_raw_name IS NOT NULL AND c2.author_raw_name != '' AND c2.author_name IS NOT NULL AND c2.author_name != '' AND LOWER(c2.author_name) != 'unknown' AND LOWER(c2.author_raw_name) != 'unknown' AND c2.map_id LIKE c1.map_id || '%'"
    if filter_type == 'recent':
        one_year_ago = (datetime.now().year - 1) * 10000 + datetime.now().month * 100 + datetime.now().day
        where_clause += f" AND (substr(c1.base_id, 1, 0) || (SELECT (substr(s.date, 7, 4) || substr(s.date, 1, 2) || substr(s.date, 4, 2)) FROM stories s WHERE s.base_id = c1.base_id)) >= '{one_year_ago}'"
    results = conn.execute(f"SELECT c2.author_name as name, c2.author_raw_name as id, COUNT(*) as follow_ups FROM chapters c1 JOIN chapters c2 ON c1.base_id = c2.base_id {where_clause} GROUP BY c2.author_raw_name ORDER BY follow_ups DESC LIMIT ?", (authorid, authorid, limit)).fetchall()
    conn.close()
    return jsonify([dict(r) for r in results])

@app.route('/api/search', methods=['GET'])
def search():
    start_time = time.time()
    q = request.args.get('q', '')
    if not q: return jsonify([])
    page, limit = max(1, int(request.args.get('page', 1))), max(1, min(1000, int(request.args.get('limit', 100))))
    offset = (page - 1) * limit
    include_cats = [c for c in request.args.get('categories', '').split(',') if c]
    exclude_cats = [c for c in request.args.get('exclude_categories', '').split(',') if c]
    snippet_limit = max(50, min(5000, int(request.args.get('snippet_limit', 300))))
    related_snippet_limit = max(50, min(5000, int(request.args.get('related_snippet_limit', 300))))
    clean_query = q
    author_filter, _, clean_query = extract_search_operator(clean_query, 'author')
    if author_filter: author_filter = author_filter.strip('"()')
    story_filter, _, clean_query = extract_search_operator(clean_query, 'storyID')
    if story_filter: story_filter = story_filter.strip('"()')
    related_filter, related_depth_str, clean_query = extract_search_operator(clean_query, 'relatedsearch')
    related_depth_limit = int(related_depth_str) if related_depth_str and related_depth_str.isdigit() else None
    before_filter, _, clean_query = extract_search_operator(clean_query, 'before')
    after_filter, _, clean_query = extract_search_operator(clean_query, 'after')
    date_sort_expr = "substr(c.date, 7, 4) || substr(c.date, 1, 2) || substr(c.date, 4, 2)"
    before_val, after_val = normalize_date_for_sql(before_filter, True), normalize_date_for_sql(after_filter, False)
    fts_query = build_fts_query(clean_query)
    query_parts, query_groups = build_like_clause_main(clean_query), parse_query_to_groups(clean_query)
    related_parts, related_groups = build_like_clause_main(related_filter or ''), parse_query_to_groups(related_filter or '')

    # Category optimization
    comb_inc_t = "|".join([CATEGORIES[c]["title_only"] for c in include_cats if c in CATEGORIES and CATEGORIES[c]["title_only"]])
    comb_inc_g = "|".join([CATEGORIES[c]["general_search"] for c in include_cats if c in CATEGORIES and CATEGORIES[c]["general_search"]])
    comb_exc_t = "|".join([CATEGORIES[c]["title_only"] for c in exclude_cats if c in CATEGORIES and CATEGORIES[c]["title_only"]])
    comb_exc_g = "|".join([CATEGORIES[c]["general_search"] for c in exclude_cats if c in CATEGORIES and CATEGORIES[c]["general_search"]])

    conn = get_db_connection()
    all_matching_results, current_search_offset, max_scan_total, rows_scanned, total = [], 0, 100000, 0, 0
    results_to_skip, target_limit = offset, limit

    if fts_query:
        try:
            where_clauses, params = ["chapters_fts MATCH ?"], [fts_query]
            if comb_inc_t: where_clauses.append("(s.title REGEXP ? OR c.chapter_title REGEXP ?)"); params.extend([comb_inc_t, comb_inc_t])
            if comb_inc_g: where_clauses.append("(s.title REGEXP ? OR c.chapter_title REGEXP ? OR s.synopsis REGEXP ?)"); params.extend([comb_inc_g, comb_inc_g, comb_inc_g])
            if comb_exc_t: where_clauses.append("NOT (s.title REGEXP ? OR c.chapter_title REGEXP ?)"); params.extend([comb_exc_t, comb_exc_t])
            if comb_exc_g: where_clauses.append("NOT (s.title REGEXP ? OR c.chapter_title REGEXP ? OR s.synopsis REGEXP ?)"); params.extend([comb_exc_g, comb_exc_g, comb_exc_g])
            if author_filter: where_clauses.append("(c.author_raw_name LIKE ? OR c.author_name LIKE ?)"); params.extend([f"%{author_filter}%", f"%{author_filter}%"])
            if story_filter: where_clauses.append("c.base_id = ?"); params.append(story_filter)
            if before_val: where_clauses.append(f"{date_sort_expr} <= ?"); params.append(before_val)
            if after_val: where_clauses.append(f"{date_sort_expr} >= ?"); params.append(after_val)
            if related_groups:
                related_fts = build_fts_query(related_filter)
                where_clauses.append("c.base_id IN (SELECT DISTINCT c_rel.base_id FROM chapters_fts f_rel JOIN chapters c_rel ON f_rel.rowid = c_rel.id WHERE f_rel.chapters_fts MATCH ?)")
                params.append(related_fts)
            where_sql = " AND ".join(where_clauses)
            
            count_start = time.time()
            total = conn.execute(f"SELECT COUNT(*) FROM chapters_fts JOIN chapters c ON chapters_fts.rowid = c.id JOIN stories s ON c.base_id = s.base_id WHERE {where_sql}", params).fetchone()[0]
            print(f"[*] Incoming Search: '{q}'")
            print(f"[*] FTS matches to verify: {total} (Count took {time.time()-count_start:.2f}s)")
            
            compiled_patterns = compile_logic(query_groups)
            rel_compiled_patterns = compile_logic(related_groups)
            related_cache = {}

            # Pre-calculate related FTS query once to avoid overhead in the loop
            rel_fts_val = build_fts_query(related_filter) if related_filter else None

            while len(all_matching_results) < target_limit and rows_scanned < max_scan_total:
                # Increase batch size if hit rate is low to reduce SQL roundtrips
                fetch_batch_size = 500 if rows_scanned > 1000 and not all_matching_results else max(target_limit, 200)
                
                if rows_scanned % 200 == 0 or rows_scanned == 0:
                    print(f"[*] Progress: {rows_scanned}/{total} scanned | {len(all_matching_results)} hits | {len(related_cache)} stories cached")

                batch = conn.execute(f"SELECT c.map_id, c.base_id, c.chapter_title, c.chapter_content, s.title as story_title, s.synopsis, c.author_name, c.author_raw_name, c.date as created, (SELECT MAX(LENGTH(c2.map_id)) - LENGTH(c.map_id) FROM chapters c2 WHERE c2.base_id = c.base_id AND c2.map_id LIKE c.map_id || '%') as ldfh FROM chapters_fts JOIN chapters c ON chapters_fts.rowid = c.id JOIN stories s ON c.base_id = s.base_id WHERE {where_sql} ORDER BY rank, c.id DESC LIMIT ? OFFSET ?", params + [fetch_batch_size, current_search_offset]).fetchall()
                if not batch: break
                for row in batch:
                    rows_scanned += 1
                    row_dict = dict(row)
                    meta_text = f"{row_dict.get('chapter_title') or ''} {row_dict.get('story_title') or ''} {row_dict.get('synopsis') or ''}".lower()
                    match_all, unmatched = True, []
                    for group_pats in compiled_patterns:
                        if not any(pat.search(meta_text) for pat in group_pats): unmatched.append(group_pats)
                    if unmatched:
                        clean_content = clean_chapter_content(row_dict.get('chapter_content'))
                        content_low = html.unescape(re.sub(r'<[^>]+>', ' ', clean_content)).lower()
                        for group_pats in unmatched:
                            if not any(pat.search(content_low) for pat in group_pats): match_all = False; break
                    else: clean_content = None

                    if match_all and related_filter:
                        bid = row_dict['base_id']
                        if bid not in related_cache:
                            try:
                                rel_rows = conn.execute(f"SELECT c.base_id, c.map_id, c.chapter_title, c.chapter_content, c.author_name, c.author_raw_name, c.date as created, (SELECT MAX(LENGTH(c2.map_id)) - LENGTH(c.map_id) FROM chapters c2 WHERE c2.base_id = c.base_id AND c2.map_id LIKE c.map_id || '%') as ldfh FROM chapters_fts f JOIN chapters c ON f.rowid = c.id WHERE c.base_id = ? AND f.chapters_fts MATCH ?", (bid, rel_fts_val)).fetchall()
                                processed_rel = []
                                for rr in rel_rows:
                                    rd = dict(rr)
                                    # Lightweight cleaning for search text: just strip HTML tags and unescape
                                    raw_text = f"{rd.get('chapter_title') or ''} {rd.get('chapter_content') or ''}"
                                    rd['_search_text'] = html.unescape(re.sub(r'<[^>]+>', ' ', raw_text)).lower()
                                    processed_rel.append(rd)
                                related_cache[bid] = processed_rel
                            except: related_cache[bid] = []
                        
                        m_map, m_suf = row_dict['map_id'], (row_dict['map_id'].split('-')[1] if '-' in row_dict['map_id'] else "").replace("Intro", "")
                        valid_related = []
                        for rr in related_cache[bid]:
                            r_suf = (rr['map_id'].split('-')[1] if '-' in rr['map_id'] else "").replace("Intro", "")
                            if related_depth_limit is not None and (not (r_suf.startswith(m_suf) or m_suf.startswith(r_suf)) or abs(len(r_suf)-len(m_suf)) > related_depth_limit): continue
                            
                            rr_txt = rr['_search_text']
                            rel_match_all, matched_terms = True, []
                            for grp_idx, grp_pats in enumerate(rel_compiled_patterns):
                                grp_matched = False
                                for pat_idx, pat in enumerate(grp_pats):
                                    if pat.search(rr_txt):
                                        grp_matched = True
                                        matched_terms.append(related_groups[grp_idx][pat_idx].strip('"'))
                                if not grp_matched:
                                    rel_match_all = False
                                    break
                            if not rel_match_all: continue
                            
                            rr_copy = dict(rr)
                            rr_copy['matched_terms_found'] = list(set(matched_terms))
                            valid_related.append(rr_copy)
                        
                        if not valid_related: match_all = False
                        else: row_dict['related_matches_pre'] = valid_related[:20]

                    if match_all:
                        if results_to_skip > 0: results_to_skip -= 1
                        else:
                            if clean_content is None: clean_content = clean_chapter_content(row_dict.get('chapter_content'))
                            row_dict['chapter_content_clean'] = clean_content
                            row_dict['content_text'] = normalize_snippet_text(clean_content)
                            all_matching_results.append(row_dict)
                            if len(all_matching_results) >= target_limit: break
                current_search_offset += fetch_batch_size
                if len(batch) < fetch_batch_size: break
            
            scanned_all = (len(all_matching_results) < target_limit) and (rows_scanned < max_scan_total)
            if scanned_all:
                total = (offset - results_to_skip) + len(all_matching_results)
        except Exception as e:
            print(f"Error during search: {e}")
            all_matching_results, total = [], 0
    final_results = []
    def part_in_text(part, text):
        if not text: return False
        pat = build_term_pattern(part.strip('"'), prefix_match=False)
        return bool(pat and pat.search(text))
    for row_dict in all_matching_results[:limit]:
        content, synopsis = row_dict.get('chapter_content_clean') or "", row_dict.get('synopsis') or ""
        text_source = content if any(part_in_text(p, row_dict.get('content_text') or "") for p in query_parts) else (synopsis if any(part_in_text(p, synopsis) for p in query_parts) else (content or synopsis))
        row_dict['snippet'] = make_like_snippet(text_source, query_parts, radius=snippet_limit)
        row_dict['chapter_title'] = highlight_query_terms(row_dict.get('chapter_title') or "", query_parts)
        row_dict['story_title'] = highlight_query_terms(row_dict.get('story_title') or "", query_parts)
        for k in ['chapter_content', 'chapter_content_clean', 'content_text', 'synopsis']: row_dict.pop(k, None)
        final_results.append(row_dict)

    if final_results and related_filter:
        for res in final_results:
            pre_matches = res.pop('related_matches_pre', [])
            res['related_matches'] = []
            for rr in pre_matches:
                res['related_matches'].append({
                    "map_id": rr["map_id"], "title": rr["chapter_title"],
                    "snippet": make_like_snippet(rr["chapter_content"], related_parts, radius=related_snippet_limit),
                    "author_name": rr["author_name"], "author_raw_name": rr["author_raw_name"],
                    "created": rr["created"], "matched_terms": rr.get('matched_terms_found', []), "ldfh": rr["ldfh"]
                })
    conn.close()
    duration = time.time() - start_time
    print(f"[*] Search complete in {duration:.2f}s. Results found: {len(final_results)}.")
    return jsonify({'results': final_results, 'total': total, 'page': page, 'limit': limit, 'query': q, 'duration': duration})

if __name__ == '__main__': app.run(host='0.0.0.0', port=9999, debug=True)