File size: 28,402 Bytes
18fd039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# """
# FilGoalBot Preprocessing Pipeline — v3 (Production)
# =====================================================
# Input:  data/raw/articles.jsonl
# Output: data/processed/chunks.jsonl
#         data/processed/stats.json

# All 9 FilGoal-specific noise patterns handled:
#   1. Social share empty links [](https://twitter/facebook...)
#   2. Date/byline: 'الأحد، 15 مارس 2026 - 02:08 كتب : FilGoal'
#   3. Scoreboard widget: **1**\\ TeamA\\ **1**\\ TeamB\\ **League**
#   4. انتهتHH:MM inline score timestamps
#   5. Backslash sequences \\\\ (Firecrawl markdown artifact)
#   6. News ticker sidebar: 'N دقيقة |' or 'ساعة |' — CUT everything after
#   7. Related articles separator '__' — CUT everything after
#   8. Markdown bold/italic/headers/links/images
#   9. HTML tags, Getty captions, duplicate adjacent phrases
# """

# import re, json, logging, argparse
# from pathlib import Path
# from datetime import datetime
# from collections import defaultdict

# logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
# log = logging.getLogger("preprocessing")

# RAW_FILE    = Path("data/raw/articles.jsonl")
# OUTPUT_DIR  = Path("data/processed")
# CHUNKS_FILE = OUTPUT_DIR / "chunks.jsonl"
# STATS_FILE  = OUTPUT_DIR / "stats.json"
# CHUNK_SIZE, CHUNK_OVERLAP = 300, 60

# _AR_DAYS = r'(الأحد|الإثنين|الثلاثاء|الأربعاء|الخميس|الجمعة|السبت)'
# _HARAKAT = re.compile(r'[\u064B-\u065F\u0670\u0640]')


# def clean_filgoal_body(text: str, title: str = '') -> str:
#     if not text:
#         return ''
#     # 1. Empty social share links
#     text = re.sub(r'\[\]\(https?://[^\)]+\)\s*', '', text)
#     # 2. Date + byline header
#     text = re.sub(_AR_DAYS + r'[،,]\s*\d{1,2}\s+\w+\s+\d{4}\s*[-–]\s*\d{2}:\d{2}\s*', '', text)
#     text = re.sub(r'كتب\s*:\s*FilGoal\s*', '', text)
#     # 3. Scoreboard widget
#     text = re.sub(
#         r'\*\*\d+\*\*\s*\\\\\s*[^\*\n]{2,40}\s*\\\\\s*'
#         r'\*\*\d+\*\*\s*\\\\\s*[^\*\n]{2,40}\s*\\\\\s*\*\*[^\*\n]+\*\*',
#         '', text
#     )
#     # 4. انتهتHH:MM
#     text = re.sub(r'انتهت\d{2}:\d{2}\s*', '', text)
#     # 5. All backslashes → space (must happen BEFORE ticker cut)
#     text = re.sub(r'\\+', ' ', text)
#     # 6. CUT news ticker: 'N دقيقة |' or 'ساعة |'
#     ticker = re.search(r'\d+\s+دقيقة\s+\||\bساعة\s+\|', text)
#     if ticker:
#         text = text[:ticker.start()].strip()
#     # 7. CUT at __ related articles separator
#     dunder = text.find(' __ ')
#     if dunder > 200:
#         text = text[:dunder].strip()
#     # 8. Remove /articles/NNNNN paths
#     text = re.sub(r'/articles/\d+\S*', '', text)
#     # 9. Markdown → plain text
#     text = re.sub(r'\*\*([^\*\n]+)\*\*', r'\1', text)
#     text = re.sub(r'\*([^\*\n]+)\*',     r'\1', text)
#     text = re.sub(r'#{1,6}\s+',           '',    text)
#     text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
#     text = re.sub(r'\[\]\([^\)]+\)',      '',    text)
#     text = re.sub(r'!\[[^\]]*\]\([^\)]+\)', '',  text)
#     # 10. HTML tags
#     text = re.sub(r'<[^>]+>', '', text)
#     # 11. Image captions
#     text = re.sub(r'صورة\s*:\s*\S+', '', text)
#     text = re.sub(r'Getty\s*(Images?)?', '', text, flags=re.IGNORECASE)
#     # 12. Deduplicate repeated adjacent words
#     text = re.sub(r'\b(\S{4,})\s+\1\b', r'\1', text)
#     # 13. Final whitespace
#     text = re.sub(r'[ \t]{2,}', ' ', text).strip()
#     # 14. Remove title duplicated at start
#     if title and len(title) > 10 and text.startswith(title[:20].strip()):
#         text = text[len(title[:20]):].strip()
#     return text


