File size: 45,166 Bytes
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20c3639
cffe6c7
 
171d541
 
 
 
20c3639
171d541
 
 
660d674
171d541
 
 
 
 
 
 
 
 
84edce3
171d541
 
 
 
 
 
 
 
 
 
5d305bb
171d541
20c3639
0e2c007
171d541
 
84edce3
 
01c7c47
84edce3
 
 
 
 
 
171d541
84edce3
171d541
84edce3
171d541
 
84edce3
171d541
 
 
 
 
 
 
84edce3
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84edce3
171d541
 
 
a37fb93
171d541
 
 
 
 
 
 
 
a37fb93
 
171d541
 
 
 
 
 
a37fb93
 
 
 
 
 
 
 
20c3639
a37fb93
 
 
 
20c3639
a37fb93
 
 
 
 
 
1068e07
3356c03
 
 
 
 
 
 
 
 
 
7a75841
 
 
3356c03
 
 
 
 
 
 
1068e07
3356c03
 
1068e07
 
 
 
 
 
 
 
 
 
 
a37fb93
 
1068e07
a37fb93
1068e07
 
a37fb93
1068e07
 
 
3356c03
a37fb93
 
 
 
 
 
1068e07
 
 
3356c03
a37fb93
20c3639
a37fb93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d44b3f
a37fb93
 
171d541
 
 
84edce3
171d541
 
84edce3
171d541
 
84edce3
171d541
 
84edce3
171d541
 
84edce3
171d541
84edce3
 
171d541
 
a37fb93
 
 
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37fb93
 
 
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37fb93
 
 
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37fb93
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84edce3
 
 
a37fb93
 
 
 
 
 
 
 
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20c3639
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84edce3
01c7c47
 
171d541
 
 
 
20c3639
 
 
 
 
 
 
 
 
 
 
 
 
01c7c47
 
 
 
 
 
 
 
20c3639
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171d541
 
 
 
 
 
 
 
a37fb93
 
 
171d541
 
 
 
 
 
84edce3
 
 
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37fb93
 
 
171d541
 
 
84edce3
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37fb93
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84edce3
 
 
171d541
20c3639
171d541
 
 
 
 
 
84edce3
 
 
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84edce3
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84edce3
 
 
 
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01c7c47
 
 
 
 
 
 
 
171d541
 
 
 
 
 
1da72dd
 
171d541
 
 
 
 
 
 
 
 
 
5d305bb
 
 
 
 
 
 
 
 
 
 
 
20c3639
 
5d305bb
 
 
 
 
171d541
 
 
 
 
ad95ea6
171d541
 
 
 
84edce3
171d541
 
 
20c3639
171d541
20c3639
ad95ea6
1da72dd
171d541
 
 
 
 
 
 
 
 
 
 
ad95ea6
 
 
3356c03
 
 
7a75841
 
 
 
 
 
ad95ea6
5d305bb
ad95ea6
 
 
 
20c3639
ad95ea6
5d305bb
 
ad95ea6
 
1068e07
171d541
c554ef1
 
 
 
5d305bb
c554ef1
 
 
 
171d541
 
 
 
 
 
 
 
 
 
5d305bb
 
 
 
 
 
1068e07
5d305bb
171d541
 
 
a37fb93
171d541
a37fb93
 
c554ef1
 
5d305bb
20c3639
5d305bb
a37fb93
c554ef1
01c7c47
 
 
c554ef1
 
 
 
 
 
 
01c7c47
 
 
 
 
 
 
 
 
 
 
 
 
 
c554ef1
171d541
3356c03
 
 
171d541
 
 
 
5d305bb
171d541
 
1068e07
171d541
 
 
 
 
 
 
 
 
 
 
 
 
20c3639
171d541
 
 
 
5d305bb
 
 
 
 
 
 
 
 
 
 
20c3639
5d305bb
 
 
 
 
 
 
 
 
 
 
 
20c3639
5d305bb
 
 
 
 
 
 
 
 
 
 
 
 
 
7a75841
 
 
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3356c03
171d541
 
 
 
 
a37fb93
 
 
 
 
 
 
 
 
 
7a75841
 
 
cffe6c7
 
 
 
 
 
 
 
 
 
 
20c3639
cffe6c7
 
1068e07
cffe6c7
 
a37fb93
1068e07
 
 
 
 
 
3356c03
1068e07
3356c03
a37fb93
 
 
 
 
 
 
20c3639
a37fb93
 
 
 
 
 
 
 
 
 
cffe6c7
 
 
 
 
 
1068e07
a37fb93
 
cffe6c7
a37fb93
7a75841
 
 
a37fb93
 
 
7a75841
 
 
1068e07
 
7a75841
a37fb93
cffe6c7
84edce3
 
cffe6c7
5d305bb
 
 
 
 
 