# def normalize_arabic(text: str) -> str:
#     """Normalize for embedding — do NOT use on display text."""
#     if not text:
#         return ''
#     text = _HARAKAT.sub('', text)
#     for frm, to in [('[أإآٱ]', 'ا'), ('ى', 'ي'), ('ة', 'ه'), ('ؤ', 'و')]:
#         text = re.sub(frm, to, text)
#     return re.sub(r'\s+', ' ', text).strip()


# EGYPTIAN_TEAMS = {
#     'الأهلي': 'al_ahly', 'الزمالك': 'zamalek', 'بيراميدز': 'pyramids',
#     'الإسماعيلي': 'ismaily', 'المصري': 'masry', 'سيراميكا': 'ceramica',
#     'طلائع الجيش': 'tala3a', 'فاركو': 'farco', 'حرس الحدود': 'haras',
#     'إنبي': 'enppi', 'المقاولون': 'mokawloon', 'مودرن': 'modern',
#     'البنك الأهلي': 'nbe', 'غزل المحلة': 'ghazl', 'سموحة': 'smouha',
#     'الجونة': 'el_gouna',
# }

# LEAGUE_KEYWORDS = {
#     'premier_league':   ['الدوري الإنجليزي', 'الدوري الإنجليزي الممتاز'],
#     'la_liga':          ['الدوري الإسباني', 'لاليغا'],
#     'serie_a':          ['الدوري الإيطالي'],
#     'bundesliga':       ['الدوري الألماني'],
#     'ligue_1':          ['الدوري الفرنسي'],
#     'champions_league': ['دوري أبطال أوروبا'],
#     'caf_champions':    ['دوري أبطال إفريقيا', 'الكونفدرالية'],
#     'egyptian_league':  ['الدوري المصري', 'دوري المحترفين'],
#     'saudi_league':     ['الدوري السعودي', 'روشن'],
# }

# def detect_teams(text: str) -> list:
#     seen, result = set(), []
#     for ar, en in EGYPTIAN_TEAMS.items():
#         if ar in text and en not in seen:
#             seen.add(en); result.append(en)
#     return result

# def detect_league(title: str, section: str, body: str) -> str:
#     combined = f"{title} {section} {body[:300]}"
#     for lid, kws in LEAGUE_KEYWORDS.items():
#         if any(kw in combined for kw in kws):
#             return lid
#     SECT_MAP = {
#         'الكرة المصرية': 'egyptian_league', 'الدوري المصري': 'egyptian_league',
#         'الكرة الإفريقية': 'caf_champions',  'سعودي في الجول': 'saudi_league',
#         'الدوري الإنجليزي': 'premier_league','الكرة الأوروبية': 'champions_league',
#     }
#     for k, v in SECT_MAP.items():
#         if k in section:
#             return v
#     return 'other'


# def chunk_text(text: str) -> list:
#     words = text.split()
#     if len(words) <= CHUNK_SIZE:
#         return [text]
#     chunks, start = [], 0
#     while start < len(words):
#         end = min(start + CHUNK_SIZE, len(words))
#         chunks.append(' '.join(words[start:end]))
#         if end == len(words):
#             break
#         start += CHUNK_SIZE - CHUNK_OVERLAP
#     return chunks


# TYPE_AR = {
#     'lineup': 'تشكيلة', 'match_result': 'نتيجة مباراة',
#     'press_conference': 'مؤتمر صحفي', 'training': 'تدريب',
#     'transfer': 'ميركاتو', 'article': 'خبر',
# }

# def build_chunk_text(art: dict, chunk_body: str, idx: int, total: int) -> str:
#     parts = [f"عنوان: {art.get('title_norm') or art.get('title', '')}"]
#     t = art.get('article_type', 'article')
#     if t != 'article':
#         parts.append(f"نوع: {TYPE_AR.get(t, t)}")
#     if art.get('section'):
#         parts.append(f"قسم: {art['section']}")
#     if art.get('league', 'other') != 'other':
#         parts.append(f"بطولة: {art['league']}")
#     if art.get('teams'):
#         parts.append(f"الفرق: {' - '.join(art['teams'][:3])}")
#     if art.get('pub_date'):
#         parts.append(f"تاريخ: {art['pub_date'][:10]}")
#     prefix = ' | '.join(parts)
#     suffix = f"[جزء {idx+1}/{total}]\n" if total > 1 else ""
#     return f"{prefix}\n\n{suffix}{chunk_body}"


# def run_pipeline(raw_file: Path = RAW_FILE):
#     OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
#     if not Path(raw_file).exists():
#         log.error(f"Not found: {raw_file}")
#         return

#     articles, seen_ids = [], set()
#     with open(raw_file, encoding='utf-8') as f:
#         for line in f:
#             line = line.strip()
#             if not line:
#                 continue
#             try:
#                 art = json.loads(line)
#                 aid = art.get('article_id')
#                 if aid and aid not in seen_ids:
#                     seen_ids.add(aid)
#                     articles.append(art)
#             except json.JSONDecodeError:
#                 pass

#     log.info(f"Loaded {len(articles)} articles")

#     type_c = defaultdict(int)
#     league_c = defaultdict(int)
#     total_chunks = skipped = 0
#     body_lens = []

#     with open(CHUNKS_FILE, 'w', encoding='utf-8') as fout:
#         for art in articles:
#             title = art.get('title', '')
#             bc = clean_filgoal_body(art.get('body', ''), title)
#             if len(bc) < 80:
#                 skipped += 1
#                 continue
#             body_lens.append(len(bc))
#             tn     = normalize_arabic(title)
#             bn     = normalize_arabic(bc)
#             teams  = detect_teams(title + ' ' + bc)
#             league = detect_league(title, art.get('section', ''), bc)
#             enriched = {**art, 'body_clean': bc, 'title_norm': tn, 'teams': teams, 'league': league}
#             chunks = chunk_text(bn)
#             n = len(chunks)
#             for i, cb in enumerate(chunks):
#                 fout.write(json.dumps({
#                     'chunk_id':     f"{art['article_id']}_{i}",
#                     'article_id':   art['article_id'],
#                     'chunk_index':  i,
#                     'total_chunks': n,
#                     'text':         build_chunk_text(enriched, cb, i, n),
#                     'title':        title,
#                     'title_norm':   tn,
#                     'body_clean':   bc,
#                     'section':      art.get('section', ''),
#                     'article_type': art.get('article_type', 'article'),
#                     'pub_date':     art.get('pub_date', ''),
#                     'teams':        teams,
#                     'league':       league,
#                     'tags':         art.get('tags', []),
#                     'source_url':   art.get('source_url', ''),
#                     'image':        art.get('image', ''),
#                 }, ensure_ascii=False) + '\n')
#                 total_chunks += 1
#             type_c[art.get('article_type', 'article')] += 1
#             league_c[league] += 1

#     avg = int(sum(body_lens) / len(body_lens)) if body_lens else 0
#     stats = {
#         'total_articles':     len(articles),
#         'articles_processed': len(articles) - skipped,
#         'skipped':            skipped,
#         'total_chunks':       total_chunks,
#         'avg_body_length':    avg,
#         'min_body_length':    min(body_lens) if body_lens else 0,
#         'max_body_length':    max(body_lens) if body_lens else 0,
#         'article_types':      dict(type_c),
#         'league_coverage':    dict(league_c),
#         'processed_at':       datetime.now().isoformat(),
#     }
#     STATS_FILE.write_text(json.dumps(stats, ensure_ascii=False, indent=2))

#     log.info(f"\n Preprocessing complete!")
#     log.info(f"   Articles   : {len(articles) - skipped} / {len(articles)}")
#     log.info(f"   Chunks     : {total_chunks}")
#     log.info(f"   Avg body   : {avg} chars")
#     log.info(f"   Types      : {dict(type_c)}")
#     log.info(f"   Leagues    : {dict(league_c)}")
#     log.info(f"   Output     : {CHUNKS_FILE}")
#     return stats


# if __name__ == '__main__':
#     parser = argparse.ArgumentParser(description='FilGoalBot Preprocessing Pipeline')
#     parser.add_argument('--input', default=str(RAW_FILE), help='Path to raw articles.jsonl')
#     args = parser.parse_args()
#     run_pipeline(Path(args.input))