84edce3
171d541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a37fb93
171d541
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
#!/usr/bin/env python3
"""
scrape_gh_docs.py

Purpose:
 - Given a list of GitHub repositories (owner/repo or full GitHub URLs), locate documentation and download it.
 - Prefer fetching only documentation folders (docs, doc, documentation) when possible.

Key features:
 - URL normalization: accepts either owner/repo or full https://github.com/owner/repo URLs.
 - Strategies:
    1) Contents API: detect and download only the 'docs/' folder.
    2) Sparse checkout (optional): `--prefer-sparse` to git sparse-checkout only docs folders (no REST usage).
    3) Zip fallback (optional): `--prefer-zip` to download a codeload zip (no REST usage) and extract only .md.
    4) Org heuristics and search fallback via GitHub API if direct docs folder not found.
 - Content selection: `--only-md` limits downloads/extractions to Markdown files.
 - Central config: reads YAML from `scrape_gh_docs_config.yaml` to control inputs/outputs and strategies.
 - Note: Repository metadata fetching and filtering (e.g., by age/language/topics) has been split
   into a separate pipeline step (see `data_collection_utils/fetch_gh_meta.py` and `clean/clean_meta.py`).
 - Quiet mode: `--quiet` or YAML `quiet: true` switches logging to warnings+ so tqdm progress stays visible.
 - No-fetch mode: `--no-fetch` rebuilds Parquet(s) from existing outdir without any network calls. You can also emit a per-file texts Parquet via `--texts-parquet` or YAML `texts_parquet`.

Typical usage:
    uv run starting_data/scrape_gh_docs.py --config starting_data/scrape_gh_docs_config.yaml

Outputs:
 - Saves files under `<outdir>/<owner>__<repo>/...`.
 - Writes a per-file Parquet to `<outdir>/cleaned_texts_on_metadata_only.parquet`.
 - Appends repos with <10 .md files to `md-failed.txt`.
"""

import os
import sys
import zipfile
import shutil
import re
import argparse
from urllib.parse import urlparse
from pathlib import Path
from tqdm import tqdm
import concurrent.futures
import threading
from typing import Optional
from typing import Dict, Any, List

import pandas as pd
import subprocess
import yaml
import duckdb
import logging
from datetime import datetime
import langid  # https://github.com/saffsd/langid.py


from github_api_utils import (
    download_file,
    download_readme_to,
    get_repo_info,
    get_contents,
    get_owner_type,
    get_org_repos,
    search_repos,
)

# Note: core Github helpers and repo tree builders are defined in the modules above

# === Helpers (local only) ===


# moved: request_json -> github_api_utils.request_json