"""
FilGoalBot Preprocessing Pipeline — v4 (Production)
=====================================================
Input:  data/raw/articles.jsonl
Output: data/processed/chunks.jsonl
        data/processed/stats.json

All 9 FilGoal-specific noise patterns handled:
  1. Social share empty links [](https://twitter/facebook...)
  2. Date/byline: 'الأحد، 15 مارس 2026 - 02:08 كتب : FilGoal'
  3. Scoreboard widget: **1**\\ TeamA\\ **1**\\ TeamB\\ **League**
  4. انتهتHH:MM inline score timestamps
  5. Backslash sequences \\\\ (Firecrawl markdown artifact)
  6. News ticker sidebar: 'N دقيقة |' or 'ساعة |' — CUT everything after
  7. Related articles separator '__' — CUT everything after
  8. Markdown bold/italic/headers/links/images
  9. HTML tags, Getty captions, duplicate adjacent phrases

v4 changes:
  - Skip non-football sections: كرة يد / كرة سلة / كرة طائرة
  - video:1 placeholders removed
  - Embedded tweet pic links pic.twitter.com stripped
  - Hashtags stripped (including escaped \\_)
  - Angle-bracket tweet separator > replaced with space
  - FilGoal domain refs filgoal.com/... stripped
  - Client JS artifact at tail stripped
  - HaytersTV promo paragraph stripped
  - English tweet dates (March 14, 2026) stripped
  - YouTube label + iframe block stripped
  - beIN Sports handles @beINSPORTS stripped
  - Mixed bold-italic _**text**_ stripped
  - Emojis removed
  - Tashkeel/tatweel diacritics removed (normalization)
  - Alef variants أ إ آ → ا (normalization)
"""

import re, json, logging, argparse
from pathlib import Path
from datetime import datetime
from collections import defaultdict

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger("preprocessing")

RAW_FILE    = Path("data/raw/articles.jsonl")
OUTPUT_DIR  = Path("data/processed")
CHUNKS_FILE = OUTPUT_DIR / "chunks.jsonl"
STATS_FILE  = OUTPUT_DIR / "stats.json"
CHUNK_SIZE, CHUNK_OVERLAP = 300, 60

# Sections to skip entirely — not football content
NON_FOOTBALL_SECTIONS = {
    'كرة يد',
    'كرة سلة',
    'كرة طائرة',
    'رياضات أخرى',   
}

_AR_DAYS = r'(الأحد|الإثنين|الثلاثاء|الأربعاء|الخميس|الجمعة|السبت)'
_HARAKAT = re.compile(r'[\u064B-\u065F\u0670\u0640]')
_EMOJI   = re.compile(
    r'[\U0001F300-\U0001F9FF'
    r'\U00002600-\U000027FF'
    r'\U0000FE00-\U0000FE0F'
    r'\U0001FA00-\U0001FA9F]+',
    flags=re.UNICODE,
)

_ENGLISH_MONTHS = (
    r'(January|February|March|April|May|June|'
    r'July|August|September|October|November|December)'
)


def clean_filgoal_body(text: str, title: str = '') -> str:
    if not text:
        return ''

    # ── Phase A: pre-backslash patterns ──────────────────────────────────────

    # 1. Empty social share links
    text = re.sub(r'\[\]\(https?://[^\)]+\)\s*', '', text)

    # 2. Date + byline header
    text = re.sub(
        _AR_DAYS + r'[،,]\s*\d{1,2}\s+\w+\s+\d{4}\s*[-–]\s*\d{2}:\d{2}\s*',
        '', text,
    )
    text = re.sub(r'كتب\s*:\s*FilGoal\s*', '', text)

    # 3. Scoreboard widget  **1**\\ TeamA\\ **1**\\ TeamB\\ **League**
    text = re.sub(
        r'\*\*\d+\*\*\s*\\\\\s*[^\*\n]{2,40}\s*\\\\\s*'
        r'\*\*\d+\*\*\s*\\\\\s*[^\*\n]{2,40}\s*\\\\\s*\*\*[^\*\n]+\*\*',
        '', text,
    )

    # 4. انتهتHH:MM
    text = re.sub(r'انتهت\d{2}:\d{2}\s*', '', text)

    # 5. video:N placeholders
    text = re.sub(r'\bvideo:\d+\b', '', text)

    # 6. Embedded tweet pic links
    text = re.sub(r'https?://pic\.twitter\.com/\S+', '', text)
    text = re.sub(r'pic\.twitter\.com/\S+', '', text)

    # 7. Hashtags (plain and escaped-underscore forms)
    text = re.sub(r'#[\w\u0600-\u06FF]+(?:\\_[\w\u0600-\u06FF]+)*', '', text)

    # 8. Angle-bracket tweet separator lines (">")
    text = re.sub(r'(?m)^>\s*', ' ', text)

    # 9. FilGoal domain references — three variants
    text = re.sub(r'https?://(?:www\.)?filgoal\.com/\S*', '', text)
    text = re.sub(r'(?:www\.)?filgoal\.com/\S*', '', text)
    text = re.sub(r'\bfilgoal\.com\b', '', text)

    # ── Phase B: hard cuts ────────────────────────────────────────────────────

    # 10. All backslashes → space (must happen BEFORE ticker/related cuts)
    text = re.sub(r'\\+', ' ', text)

    # 11. CUT news ticker: 'N دقيقة |' or 'ساعة |'
    ticker = re.search(r'\d+\s+دقيقة\s+\||\bساعة\s+\|', text)
    if ticker:
        text = text[:ticker.start()].strip()

    # 12. CUT at __ related articles separator
    dunder = text.find(' __ ')
    if dunder > 200:
        text = text[:dunder].strip()

    # ── Phase C: post-cut cleanup ─────────────────────────────────────────────

    # 13. Remove /articles/NNNNN paths
    text = re.sub(r'/articles/\d+\S*', '', text)

    # 14. Strip "Client" JS artifact at tail
    text = re.sub(r'\bClient\b.*$', '', text, flags=re.DOTALL)

    # 15. HaytersTV promo paragraph
    text = re.sub(
        r'هايترز\s*تي\s*في.*?(?:يوتيوب|YouTube|اشترك)[^\n]*',
        '', text, flags=re.IGNORECASE | re.DOTALL,
    )

    # 16. YouTube label + iframe block
    text = re.sub(r'\bYouTube\b[^\n]*', '', text, flags=re.IGNORECASE)
    text = re.sub(
        r'\d[\d,\.]*\s*(?:مشترك|subscriber)[^\n]*',
        '', text, flags=re.IGNORECASE,
    )

    # 17. beIN Sports handles and attributions
    text = re.sub(r'@beIN\w*', '', text, flags=re.IGNORECASE)
    text = re.sub(r'beIN\s*Sports?\s*(?:عربي|العربية|Arabic)?', '', text, flags=re.IGNORECASE)

    # 18. English tweet dates "March 14, 2026" / "14 March 2026"
    text = re.sub(
        r'\b\d{1,2}\s+' + _ENGLISH_MONTHS + r'\s+\d{4}\b', '', text,
    )
    text = re.sub(
        _ENGLISH_MONTHS + r'\s+\d{1,2},?\s+\d{4}\b', '', text,
    )

    # 19. Mixed bold-italic  _**text**_  or  **_text_**
    text = re.sub(r'_\*\*([^\*\n]+)\*\*_', r'\1', text)
    text = re.sub(r'\*\*_([^_\n]+)_\*\*',  r'\1', text)

    # 20. Emojis
    text = _EMOJI.sub('', text)

    # ── Phase D: standard markdown → plain text ───────────────────────────────

    text = re.sub(r'\*\*([^\*\n]+)\*\*', r'\1', text)
    text = re.sub(r'\*([^\*\n]+)\*',     r'\1', text)
    text = re.sub(r'#{1,6}\s+',           '',    text)
    text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
    text = re.sub(r'\[\]\([^\)]+\)',      '',    text)
    text = re.sub(r'!\[[^\]]*\]\([^\)]+\)', '',  text)

    # ── Phase E: HTML + captions ──────────────────────────────────────────────

    text = re.sub(r'<[^>]+>', '', text)
    text = re.sub(r'صورة\s*:\s*\S+', '', text)
    text = re.sub(r'Getty\s*(Images?)?', '', text, flags=re.IGNORECASE)

    # ── Phase F: final normalisation ──────────────────────────────────────────

    # Deduplicate repeated adjacent words
    text = re.sub(r'\b(\S{4,})\s+\1\b', r'\1', text)
    # Collapse whitespace
    text = re.sub(r'[ \t]{2,}', ' ', text).strip()
    # Remove title duplicated at start
    if title and len(title) > 10 and text.startswith(title[:20].strip()):
        text = text[len(title[:20]):].strip()

    return text