def write_text(path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(data, encoding="utf-8")


# moved: session management -> github_api_utils.get_session


def ensure_github_token(token_file: Optional[str]) -> str:
    """Ensure GITHUB_TOKEN is set, optionally reading it from token_file.
    Exits the program if the token cannot be obtained.
    """
    token = os.getenv("GITHUB_TOKEN")
    if not token and token_file:
        p = Path(token_file)
        if p.exists():
            tok = p.read_text(encoding="utf-8").strip()
            if tok:
                os.environ["GITHUB_TOKEN"] = tok
                token = tok
            else:
                logger.error(f"Token file is empty: {p}")
        else:
            logger.error(f"Token file not found at: {p}")
    if not token:
        where = f" (from file {token_file})" if token_file else ""
        logger.error(
            f"GITHUB_TOKEN is required. Set it in the environment or provide --token-file pointing to a file containing the token{where}."
        )
        sys.exit(2)
    return token


def append_line_threadsafe(
    path: Path, text: str, lock: Optional[threading.Lock] = None
):
    """Append a single line to a file in a thread-safe way."""
    path.parent.mkdir(parents=True, exist_ok=True)
    if lock:
        lock.acquire()
    try:
        with open(path, "a", encoding="utf-8") as f:
            f.write(text)
    finally:
        if lock:
            lock.release()


# moved: download_file -> github_api_utils.download_file


def count_md_files(root_dir: Path):
    return sum(1 for p in root_dir.rglob("*.md") if p.is_file())


def safe_name(s: str):
    return re.sub(r"[^A-Za-z0-9._-]+", "_", s)


def copy_tree_only_md(src_dir: Path, dst_dir: Path):
    for p in src_dir.rglob("*.md"):
        if not p.is_file():
            continue
        rel = p.relative_to(src_dir)
        target = dst_dir / rel
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(p, target)


# === Scanning helpers (deduplicate per-file scanning and md-failed computation) ===


def collect_md_rows_for_repo_dir(
    d: Path,
    outdir: Path,
    lang_filter_value: Optional[str],
    min_text_chars_value: int,
    updated_at: str,
) -> List[Dict[str, Any]]:
    """Scan a single <owner>__<repo> directory for Markdown files and build row dicts.

    Returns a list of rows with fields: owner, repo, repo_dir, file_rel_repo,
    file_rel_outdir, size, mtime, lang, content, updated_at.
    """
    try:
        owner, repo = d.name.split("__", 1)
    except ValueError:
        return []
    rows: List[Dict[str, Any]] = []
    # Collect candidate files:
    md_files: List[Path] = list(d.rglob("*.md"))
    root_readmes: List[Path] = [
        p for p in d.iterdir() if p.is_file() and p.name.lower().startswith("readme")
    ]
    # Determine repo-level language once, if filtering is enabled
    repo_lang: Optional[str] = None
    should_filter_lang = (
        lang_filter_value is not None and str(lang_filter_value).strip() != ""
    )
    if should_filter_lang:
        src_for_lang: Optional[Path] = (
            root_readmes[0] if root_readmes else (md_files[0] if md_files else None)
        )
        if src_for_lang is not None and src_for_lang.is_file():
            text0 = src_for_lang.read_text(encoding="utf-8", errors="replace")
            # Classify once per repo using README (or first .md) regardless of length
            lid_code, _ = langid.classify(text0)
            repo_lang = lid_code

    # Merge candidates (all .md + root-level README variants), de-duplicated
    candidates: List[Path] = []
    candidates.extend(md_files)
    candidates.extend(root_readmes)
    seen_paths = set()
    unique_candidates: List[Path] = []
    for p in candidates:
        rp = p.resolve()
        if rp in seen_paths:
            continue
        seen_paths.add(rp)
        unique_candidates.append(p)

    for fpath in unique_candidates:
        if not fpath.is_file():
            continue
        try:
            rel_repo = fpath.relative_to(d)
        except Exception:
            rel_repo = fpath.name
        text = fpath.read_text(encoding="utf-8", errors="replace")
        include = True
        # Always include README files regardless of length/language
        is_readme = fpath.parent == d and fpath.name.lower().startswith("readme")
        if not is_readme and should_filter_lang:
            include = repo_lang == lang_filter_value
        if include:
            row = {
                "owner": owner,
                "repo": repo,
                "repo_dir": d.name,
                "file_rel_repo": str(rel_repo),
                "file_rel_outdir": str(fpath.relative_to(outdir)),
                "size": fpath.stat().st_size,
                "mtime": int(fpath.stat().st_mtime),
                "lang": repo_lang,
                "content": text,
                "updated_at": updated_at,
            }
            rows.append(row)
    return rows


def compute_md_failed_for_existing(outdir: Path, md_failed_path: Path):
    """Scan existing <owner>__<repo> directories and append low-md-count entries to md-failed.

    This mirrors the docs folder detection used in process_repo_entry().
    """
    repo_dirs = [
        d
        for d in outdir.iterdir()
        if d.is_dir() and "__" in d.name and not d.name.startswith("tmp_")
    ]
    with tqdm(total=len(repo_dirs), desc="Existing repos") as pbar:
        for d in repo_dirs:
            try:
                owner, repo = d.name.split("__", 1)
            except ValueError:
                pbar.update(1)
                continue
            # Detect docs folder similar to process_repo_entry
            if (d / "docs").exists():
                docs_folder = d / "docs"
            else:
                found = None
                for p in d.rglob("docs"):
                    if p.is_dir():
                        found = p
                        break
                docs_folder = found if found else d
            md_count = count_md_files(docs_folder)
            logger.info(
                f"[no-fetch] {owner}/{repo}: {md_count} .md files in '{docs_folder.relative_to(outdir)}'"
            )
            if md_count < 10:
                append_line_threadsafe(
                    md_failed_path, f"{owner}/{repo}  # md-count={md_count}\n"
                )
            pbar.update(1)


# === Main logic for a single repo ===


# moved: get_repo_info -> github_api_utils.get_repo_info


# moved: get_default_branch -> github_api_utils.get_default_branch


# moved: get_contents -> github_api_utils.get_contents


# moved: get_owner_type -> github_api_utils.get_owner_type


# moved: get_org_repos -> github_api_utils.get_org_repos


# moved: search_repos -> github_api_utils.search_repos


def download_docs_folder(
    owner, repo, docs_path, default_branch, outdir, only_md: bool = False
):
    """
    docs_path: path to folder in repo, e.g., 'docs' or 'website/docs'
    Will download all files under that folder recursively using the contents API.
    """
    # Get contents of the docs_path
    contents = get_contents(owner, repo, docs_path, ref=default_branch)
    if not contents:
        return False
    if isinstance(contents, dict) and contents.get("type") == "file":
        # Single file - download it
        dest_root = outdir / safe_name(f"{owner}__{repo}") / docs_path
        dest_root.parent.mkdir(parents=True, exist_ok=True)
        download_file(contents["download_url"], dest_root)
        return True
    if isinstance(contents, list):
        for item in contents:
            if item["type"] == "dir":
                # recursively fetch
                subpath = item["path"]
                download_folder_via_api(
                    owner,
                    repo,
                    subpath,
                    default_branch,
                    outdir / safe_name(f"{owner}__{repo}"),
                    only_md=only_md,
                )
            elif item["type"] == "file":
                if (not only_md) or item["name"].lower().endswith(".md"):
                    rel = Path(item["path"])
                    dest = outdir / safe_name(f"{owner}__{repo}") / rel
                    download_file(item["download_url"], dest)
        return True
    return False


def download_folder_via_api(
    owner, repo, path, ref, dest_root: Path, only_md: bool = False
):
    """
    Recursively download a path via contents API and save to dest_root/path
    """
    contents = get_contents(owner, repo, path, ref=ref)
    if not contents:
        return
    if isinstance(contents, dict) and contents.get("type") == "file":
        if (not only_md) or contents.get("name", "").lower().endswith(".md"):
            dest = dest_root / contents["path"]
            dest.parent.mkdir(parents=True, exist_ok=True)
            download_file(contents["download_url"], dest)
        return
    if isinstance(contents, list):
        for item in contents:
            if item["type"] == "dir":
                download_folder_via_api(
                    owner, repo, item["path"], ref, dest_root, only_md=only_md
                )
            elif item["type"] == "file":
                if (not only_md) or item["name"].lower().endswith(".md"):
                    dest = dest_root / item["path"]
                    dest.parent.mkdir(parents=True, exist_ok=True)
                    download_file(item["download_url"], dest)


def download_repo_zip(owner, repo, ref, outdir, only_md: bool = False):
    """
    Download zipball and extract into outdir/{owner}__{repo}/
    """
    # Prefer codeload endpoint to avoid REST API rate limits
    ref = ref or "main"
    url = f"https://codeload.github.com/{owner}/{repo}/zip/refs/heads/{ref}"
    tmpzip = outdir / safe_name(f"tmp_{owner}_{repo}.zip")
    download_file(url, tmpzip)
    extract_to = outdir / safe_name(f"{owner}__{repo}")
    extract_to.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(tmpzip, "r") as z:
        if only_md:
            # Extract only .md files, preserving paths (strip the top-level folder added by GitHub)
            top_prefix = None
            for info in z.infolist():
                if info.is_dir():
                    continue
                name = info.filename
                if top_prefix is None:
                    top_prefix = name.split("/", 1)[0] + "/"
                rel = name[len(top_prefix) :] if name.startswith(top_prefix) else name
                if not rel.lower().endswith(".md"):
                    continue
                dest = extract_to / rel
                dest.parent.mkdir(parents=True, exist_ok=True)
                with z.open(info) as src, open(dest, "wb") as dst:
                    shutil.copyfileobj(src, dst)
        else:
            z.extractall(extract_to)
            # After extract, find top-level folder (github zip adds a prefix), move its contents up
            entries = list(extract_to.iterdir())
            if len(entries) == 1 and entries[0].is_dir():
                inner = entries[0]
                for item in inner.iterdir():
                    shutil.move(str(item), str(extract_to))
                inner.rmdir()
    tmpzip.unlink(missing_ok=True)
    return extract_to


# === Repo structure helpers moved to data_collection_utils.repo_tree ===


def sparse_checkout_docs(
    owner: str,
    repo: str,
    branch: str,
    outdir: Path,
    patterns: Optional[List[str]] = None,
    only_md: bool = False,
) -> bool:
    """Use git sparse-checkout to fetch only documentation folders for a given branch.
    patterns: list of sparse-checkout patterns. Defaults to ['docs', 'doc', 'documentation', '**/docs', '**/doc', '**/documentation'].
    Returns True if at least one documentation folder was found and copied into outdir/<owner__repo>/...
    """
    repo_url = f"https://github.com/{owner}/{repo}.git"
    dest_root = outdir / safe_name(f"{owner}__{repo}")
    tmp_dir = outdir / safe_name(f"tmp_sparse_{owner}_{repo}_{branch}")
    if patterns is None:
        patterns = [
            "docs",
            "doc",
            "documentation",
            "**/docs",
            "**/doc",
            "**/documentation",
        ]

    # Clean any previous temp directory
    if tmp_dir.exists():
        shutil.rmtree(tmp_dir, ignore_errors=True)

    try:
        # Clone sparse without checkout
        subprocess.run(
            [
                "git",
                "clone",
                "--depth",
                "1",
                "--filter=blob:none",
                "--sparse",
                "-b",
                branch,
                repo_url,
                str(tmp_dir),
            ],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        # Configure sparse-checkout (non-cone) to include patterns
        subprocess.run(
            ["git", "-C", str(tmp_dir), "sparse-checkout", "init", "--no-cone"],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        subprocess.run(
            [
                "git",
                "-C",
                str(tmp_dir),
                "sparse-checkout",
                "set",
                *patterns,
            ],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        # After sparse-checkout, find matched documentation directories
        matched_dirs: List[Path] = []
        for pat in ["docs", "doc", "documentation"]:
            for p in tmp_dir.rglob(pat):
                if p.is_dir():
                    matched_dirs.append(p)

        if not matched_dirs:
            return False

        # Copy only .md files from all matched directories preserving relative paths
        for d in matched_dirs:
            rel = d.relative_to(tmp_dir)
            target_dir = dest_root / rel
            target_dir.parent.mkdir(parents=True, exist_ok=True)
            if target_dir.exists():
                shutil.rmtree(target_dir)
            copy_tree_only_md(d, target_dir)
        return True
    finally:
        # Cleanup temp directory
        if tmp_dir.exists():
            shutil.rmtree(tmp_dir, ignore_errors=True)


# Heuristics to find candidate docs repo names in org repos:
DOC_NAME_PATTERNS = [
    re.compile(r"^docs?$", re.I),
    re.compile(r"^documentation$", re.I),
    re.compile(r"^doc$", re.I),
    re.compile(r".*[-_.]docs?$", re.I),
    re.compile(r"^docs[-_].*", re.I),
    re.compile(r".*doc.*", re.I),
]


def find_docs_repo_in_org(org_repos, project_repo_name=None):
    # prefer exact matches like 'docs', 'documentation'
    candidates = []
    for r in org_repos:
        name = r.get("name", "")
        for p in DOC_NAME_PATTERNS:
            if p.fullmatch(name) or p.match(name):
                candidates.append(r)
                break
    # If project_repo_name given, prefer repos containing the project name + doc keywords
    if project_repo_name:
        project_lower = project_repo_name.lower()
        scored = []
        for r in candidates:
            name = r.get("name", "").lower()
            score = 0
            if project_lower in name:
                score += 10
            if name.startswith("docs") or name.endswith("docs"):
                score += 1
            scored.append((score, r))
        scored.sort(reverse=True, key=lambda x: x[0])
        if scored:
            return scored[0][1]
    if candidates:
        return candidates[0]
    return None


# === Orchestrator for each repo entry ===


def _parse_owner_repo(line: str) -> Optional[tuple[str, str]]:
    s = line.strip()
    if not s:
        return None
    if s.startswith("http://") or s.startswith("https://"):
        p = urlparse(s)
        if p.netloc != "github.com":
            return None
        parts = [part for part in p.path.split("/") if part]
        if len(parts) < 2:
            return None
        owner, repo = parts[0], parts[1]
        if repo.endswith(".git"):
            repo = repo[:-4]
        return owner, repo
    # fallback: expect owner/repo
    if "/" in s:
        owner, repo = s.split("/", 1)
        return owner, repo
    return None


def process_repo_entry(
    owner_repo,
    outdir: Path,
    md_failed_path: Path,
    dry_run=False,
    lock: Optional[threading.Lock] = None,
    prefer_zip: bool = False,
    prefer_sparse: bool = False,
    only_md: bool = False,
    resume: bool = True,
):
    owner_repo = owner_repo.strip()
    if not owner_repo or owner_repo.startswith("#"):
        return None
    parsed = _parse_owner_repo(owner_repo)
    if not parsed:
        logger.warning(
            f"invalid line (expected owner/repo or GitHub URL): '{owner_repo}'"
        )
        return None
    owner, repo = parsed
    logger.info(f"Processing {owner}/{repo}")
    # Default result skeleton; we will fill in default_branch depending on path
    result: Dict[str, Any] = {
        "owner": owner,
        "repo": repo,
        "default_branch": None,
        "method": None,
        "docs_found": False,
        "docs_folder": None,
        "md_count": None,
        "status": "ok",
        "note": None,
        "docs_found_in": None,
        "readme_found": False,
        "readme_filename": None,
    }
    got_any = False
    default_branch = None

    # Resume: if repo directory already exists, skip network fetch and use existing files
    repo_saved_root = outdir / safe_name(f"{owner}__{repo}")
    if resume and repo_saved_root.exists():
        # Determine docs folder similar to below logic
        if (repo_saved_root / "docs").exists():
            docs_folder = repo_saved_root / "docs"
        else:
            found = None
            for p in repo_saved_root.rglob("docs"):
                if p.is_dir():
                    found = p
                    break
            docs_folder = found if found else repo_saved_root
        # Download README at repo root into saved directory
        try:
            info = download_readme_to(owner, repo, repo_saved_root, ref=None)
            if info:
                result["readme_found"] = True
                result["readme_filename"] = info.get("name")
        except Exception:
            pass
        md_count = count_md_files(docs_folder)
        result["default_branch"] = None
        result["method"] = "resume-existing"
        result["docs_found_in"] = None
        result["docs_found"] = True
        assert docs_folder.is_relative_to(outdir)
        result["docs_folder"] = str(docs_folder.relative_to(outdir))
        result["md_count"] = int(md_count)
        if md_count < 10:
            append_line_threadsafe(
                md_failed_path, f"{owner}/{repo}  # md-count={md_count}\n", lock
            )
            result["status"] = "low-md-count"
        return result

    if prefer_sparse:
        # Try to fetch only docs/ folder via git sparse-checkout without REST API
        for branch_guess in ("main", "master"):
            try:
                logger.info(
                    f"prefer_sparse: attempting docs/ for {owner}/{repo}@{branch_guess} via git sparse-checkout"
                )
                if not dry_run:
                    ok = sparse_checkout_docs(
                        owner, repo, branch_guess, outdir, only_md=only_md
                    )
                else:
                    ok = True
                if ok:
                    default_branch = branch_guess
                    result["default_branch"] = branch_guess
                    result["method"] = "sparse_docs"
                    result["docs_found_in"] = (
                        f"https://github.com/{owner}/{repo}/tree/{branch_guess}/docs"
                    )
                    got_any = True
                    break
            except FileNotFoundError:
                logger.error("'git' not found. Install git to use --prefer-sparse.")
                break
            except subprocess.CalledProcessError as e:
                logger.warning(
                    f"prefer_sparse: git error for {owner}/{repo}@{branch_guess}: {e}"
                )
        if not got_any:
            logger.info(
                f"prefer_sparse: docs/ not found via sparse-checkout for {owner}/{repo}. Continuing with other strategies."
            )

    if prefer_zip and not got_any:
        # Try to download repo zips without using REST API to avoid rate limiting
        for branch_guess in ("main", "master"):
            try:
                logger.info(
                    f"prefer_zip: attempting {owner}/{repo}@{branch_guess} via codeload"
                )
                if not dry_run:
                    download_repo_zip(
                        owner, repo, branch_guess, outdir, only_md=only_md
                    )
                default_branch = branch_guess
                result["default_branch"] = branch_guess
                result["method"] = "zip_whole_repo"
                result["docs_found_in"] = f"https://github.com/{owner}/{repo}"
                got_any = True
                break
            except Exception as e:
                logger.warning(
                    f"prefer_zip: failed to download {owner}/{repo}@{branch_guess}: {e}"
                )
        if not got_any:
            logger.warning(
                f"prefer_zip failed for {owner}/{repo} (both main and master). Marking as docs-not-found."
            )
            append_line_threadsafe(
                md_failed_path, f"{owner}/{repo}  # zip-failed\n", lock
            )
            result["status"] = "docs-not-found"
            return result
    if not got_any:
        # API-driven path (only if neither prefer_sparse nor prefer_zip succeeded)
        repo_json = get_repo_info(owner, repo)
        if not repo_json:
            logger.error(f"Cannot fetch repo metadata for {owner}/{repo}")
            append_line_threadsafe(
                md_failed_path, f"{owner}/{repo}  # metadata-failed\n", lock
            )
            return {
                "owner": owner,
                "repo": repo,
                "default_branch": None,
                "method": None,
                "docs_found": False,
                "docs_folder": None,
                "md_count": None,
                "status": "metadata-failed",
                "note": "failed to fetch repo metadata",
            }
        default_branch = repo_json.get("default_branch", "main")
        result["default_branch"] = default_branch

    # Step 1: check docs/ in repo root (skipped if prefer_zip/prefer_sparse already downloaded docs or repo)
    docs_path = "docs"
    logger.info(
        f"Checking for '{docs_path}/' in {owner}/{repo} (branch {default_branch})"
    )
    contents = (
        None
        if (prefer_zip or prefer_sparse)
        else get_contents(owner, repo, docs_path, ref=default_branch)
    )
    saved_root = outdir / safe_name(f"{owner}__{repo}")
    if contents:
        if isinstance(contents, list):  # docs/ exists as directory
            logger.info(f"Found docs/ directory in {owner}/{repo}. Downloading...")
            if not dry_run:
                download_folder_via_api(
                    owner, repo, docs_path, default_branch, saved_root, only_md=only_md
                )
            got_any = True
            result["method"] = "docs_folder_in_repo"
            result["docs_found_in"] = (
                f"https://github.com/{owner}/{repo}/tree/{default_branch}/{docs_path}"
            )
        elif isinstance(contents, dict) and contents.get("type") == "file":
            logger.info("Found file at docs (single-file). Downloading...")
            if not dry_run:
                download_folder_via_api(
                    owner, repo, docs_path, default_branch, saved_root, only_md=only_md
                )
            got_any = True
            result["method"] = "docs_file_in_repo"
            result["docs_found_in"] = (
                f"https://github.com/{owner}/{repo}/blob/{default_branch}/{docs_path}"
            )
        else:
            # contents returned but unknown structure: skip to next steps
            pass
    else:
        # Not found or error
        pass

    if not got_any:
        # Step 2: search org repos for docs repo by name heuristics
        org_repos = get_org_repos(owner)
        candidate = find_docs_repo_in_org(org_repos, project_repo_name=repo)
        if candidate:
            cand_name = candidate["name"]
            logger.info(
                f"Found candidate docs repo in org: {owner}/{cand_name} -> will download repo zip"
            )
            if not dry_run:
                download_repo_zip(
                    owner, cand_name, candidate.get("default_branch", "main"), outdir
                )
            got_any = True
            result["method"] = "org_docs_repo_zip"
            result["docs_found_in"] = f"https://github.com/{owner}/{cand_name}"
        else:
            # Step 3 fallback: use search API for repos in owner scope with '{repo} docs' in name
            owner_type = get_owner_type(owner)
            scope = f"org:{owner}" if owner_type == "Organization" else f"user:{owner}"
            q = f"{repo} docs in:name {scope}"
            logger.info(f"Trying fallback search: '{q}'")
            items = search_repos(q, per_page=5)
            if items:
                first = items[0]
                logger.info(
                    f"Fallback search found {first['full_name']}. Downloading repo zip"
                )
                if not dry_run:
                    download_repo_zip(
                        first["owner"]["login"],
                        first["name"],
                        first.get("default_branch", "main"),
                        outdir,
                    )
                got_any = True
                result["method"] = "search_repo_zip"
                result["docs_found_in"] = first.get(
                    "html_url",
                    f"https://github.com/{first['owner']['login']}/{first['name']}",
                )

    if not got_any:
        logger.warning(
            f"No docs found for {owner}/{repo} after heuristics. Marking as md-failed."
        )
        append_line_threadsafe(
            md_failed_path, f"{owner}/{repo}  # docs-not-found\n", lock
        )
        result["status"] = "docs-not-found"
        result["docs_found"] = False
        return result

    # At this point we have a folder under outdir/<owner__repo>/... containing docs or an entire repo.
    # We need to find the docs folder path inside that folder to count .md files that are "inside of the folders".
    repo_saved_root = outdir / safe_name(f"{owner}__{repo}")
    # Attempt to determine the docs folder: prefer a top-level 'docs' subfolder; else count all .md under the saved root
    if (repo_saved_root / "docs").exists():
        docs_folder = repo_saved_root / "docs"
    else:
        # find any folder with name 'docs' anywhere
        found = None
        for p in repo_saved_root.rglob("docs"):
            if p.is_dir():
                found = p
                break
        docs_folder = found if found else repo_saved_root
    # Ensure README is downloaded at repo root under saved directory
    try:
        info = download_readme_to(owner, repo, repo_saved_root, ref=default_branch)
        if info:
            result["readme_found"] = True
            result["readme_filename"] = info.get("name")
    except Exception:
        pass

    md_count = count_md_files(docs_folder)
    logger.info(
        f"Found {md_count} .md files for {owner}/{repo} in '{docs_folder.relative_to(outdir)}'"
    )
    result["docs_found"] = True
    assert docs_folder.is_relative_to(outdir)
    result["docs_folder"] = str(docs_folder.relative_to(outdir))
    result["md_count"] = int(md_count)
    if md_count < 10:
        append_line_threadsafe(
            md_failed_path, f"{owner}/{repo}  # md-count={md_count}\n", lock
        )
        result["status"] = "low-md-count"

    return result


def _init_duckdb(con):
    con.execute(
        """
        CREATE TABLE IF NOT EXISTS texts (
          owner TEXT,
          repo TEXT,
          repo_dir TEXT,
          file_rel_repo TEXT,
          file_rel_outdir TEXT,
          size BIGINT,
          mtime BIGINT,
          lang TEXT,
          content TEXT,
          updated_at TEXT
        );
        """
    )


# === CLI ===


def main():
    parser = argparse.ArgumentParser(
        description="Scrape docs/ folders for a list of GitHub repos (configuration via YAML only)."
    )
    parser.add_argument(
        "--no-fetch",
        action="store_true",
        help="Do not perform any network downloads; only scan existing outdir to build Parquet and md-failed",
    )
    args = parser.parse_args()

    # Load YAML config next to this script (scrape_gh_docs_config.yaml) if present
    cfg: Dict[str, Any] = {}
    cfg_path = Path(__file__).with_name("scrape_gh_docs_config.yaml")
    if cfg_path.exists():
        cfg = yaml.safe_load(cfg_path.read_text(encoding="utf-8")) or {}

    # Resolve effective configuration (YAML takes precedence for simplicity)
    # IMPORTANT: resolve any relative paths in YAML against the config file directory
    def _resolve_cfg_path(val):
        if val is None:
            return None
        p = Path(val)
        if not p.is_absolute() and cfg_path is not None:
            p = (cfg_path.parent / p).resolve()
        return str(p)

    outdir_value = _resolve_cfg_path(cfg.get("outdir", "output"))
    md_failed_value = _resolve_cfg_path(cfg.get("md_failed", "md-failed.txt"))
    dry_run_value = bool(cfg.get("dry_run", False))
    # Concurrency settings
    # Backwards compat: if legacy 'workers' is present, use as fallback for both phases
    legacy_workers = cfg.get("workers")
    scrape_workers_value = int(
        cfg.get("scrape_workers", legacy_workers if legacy_workers is not None else 4)
    )
    rebuild_workers_value = int(
        cfg.get("rebuild_workers", legacy_workers if legacy_workers is not None else 4)
    )
    texts_parquet_value = _resolve_cfg_path(cfg.get("texts_parquet"))
    duckdb_path_value = _resolve_cfg_path(cfg.get("duckdb_path"))
    token_file_value = _resolve_cfg_path(cfg.get("token_file"))
    prefer_zip_value = bool(cfg.get("prefer_zip", False))
    prefer_sparse_value = bool(cfg.get("prefer_sparse", False))
    only_md_value = bool(cfg.get("only_md", False))
    resume_value = bool(cfg.get("resume", True))
    quiet_value = bool(cfg.get("quiet", False))
    # CLI should override YAML for convenience
    no_fetch_value = bool(args.no_fetch or cfg.get("no_fetch", False))
    lang_filter_value = cfg.get("lang_filter", "en")
    min_text_chars_value = int(cfg.get("min_text_chars", 200))
    postprocess_executor_value = str(cfg.get("postprocess_executor", "thread")).lower()

    def _resolve_cfg_paths(val):
        if val is None:
            return []
        if isinstance(val, (list, tuple)):
            return [_resolve_cfg_path(v) for v in val if v is not None]
        return [_resolve_cfg_path(val)]

    input_parquet_values = _resolve_cfg_paths(cfg.get("input_parquet"))

    # Configure logging (use tqdm-friendly handler)
    setup_logging(quiet=quiet_value)

    # Ensure we have a GitHub token before making any requests (unless no-fetch)
    if not no_fetch_value:
        ensure_github_token(token_file_value)

    outdir = Path(outdir_value)
    outdir.mkdir(parents=True, exist_ok=True)

    # Initialize DuckDB connection (file-backed)
    duckdb_path = (
        Path(duckdb_path_value) if duckdb_path_value else (outdir / "gh_docs.duckdb")
    )
    con = duckdb.connect(str(duckdb_path))
    _init_duckdb(con)
    logger.info(f"Opened DuckDB at '{duckdb_path}'")

    md_failed_path = Path(md_failed_value)
    # create/empty md_failed file
    md_failed_path.write_text("")
    # Determine which repositories to fetch. If no-fetch is set, skip fetching entirely
    if no_fetch_value:
        lines: List[str] = []
    else:
        lines: List[str] = []
        if not input_parquet_values:
            logger.error(
                "'input_parquet' is required. Configure one or more Parquet files with a 'link' column in scrape_gh_docs_config.yaml."
            )
            sys.exit(2)
        # Read repositories from one or more Parquet files; use 'link' column
        # Canonicalize to owner/repo and deduplicate by logical repo (case-insensitive)
        seen_canonical = set()
        seen_raw_invalid = set()
        for pth in input_parquet_values:
            df = pd.read_parquet(pth)
            assert "link" in df.columns, f"Parquet {pth} must contain 'link' column"
            for u in df["link"].tolist():
                s = str(u).strip()
                if not s:
                    continue
                parsed = _parse_owner_repo(s)
                if parsed:
                    owner, repo = parsed
                    key = f"{owner.lower()}/{repo.lower()}"
                    if key in seen_canonical:
                        continue
                    seen_canonical.add(key)
                    # Always submit canonical owner/repo to processing
                    lines.append(f"{owner}/{repo}")
                else:
                    # Fallback: keep exactly one copy of an invalid/raw link to surface a warning once
                    if s in seen_raw_invalid:
                        continue
                    seen_raw_invalid.add(s)
                    lines.append(s)

    logger.info(
        f"Will process {len(lines)} repo entries (fetch={'off' if no_fetch_value else 'on'}), scrape_workers={scrape_workers_value}, rebuild_workers={rebuild_workers_value}"
    )
    # Initialize locks for thread-safe writes and results accumulation
    md_failed_lock = threading.Lock()
    results_lock = threading.Lock()
    results: List[Dict[str, Any]] = []
    duckdb_lock = threading.Lock()

    # Process repositories concurrently
    run_ts = datetime.utcnow().isoformat()
    with tqdm(total=len(lines), desc="Repos") as pbar:

        def _run(lr: str):
            try:
                res = process_repo_entry(
                    lr,
                    outdir,
                    md_failed_path,
                    dry_run=dry_run_value,
                    lock=md_failed_lock,
                    prefer_zip=prefer_zip_value,
                    prefer_sparse=prefer_sparse_value,
                    only_md=only_md_value,
                    resume=resume_value,
                )
                if res is not None:
                    with results_lock:
                        results.append(res)
                    # Incremental per-repo texts persistence into DuckDB
                    owner = res.get("owner")
                    repo = res.get("repo")
                    if owner and repo and res.get("docs_found"):
                        d = outdir / safe_name(f"{owner}__{repo}")
                        if d.exists() and d.is_dir():
                            rows_one = collect_md_rows_for_repo_dir(
                                d,
                                outdir,
                                lang_filter_value,
                                min_text_chars_value,
                                run_ts,
                            )
                            if rows_one:
                                cols = [
                                    "owner",
                                    "repo",
                                    "repo_dir",
                                    "file_rel_repo",
                                    "file_rel_outdir",
                                    "size",
                                    "mtime",
                                    "lang",
                                    "content",
                                    "updated_at",
                                ]
                                df_one = pd.DataFrame(rows_one, columns=cols)
                                with duckdb_lock:
                                    con.execute("BEGIN")
                                    con.execute(
                                        "DELETE FROM texts WHERE owner = ? AND repo = ?",
                                        [owner, repo],
                                    )
                                    con.register("df_txt_one", df_one)
                                    con.execute(
                                        "INSERT INTO texts SELECT * FROM df_txt_one"
                                    )
                                    con.unregister("df_txt_one")
                                    con.execute("COMMIT")
                                logger.info(
                                    f"[incremental] {owner}/{repo}: inserted {len(rows_one)} rows into DuckDB"
                                )
            except Exception as e:
                logger.error(f"Exception while processing {lr}: {e}")
                append_line_threadsafe(
                    md_failed_path, f"{lr}  # exception\n", md_failed_lock
                )
                with results_lock:
                    results.append(
                        {
                            "owner": lr.split("/", 1)[0] if "/" in lr else None,
                            "repo": lr.split("/", 1)[1] if "/" in lr else lr,
                            "default_branch": None,
                            "method": None,
                            "docs_found": False,
                            "docs_folder": None,
                            "md_count": None,
                            "status": "exception",
                            "note": str(e),
                        }
                    )

        with concurrent.futures.ThreadPoolExecutor(
            max_workers=scrape_workers_value
        ) as executor:
            futures = [executor.submit(_run, lr) for lr in lines]
            for _ in concurrent.futures.as_completed(futures):
                pbar.update(1)

    # In no-fetch mode, compute md-failed from existing directories after (skipped) fetch
    if no_fetch_value:
        compute_md_failed_for_existing(outdir, md_failed_path)

    # After fetching (or skipping), scan outdir to build per-file dataset in parallel
    repo_dirs = [
        d
        for d in outdir.iterdir()
        if d.is_dir() and "__" in d.name and not d.name.startswith("tmp_")
    ]
    logger.info(
        f"Starting post-processing scan of {len(repo_dirs)} repos under '{outdir}' to rebuild per-file dataset"
    )
    # Rebuild texts table from filesystem by streaming per-repo inserts into DuckDB
    cols = [
        "owner",
        "repo",
        "repo_dir",
        "file_rel_repo",
        "file_rel_outdir",
        "size",
        "mtime",
        "lang",
        "content",
        "updated_at",
    ]
    total_inserted = 0
    logger.info("Clearing DuckDB 'texts' table for full rebuild")
    with duckdb_lock:
        con.execute("DELETE FROM texts")
    with tqdm(total=len(repo_dirs), desc="Collecting per-file rows (repos)") as pbar:
        executor_cls = (
            concurrent.futures.ProcessPoolExecutor
            if postprocess_executor_value == "process"
            else concurrent.futures.ThreadPoolExecutor
        )
        logger.info(
            f"Post-processing executor: {executor_cls.__name__} with workers={rebuild_workers_value}"
        )
        with executor_cls(max_workers=rebuild_workers_value) as executor:
            futures = [
                executor.submit(
                    collect_md_rows_for_repo_dir,
                    d,
                    outdir,
                    lang_filter_value,
                    min_text_chars_value,
                    run_ts,
                )
                for d in repo_dirs
            ]
            for fut in concurrent.futures.as_completed(futures):
                try:
                    rows = fut.result()
                except Exception as e:
                    logger.error(f"Error while scanning repo dir: {e}")
                    rows = []
                if rows:
                    df_chunk = pd.DataFrame(rows, columns=cols)
                    with duckdb_lock:
                        con.register("df_txt_chunk", df_chunk)
                        con.execute("INSERT INTO texts SELECT * FROM df_txt_chunk")
                        con.unregister("df_txt_chunk")
                    total_inserted += len(rows)
                    pbar.set_postfix_str(f"rows={total_inserted}")
                pbar.update(1)

    # Export texts from DuckDB to Parquet
    texts_parquet_path = (
        Path(texts_parquet_value)
        if texts_parquet_value
        else (outdir / "cleaned_texts_on_metadata_only.parquet")
    )
    try:
        texts_parquet_path.parent.mkdir(parents=True, exist_ok=True)
        logger.info(
            f"Exporting DuckDB 'texts' table to Parquet at '{texts_parquet_path}' ..."
        )
        # DuckDB does not support parameter binding for COPY target; embed the path directly
        out_path_sql = str(texts_parquet_path).replace("'", "''")
        con.execute(f"COPY (SELECT * FROM texts) TO '{out_path_sql}' (FORMAT PARQUET)")
        logger.info(
            f"Wrote per-file dataset to {texts_parquet_path} (rows={total_inserted})"
        )
    except Exception as e:
        logger.error(f"Failed to export texts to Parquet: {e}")

    # Close DB connection
    try:
        con.close()
    except Exception:
        pass

    logger.info("Done. Check output directory and md-failed.txt")


class TqdmLoggingHandler(logging.Handler):
    def emit(self, record):
        try:
            msg = self.format(record)
            tqdm.write(msg)
        except Exception:
            # As a fallback, write to stderr
            sys.stderr.write(str(record.getMessage()) + "\n")


logger = logging.getLogger("scrape_gh_docs")


def setup_logging(quiet: bool = False):
    logger.setLevel(logging.DEBUG)
    logger.propagate = False
    # Clear existing handlers to avoid duplicates on repeated runs in the same interpreter
    logger.handlers.clear()
    handler = TqdmLoggingHandler()
    handler.setFormatter(logging.Formatter("[%(levelname)s] %(message)s"))
    handler.setLevel(logging.WARNING if quiet else logging.INFO)
    logger.addHandler(handler)


if __name__ == "__main__":
    main()