def normalize_arabic(text: str) -> str:
    """Normalize for embedding — do NOT use on display text."""
    if not text:
        return ''
    text = _HARAKAT.sub('', text)
    for frm, to in [
        ('[أإآٱ]', 'ا'),
        ('ى',      'ي'),
        ('ة',      'ه'),
        ('ؤ',      'و'),
    ]:
        text = re.sub(frm, to, text)
    return re.sub(r'\s+', ' ', text).strip()


EGYPTIAN_TEAMS = {
    'الأهلي':       'al_ahly',
    'الزمالك':      'zamalek',
    'بيراميدز':     'pyramids',
    'الإسماعيلي':   'ismaily',
    'المصري':       'masry',
    'سيراميكا':     'ceramica',
    'طلائع الجيش':  'tala3a',
    'فاركو':        'farco',
    'حرس الحدود':   'haras',
    'إنبي':         'enppi',
    'المقاولون':    'mokawloon',
    'مودرن':        'modern',
    'البنك الأهلي': 'nbe',
    'غزل المحلة':   'ghazl',
    'سموحة':        'smouha',
    'الجونة':       'el_gouna',
}

LEAGUE_KEYWORDS = {
    'premier_league':   ['الدوري الإنجليزي', 'الدوري الإنجليزي الممتاز'],
    'la_liga':          ['الدوري الإسباني', 'لاليغا'],
    'serie_a':          ['الدوري الإيطالي'],
    'bundesliga':       ['الدوري الألماني'],
    'ligue_1':          ['الدوري الفرنسي'],
    'champions_league': ['دوري أبطال أوروبا'],
    'caf_champions':    ['دوري أبطال إفريقيا', 'الكونفدرالية'],
    'egyptian_league':  ['الدوري المصري', 'دوري المحترفين'],
    'saudi_league':     ['الدوري السعودي', 'روشن'],
}


def detect_teams(text: str) -> list:
    seen, result = set(), []
    for ar, en in EGYPTIAN_TEAMS.items():
        if ar in text and en not in seen:
            seen.add(en)
            result.append(en)
    return result


def detect_league(title: str, section: str, body: str) -> str:
    combined = f"{title} {section} {body[:300]}"
    for lid, kws in LEAGUE_KEYWORDS.items():
        if any(kw in combined for kw in kws):
            return lid
    SECT_MAP = {
        'الكرة المصرية':    'egyptian_league',
        'الدوري المصري':    'egyptian_league',
        'الكرة الإفريقية':  'caf_champions',
        'سعودي في الجول':   'saudi_league',
        'الدوري الإنجليزي': 'premier_league',
        'الكرة الأوروبية':  'champions_league',
    }
    for k, v in SECT_MAP.items():
        if k in section:
            return v
    return 'other'


def chunk_text(text: str) -> list:
    words = text.split()
    if len(words) <= CHUNK_SIZE:
        return [text]
    chunks, start = [], 0
    while start < len(words):
        end = min(start + CHUNK_SIZE, len(words))
        chunks.append(' '.join(words[start:end]))
        if end == len(words):
            break
        start += CHUNK_SIZE - CHUNK_OVERLAP
    return chunks


TYPE_AR = {
    'lineup':           'تشكيلة',
    'match_result':     'نتيجة مباراة',
    'press_conference': 'مؤتمر صحفي',
    'training':         'تدريب',
    'transfer':         'ميركاتو',
    'article':          'خبر',
}


def build_chunk_text(art: dict, chunk_body: str, idx: int, total: int) -> str:
    parts = [f"عنوان: {art.get('title_norm') or art.get('title', '')}"]
    t = art.get('article_type', 'article')
    if t != 'article':
        parts.append(f"نوع: {TYPE_AR.get(t, t)}")
    if art.get('section'):
        parts.append(f"قسم: {art['section']}")
    if art.get('league', 'other') != 'other':
        parts.append(f"بطولة: {art['league']}")
    if art.get('teams'):
        parts.append(f"الفرق: {' - '.join(art['teams'][:3])}")
    if art.get('pub_date'):
        parts.append(f"تاريخ: {art['pub_date'][:10]}")
    prefix = ' | '.join(parts)
    suffix = f"[جزء {idx+1}/{total}]\n" if total > 1 else ""
    return f"{prefix}\n\n{suffix}{chunk_body}"


def run_pipeline(raw_file: Path = RAW_FILE):
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    if not Path(raw_file).exists():
        log.error(f"Not found: {raw_file}")
        return

    articles, seen_ids = [], set()
    with open(raw_file, encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                art = json.loads(line)
                aid = art.get('article_id')
                if aid and aid not in seen_ids:
                    seen_ids.add(aid)
                    articles.append(art)
            except json.JSONDecodeError:
                pass

    log.info(f"Loaded {len(articles)} articles")

    type_c   = defaultdict(int)
    league_c = defaultdict(int)
    total_chunks = skipped = skipped_section = 0
    body_lens = []

    with open(CHUNKS_FILE, 'w', encoding='utf-8') as fout:
        for art in articles:
            # ── Filter: skip non-football sections ───────────────────────────
            section = art.get('section', '').strip()
            if section in NON_FOOTBALL_SECTIONS:
                skipped_section += 1
                log.debug(f"Skipped non-football section '{section}': {art.get('article_id')}")
                continue

            title = art.get('title', '')
            bc = clean_filgoal_body(art.get('body', ''), title)
            if len(bc) < 80:
                skipped += 1
                continue

            body_lens.append(len(bc))
            tn     = normalize_arabic(title)
            bn     = normalize_arabic(bc)
            teams  = detect_teams(title + ' ' + bc)
            league = detect_league(title, section, bc)

            enriched = {
                **art,
                'body_clean': bc,
                'title_norm': tn,
                'teams':      teams,
                'league':     league,
            }
            chunks = chunk_text(bn)
            n = len(chunks)

            for i, cb in enumerate(chunks):
                fout.write(json.dumps({
                    'chunk_id':     f"{art['article_id']}_{i}",
                    'article_id':   art['article_id'],
                    'chunk_index':  i,
                    'total_chunks': n,
                    'text':         build_chunk_text(enriched, cb, i, n),
                    'title':        title,
                    'title_norm':   tn,
                    'body_clean':   bc,
                    'section':      section,
                    'article_type': art.get('article_type', 'article'),
                    'pub_date':     art.get('pub_date', ''),
                    'teams':        teams,
                    'league':       league,
                    'tags':         art.get('tags', []),
                    'source_url':   art.get('source_url', ''),
                    'image':        art.get('image', ''),
                }, ensure_ascii=False) + '\n')
                total_chunks += 1

            type_c[art.get('article_type', 'article')] += 1
            league_c[league] += 1

    processed = len(articles) - skipped - skipped_section
    avg = int(sum(body_lens) / len(body_lens)) if body_lens else 0

    stats = {
        'total_articles':          len(articles),
        'articles_processed':      processed,
        'skipped_short_body':      skipped,
        'skipped_non_football':    skipped_section,
        'total_chunks':            total_chunks,
        'avg_body_length':         avg,
        'min_body_length':         min(body_lens) if body_lens else 0,
        'max_body_length':         max(body_lens) if body_lens else 0,
        'article_types':           dict(type_c),
        'league_coverage':         dict(league_c),
        'processed_at':            datetime.now().isoformat(),
    }
    STATS_FILE.write_text(json.dumps(stats, ensure_ascii=False, indent=2))

    log.info(f"\n Preprocessing complete!")
    log.info(f"   Articles total      : {len(articles)}")
    log.info(f"   Processed           : {processed}")
    log.info(f"   Skipped (short body): {skipped}")
    log.info(f"   Skipped (non-football sections): {skipped_section}  "
             f"{sorted(NON_FOOTBALL_SECTIONS)}")
    log.info(f"   Chunks              : {total_chunks}")
    log.info(f"   Avg body            : {avg} chars")
    log.info(f"   Types               : {dict(type_c)}")
    log.info(f"   Leagues             : {dict(league_c)}")
    log.info(f"   Output              : {CHUNKS_FILE}")
    return stats


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='FilGoalBot Preprocessing Pipeline v4')
    parser.add_argument('--input', default=str(RAW_FILE), help='Path to raw articles.jsonl')
    args = parser.parse_args()
    run_pipeline(Path(args.input))