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
 
 
 
 
 
 
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
#!/usr/bin/env python3
# pyright: basic, reportDeprecated=false, reportUnknownParameterType=false, reportMissingTypeArgument=false, reportUnknownVariableType=false, reportUnknownMemberType=false, reportUnknownArgumentType=false, reportUnusedCallResult=false, reportUnusedImport=false

import argparse
import html
import json
import re
import time
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
from urllib.parse import urljoin, urlparse

from utils import *


USER_AGENT = (
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
)

SITEMAP_URL = "https://www.mureka.ai/sitemap.xml"
HOME_URL = "https://www.mureka.ai/home"
API_BASE = "https://www.mureka.ai"
CDN_BASE = "https://static-cos.mureka.ai"

SUPPORTED_VERSIONS = ["v6", "v7.5", "v8"]
DEFAULT_TARGET = 2000
MAX_GENRE_PAGES = 300


def sanitize_filename(name: str) -> str:
    cleaned = re.sub(r"[^\w\-. ]+", "_", (name or "untitled").strip())
    cleaned = re.sub(r"\s+", "_", cleaned)
    return cleaned[:140] if cleaned else "untitled"


def normalize_tags(raw_tags: Any) -> List[str]:
    if isinstance(raw_tags, list):
        return [str(t).strip() for t in raw_tags if str(t).strip()]
    if isinstance(raw_tags, str):
        return [t.strip() for t in raw_tags.split(",") if t.strip()]
    return []


def detect_version_from_text(text: str) -> Optional[str]:
    t = (text or "").lower()
    if "v7.5" in t or "7.5" in t or re.search(r"\bv7\b", t):
        return "v7.5"
    if re.search(r"\bv8\b", t):
        return "v8"
    if re.search(r"\bv6\b", t):
        return "v6"
    return None


def detect_version(
    song: Dict[str, Any], feed: Optional[Dict[str, Any]] = None
) -> Optional[str]:
    candidates = [
        song.get("model"),
        song.get("model_version"),
        song.get("modelVersion"),
        (song.get("model_bandage") or {}).get("display_name")
        if isinstance(song.get("model_bandage"), dict)
        else None,
        (feed or {}).get("model"),
        song.get("title"),
        song.get("description"),
    ]
    for value in candidates:
        detected = detect_version_from_text(str(value) if value is not None else "")
        if detected:
            return detected
    return None


def canonicalize_mp3_url(raw_url: str) -> Optional[str]:
    if not raw_url:
        return None
    value = html.unescape(str(raw_url).strip())
    if not value:
        return None
    if value.startswith("http://") or value.startswith("https://"):
        return value
    cleaned = value.lstrip("/")
    if not cleaned:
        return None
    return f"{CDN_BASE}/{cleaned}"


def build_source_url(song: Dict[str, Any]) -> Optional[str]:
    share_key = str(song.get("share_key") or "").strip()
    if share_key:
        return f"https://www.mureka.ai/song-detail/{share_key}?is_from_share=1"
    song_id = str(song.get("song_id") or "").strip()
    if song_id:
        return f"https://www.mureka.ai/song-detail/{song_id}"
    return None


def request_with_backoff(
    session: requests.Session,
    method: str,
    url: str,
    limiter: RateLimiter,
    *,
    params: Optional[Dict[str, Any]] = None,
    timeout: int = 30,
    max_retries: int = 5,
) -> Optional[requests.Response]:
    delay = 1.0
    for attempt in range(1, max_retries + 1):
        limiter.wait()
        try:
            resp = session.request(
                method=method.upper(), url=url, params=params, timeout=timeout
            )
        except requests.RequestException as exc:
            if attempt == max_retries:
                logger.warning(f"Request failed for {url}: {exc}")
                return None
            time.sleep(min(delay, 30))
            delay *= 2
            continue

        if resp.status_code == 429:
            retry_after = resp.headers.get("Retry-After")
            wait_seconds = delay
            if retry_after:
                try:
                    wait_seconds = max(wait_seconds, float(retry_after))
                except ValueError:
                    pass
            logger.warning(f"429 from {url}; retrying in {wait_seconds:.1f}s")
            resp.close()
            time.sleep(min(wait_seconds, 30))
            delay *= 2
            continue

        if resp.status_code >= 500:
            logger.warning(f"Server error {resp.status_code} from {url}")
            resp.close()
            if attempt == max_retries:
                return None
            time.sleep(min(delay, 30))
            delay *= 2
            continue

        return resp

    return None


def fetch_json(
    session: requests.Session,
    endpoint: str,
    limiter: RateLimiter,
    params: Optional[Dict[str, Any]] = None,
) -> Optional[Dict[str, Any]]:
    url = endpoint if endpoint.startswith("http") else urljoin(API_BASE, endpoint)
    resp = request_with_backoff(session, "GET", url, limiter, params=params)
    if resp is None:
        return None

    try:
        if resp.status_code in {403, 404}:
            logger.warning(f"Skipping {url} with HTTP {resp.status_code}")
            return None
        if resp.status_code >= 400:
            logger.warning(f"HTTP {resp.status_code} for {url}")
            return None
        data = resp.json()
        if isinstance(data, dict):
            return data
        return None
    except ValueError:
        logger.warning(f"Failed to parse JSON from {url}")
        return None
    finally:
        resp.close()


def fetch_text(
    session: requests.Session,
    url: str,
    limiter: RateLimiter,
) -> Optional[str]:
    resp = request_with_backoff(session, "GET", url, limiter)
    if resp is None:
        return None
    try:
        if resp.status_code in {403, 404}:
            logger.warning(f"Skipping {url} with HTTP {resp.status_code}")
            return None
        if resp.status_code >= 400:
            logger.warning(f"HTTP {resp.status_code} for {url}")
            return None
        return resp.text
    finally:
        resp.close()


def parse_genre_pages_from_sitemap(xml_text: str) -> List[Tuple[str, int, str]]:
    pages: List[Tuple[str, int, str]] = []
    try:
        root = ET.fromstring(xml_text)
    except ET.ParseError as exc:
        logger.warning(f"Failed to parse sitemap XML: {exc}")
        return pages

    namespace = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
    loc_nodes = root.findall("sm:url/sm:loc", namespace)
    seen_ids: Set[int] = set()

    for loc in loc_nodes:
        raw = (loc.text or "").strip()
        if "/genre/" not in raw:
            continue
        match = re.search(r"/genre/([^/]+)/([0-9]+)", raw)
        if not match:
            continue
        slug = match.group(1)
        genre_id = int(match.group(2))
        if genre_id in seen_ids:
            continue
        seen_ids.add(genre_id)
        pages.append((raw, genre_id, slug))

    return pages


def extract_api_endpoints_from_text(text: str) -> Set[str]:
    found: Set[str] = set()
    if not text:
        return found

    for rel in re.findall(r'"(/api/[^"\s]+)"', text):
        if "{" in rel or "}" in rel:
            continue
        found.add(urljoin(API_BASE, rel))
    for rel in re.findall(r"'(/api/[^'\s]+)'", text):
        if "{" in rel or "}" in rel:
            continue
        found.add(urljoin(API_BASE, rel))
    return found


def collect_song_like_nodes(node: Any, out: List[Dict[str, Any]]) -> None:
    if isinstance(node, dict):
        if node.get("song_id") and (node.get("mp3_url") or node.get("song_url")):
            out.append(node)
        for value in node.values():
            if isinstance(value, (dict, list)):
                collect_song_like_nodes(value, out)
    elif isinstance(node, list):
        for value in node:
            if isinstance(value, (dict, list)):
                collect_song_like_nodes(value, out)


def extract_embedded_song_candidates(
    html_text: str,
    source_url: str,
    genre_hint: Optional[str] = None,
) -> List[Dict[str, Any]]:
    candidates: List[Dict[str, Any]] = []
    if not html_text:
        return candidates

    json_blobs: List[str] = []

    for pat in [
        r"window\.__INITIAL_STATE__\s*=\s*(\{.*?\});",
        r"window\.__NEXT_DATA__\s*=\s*(\{.*?\});",
        r"window\.__INITIAL_DATA__\s*=\s*(\{.*?\});",
    ]:
        json_blobs.extend(re.findall(pat, html_text, flags=re.DOTALL))

    script_json_blobs = re.findall(
        r'<script[^>]*type="application/json"[^>]*>(.*?)</script>',
        html_text,
        flags=re.DOTALL | re.IGNORECASE,
    )
    json_blobs.extend(script_json_blobs)

    for blob in json_blobs:
        text = blob.strip()
        if not text.startswith("{"):
            continue
        try:
            payload = json.loads(text)
        except ValueError:
            continue
        nodes: List[Dict[str, Any]] = []
        collect_song_like_nodes(payload, nodes)
        for song in nodes:
            candidates.append(
                {
                    "song": song,
                    "feed": {},
                    "source_hint": f"embedded:{source_url}",
                    "genre_hint": genre_hint,
                }
            )

    return candidates


def to_song_candidate(
    song: Dict[str, Any],
    feed: Optional[Dict[str, Any]],
    source_hint: str,
    genre_hint: Optional[str],
) -> Optional[Dict[str, Any]]:
    song_id = str(song.get("song_id") or "").strip()
    if not song_id:
        return None

    download_url = canonicalize_mp3_url(
        str(song.get("mp3_url") or song.get("song_url") or "")
    )
    if not download_url:
        return None

    title = str(song.get("title") or "untitled").strip() or "untitled"
    version = detect_version(song, feed)

    genres = normalize_tags(song.get("genres") or [])
    moods = normalize_tags(song.get("moods") or [])
    description = str(song.get("description") or "").strip() or None
    tags = list(dict.fromkeys([*genres, *moods]))

    if genre_hint and genre_hint not in genres:
        genres = [*genres, genre_hint]

    return {
        "track_id": song_id,
        "title": title,
        "version": version,
        "prompt": description,
        "genre": genres[0] if genres else genre_hint,
        "genres": genres,
        "moods": moods,
        "tags": tags,
        "source_url": build_source_url(song),
        "download_url": download_url,
        "source_hint": source_hint,
    }


def pick_version_for_candidate(
    detected: Optional[str],
    requested_versions: List[str],
    counts: Dict[str, int],
    target: int,
    fallback_counter: List[int],
) -> Optional[str]:
    pending = [v for v in requested_versions if counts.get(v, 0) < target]
    if not pending:
        return None

    if detected in pending:
        return detected

    if len(requested_versions) == 1:
        only = requested_versions[0]
        return only if counts.get(only, 0) < target else None

    min_count = min(counts.get(v, 0) for v in pending)
    min_versions = [v for v in pending if counts.get(v, 0) == min_count]
    idx = fallback_counter[0] % len(min_versions)
    fallback_counter[0] += 1
    return min_versions[idx]


def load_existing_track_ids(managers: Dict[str, MetadataManager]) -> Set[str]:
    seen: Set[str] = set()
    for manager in managers.values():
        jsonl_path = manager.folder_path / "metadata.jsonl"
        if not jsonl_path.exists():
            continue
        try:
            with open(jsonl_path, "r", encoding="utf-8") as fin:
                for line in fin:
                    try:
                        data = json.loads(line.strip())
                    except json.JSONDecodeError:
                        continue
                    track_id = str(data.get("track_id") or "").strip()
                    if track_id:
                        seen.add(track_id)
        except Exception as exc:
            logger.warning(f"Failed loading existing metadata from {jsonl_path}: {exc}")
    return seen


def download_with_backoff(
    session: requests.Session,
    url: str,
    output_path: Path,
    limiter: RateLimiter,
    max_retries: int = 5,
) -> bool:
    if output_path.exists() and output_path.stat().st_size > 1000:
        return True

    tmp_path = output_path.with_suffix(output_path.suffix + ".part")
    delay = 1.0

    for attempt in range(1, max_retries + 1):
        limiter.wait()
        try:
            resp = session.get(url, timeout=60, stream=True)
        except requests.RequestException as exc:
            logger.warning(f"Download request failed for {url}: {exc}")
            if attempt == max_retries:
                return False
            time.sleep(min(delay, 30))
            delay *= 2
            continue

        status = resp.status_code
        if status in {403, 404}:
            logger.warning(f"CDN returned {status} for {url}")
            resp.close()
            return False
        if status == 429:
            retry_after = resp.headers.get("Retry-After")
            wait_seconds = delay
            if retry_after:
                try:
                    wait_seconds = max(wait_seconds, float(retry_after))
                except ValueError:
                    pass
            logger.warning(f"CDN 429 for {url}; retrying in {wait_seconds:.1f}s")
            resp.close()
            time.sleep(min(wait_seconds, 30))
            delay *= 2
            continue
        if status >= 500:
            logger.warning(f"CDN server error {status} for {url}")
            resp.close()
            if attempt == max_retries:
                return False
            time.sleep(min(delay, 30))
            delay *= 2
            continue
        if status >= 400:
            logger.warning(f"CDN HTTP {status} for {url}")
            resp.close()
            return False

        try:
            output_path.parent.mkdir(parents=True, exist_ok=True)
            with open(tmp_path, "wb") as fout:
                for chunk in resp.iter_content(chunk_size=8192):
                    if chunk:
                        fout.write(chunk)
        except Exception as exc:
            logger.warning(f"Failed writing {output_path}: {exc}")
            tmp_path.unlink(missing_ok=True)
            resp.close()
            if attempt == max_retries:
                return False
            time.sleep(min(delay, 30))
            delay *= 2
            continue
        finally:
            resp.close()

        if not tmp_path.exists() or tmp_path.stat().st_size < 1000:
            logger.warning(f"Downloaded file too small for {url}")
            tmp_path.unlink(missing_ok=True)
            if attempt == max_retries:
                return False
            time.sleep(min(delay, 30))
            delay *= 2
            continue

        tmp_path.replace(output_path)
        return True

    return False


def create_track_metadata(
    candidate: Dict[str, Any],
    file_path: Path,
    version: str,
) -> TrackMetadata:
    audio_info = get_audio_info(file_path)
    tags = normalize_tags(candidate.get("tags") or [])
    for extra_tag in [
        *(candidate.get("genres") or []),
        *(candidate.get("moods") or []),
    ]:
        if extra_tag and extra_tag not in tags:
            tags.append(extra_tag)
    if "mureka" not in [t.lower() for t in tags]:
        tags.append("mureka")

    return TrackMetadata(
        track_id=str(candidate.get("track_id") or ""),
        filename=file_path.name,
        category="A_commercial",
        subcategory=f"mureka_{version}",
        source_platform="mureka",
        source_type="commercial",
        model_name="Mureka",
        model_version=version,
        title=str(candidate.get("title") or "untitled"),
        prompt=str(candidate.get("prompt")) if candidate.get("prompt") else None,
        genre=str(candidate.get("genre")) if candidate.get("genre") else None,
        tags=tags,
        source_url=str(candidate.get("source_url"))
        if candidate.get("source_url")
        else None,
        download_url=str(candidate.get("download_url") or ""),
        collection_method="crawl",
        duration_sec=audio_info.get("duration_sec"),
        sample_rate=audio_info.get("sample_rate"),
        channels=audio_info.get("channels"),
        bitrate_kbps=audio_info.get("bitrate_kbps"),
        file_size_bytes=audio_info.get("file_size_bytes") or file_path.stat().st_size,
        audio_format="mp3",
        md5_hash=compute_md5(file_path),
    )


def process_candidate(
    session: requests.Session,
    candidate: Dict[str, Any],
    requested_versions: List[str],
    managers: Dict[str, MetadataManager],
    output_dirs: Dict[str, Path],
    counts: Dict[str, int],
    seen_song_ids: Set[str],
    target: int,
    fallback_counter: List[int],
    download_limiter: RateLimiter,
    progress: tqdm,
) -> bool:
    track_id = str(candidate.get("track_id") or "").strip()
    if not track_id or track_id in seen_song_ids:
        return False

    selected_version = pick_version_for_candidate(
        candidate.get("version"),
        requested_versions,
        counts,
        target,
        fallback_counter,
    )
    if not selected_version:
        return False

    manager = managers[selected_version]
    output_dir = output_dirs[selected_version]

    title = str(candidate.get("title") or "untitled").strip() or "untitled"
    filename = f"{track_id}_{sanitize_filename(title)}.mp3"
    file_path = output_dir / filename

    if (
        manager.has_track(track_id)
        and file_path.exists()
        and file_path.stat().st_size > 1000
    ):
        seen_song_ids.add(track_id)
        return False

    if not ensure_disk_space():
        logger.warning("Stopping due to insufficient disk space")
        return False

    download_url = str(candidate.get("download_url") or "")
    if not download_url:
        return False

    ok = download_with_backoff(session, download_url, file_path, download_limiter)
    if not ok:
        return False

    meta = create_track_metadata(candidate, file_path, selected_version)
    manager.add_track(meta)
    counts[selected_version] = manager.get_count()
    seen_song_ids.add(track_id)
    progress.update(1)
    return True


def build_progress_desc(
    counts: Dict[str, int], target: int, requested_versions: List[str]
) -> str:
    pieces = [f"{v}={counts.get(v, 0)}/{target}" for v in requested_versions]
    total = sum(counts.get(v, 0) for v in requested_versions)
    return f"mureka: {total}/{target * len(requested_versions)} [{', '.join(pieces)}]"


def resolve_output_dirs(version: str, output_dir: Optional[str]) -> Dict[str, Path]:
    if version == "all":
        base = Path(output_dir) if output_dir else FAKE_DIR / "A_commercial"
        return {v: base / f"mureka_{v}" for v in SUPPORTED_VERSIONS}

    if output_dir:
        return {version: Path(output_dir)}
    return {version: FAKE_DIR / "A_commercial" / f"mureka_{version}"}


def extract_genre_hint(slug: str) -> str:
    return slug.replace("%20", " ").replace("-", " ").strip()


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--target", type=int, default=DEFAULT_TARGET)
    parser.add_argument(
        "--version",
        type=str,
        default="all",
        choices=["v6", "v7.5", "v8", "all"],
    )
    parser.add_argument("--output-dir", type=str, default=None)
    args = parser.parse_args()

    requested_versions = SUPPORTED_VERSIONS if args.version == "all" else [args.version]
    output_dirs = resolve_output_dirs(args.version, args.output_dir)

    for out_dir in output_dirs.values():
        out_dir.mkdir(parents=True, exist_ok=True)

    managers = {v: MetadataManager(output_dirs[v]) for v in requested_versions}
    counts = {v: managers[v].get_count() for v in requested_versions}
    seen_song_ids = load_existing_track_ids(managers)

    if all(counts[v] >= args.target for v in requested_versions):
        logger.info("Requested Mureka targets already satisfied")
        for manager in managers.values():
            manager.update_summary()
        return

    session = requests.Session()
    session.headers.update(
        {
            "User-Agent": USER_AGENT,
            "Accept": "application/json,text/plain,text/html,*/*",
            "Referer": "https://www.mureka.ai/home",
        }
    )

    page_limiter = RateLimiter(requests_per_second=1.0)
    download_limiter = RateLimiter(requests_per_second=2.0)
    fallback_counter = [0]

    progress = tqdm(
        total=args.target * len(requested_versions),
        initial=sum(counts.values()),
        desc=build_progress_desc(counts, args.target, requested_versions),
        unit="track",
    )

    known_api_endpoints: Set[str] = {
        f"{API_BASE}/api/pgc/song/songs_by_genre",
        f"{API_BASE}/api/pgc/home/modules",
        f"{API_BASE}/api/pgc/home/modules/featured-songs",
        f"{API_BASE}/api/pgc/home/modules/featured-playlist",
        f"{API_BASE}/api/pgc/song/recommend_list",
    }

    def targets_filled() -> bool:
        return all(counts.get(v, 0) >= args.target for v in requested_versions)

    try:
        sitemap_text = fetch_text(session, SITEMAP_URL, page_limiter)
        genre_pages = parse_genre_pages_from_sitemap(sitemap_text or "")
        logger.info(f"Discovered {len(genre_pages)} genre pages from sitemap")

        home_html = fetch_text(session, HOME_URL, page_limiter)
        if home_html:
            known_api_endpoints.update(extract_api_endpoints_from_text(home_html))
            for embedded in extract_embedded_song_candidates(home_html, HOME_URL):
                candidate = to_song_candidate(
                    embedded.get("song") or {},
                    embedded.get("feed") or {},
                    embedded.get("source_hint") or "embedded:home",
                    embedded.get("genre_hint"),
                )
                if not candidate:
                    continue
                if process_candidate(
                    session,
                    candidate,
                    requested_versions,
                    managers,
                    output_dirs,
                    counts,
                    seen_song_ids,
                    args.target,
                    fallback_counter,
                    download_limiter,
                    progress,
                ):
                    progress.set_description(
                        build_progress_desc(counts, args.target, requested_versions)
                    )

        if not targets_filled():
            modules_payload = fetch_json(
                session,
                "/api/pgc/home/modules",
                page_limiter,
                params={"page_size": 20},
            )
            module_feeds = (
                ((modules_payload or {}).get("data") or {}).get("feeds")
                if isinstance((modules_payload or {}).get("data"), dict)
                else []
            )
            if isinstance(module_feeds, list):
                for module in module_feeds:
                    if not isinstance(module, dict):
                        continue
                    module_id = module.get("id")
                    module_type = module.get("type")
                    if not module_id:
                        continue

                    endpoint = None
                    if module_type == 100:
                        endpoint = "/api/pgc/home/modules/featured-songs"
                    elif module_type in {101, 102}:
                        endpoint = "/api/pgc/home/modules/featured-playlist"
                    if not endpoint:
                        continue

                    payload = fetch_json(
                        session,
                        endpoint,
                        page_limiter,
                        params={"module_id": module_id},
                    )
                    if not payload:
                        continue
                    data = payload.get("data") if isinstance(payload, dict) else None
                    if not isinstance(data, dict):
                        continue

                    if endpoint.endswith("featured-songs"):
                        raw_featured_song_feeds = data.get("feeds")
                        featured_song_feeds: List[Any] = (
                            raw_featured_song_feeds
                            if isinstance(raw_featured_song_feeds, list)
                            else []
                        )
                        for feed in featured_song_feeds:
                            if not isinstance(feed, dict):
                                continue
                            raw_song = feed.get("song")
                            module_song_dict: Dict[str, Any] = (
                                raw_song if isinstance(raw_song, dict) else {}
                            )
                            candidate = to_song_candidate(
                                module_song_dict,
                                feed,
                                f"home:module:{module_id}",
                                None,
                            )
                            if not candidate:
                                continue
                            if process_candidate(
                                session,
                                candidate,
                                requested_versions,
                                managers,
                                output_dirs,
                                counts,
                                seen_song_ids,
                                args.target,
                                fallback_counter,
                                download_limiter,
                                progress,
                            ):
                                progress.set_description(
                                    build_progress_desc(
                                        counts, args.target, requested_versions
                                    )
                                )
                            if targets_filled():
                                break

                    if endpoint.endswith("featured-playlist"):
                        raw_playlists = data.get("play_lists")
                        playlists: List[Any] = (
                            raw_playlists if isinstance(raw_playlists, list) else []
                        )
                        for playlist in playlists:
                            if not isinstance(playlist, dict):
                                continue
                            raw_playlist_feeds = playlist.get("feeds")
                            playlist_feeds: List[Any] = (
                                raw_playlist_feeds
                                if isinstance(raw_playlist_feeds, list)
                                else []
                            )
                            for feed in playlist_feeds:
                                if not isinstance(feed, dict):
                                    continue
                                raw_song = feed.get("song")
                                playlist_song_dict: Dict[str, Any] = (
                                    raw_song if isinstance(raw_song, dict) else {}
                                )
                                candidate = to_song_candidate(
                                    playlist_song_dict,
                                    feed,
                                    f"home:playlist:{module_id}:{playlist.get('id')}",
                                    None,
                                )
                                if not candidate:
                                    continue
                                if process_candidate(
                                    session,
                                    candidate,
                                    requested_versions,
                                    managers,
                                    output_dirs,
                                    counts,
                                    seen_song_ids,
                                    args.target,
                                    fallback_counter,
                                    download_limiter,
                                    progress,
                                ):
                                    progress.set_description(
                                        build_progress_desc(
                                            counts, args.target, requested_versions
                                        )
                                    )
                                if targets_filled():
                                    break
                            if targets_filled():
                                break

                    if targets_filled():
                        break

        for genre_url, genre_id, slug in genre_pages:
            if targets_filled():
                break

            genre_hint = extract_genre_hint(slug)
            genre_html = fetch_text(session, genre_url, page_limiter)
            if genre_html:
                known_api_endpoints.update(extract_api_endpoints_from_text(genre_html))
                for embedded in extract_embedded_song_candidates(
                    genre_html, genre_url, genre_hint
                ):
                    candidate = to_song_candidate(
                        embedded.get("song") or {},
                        embedded.get("feed") or {},
                        embedded.get("source_hint") or f"embedded:{genre_url}",
                        embedded.get("genre_hint") or genre_hint,
                    )
                    if not candidate:
                        continue
                    if process_candidate(
                        session,
                        candidate,
                        requested_versions,
                        managers,
                        output_dirs,
                        counts,
                        seen_song_ids,
                        args.target,
                        fallback_counter,
                        download_limiter,
                        progress,
                    ):
                        progress.set_description(
                            build_progress_desc(counts, args.target, requested_versions)
                        )
                    if targets_filled():
                        break

            last_id = 0
            for _ in range(MAX_GENRE_PAGES):
                if targets_filled() or not ensure_disk_space():
                    break

                params = {"genre_id": genre_id, "size": 20}
                if last_id:
                    params["last_id"] = last_id

                payload = fetch_json(
                    session,
                    "/api/pgc/song/songs_by_genre",
                    page_limiter,
                    params=params,
                )
                if not payload:
                    break

                data = payload.get("data") if isinstance(payload, dict) else None
                if not isinstance(data, dict):
                    break
                raw_genre_feeds = data.get("feeds")
                genre_feeds: List[Any] = (
                    raw_genre_feeds if isinstance(raw_genre_feeds, list) else []
                )
                if not genre_feeds:
                    break

                added_this_page = 0
                for feed in genre_feeds:
                    if not isinstance(feed, dict):
                        continue
                    raw_song = feed.get("song")
                    genre_song_dict: Dict[str, Any] = (
                        raw_song if isinstance(raw_song, dict) else {}
                    )
                    candidate = to_song_candidate(
                        genre_song_dict,
                        feed,
                        f"genre_api:{genre_id}",
                        genre_hint,
                    )
                    if not candidate:
                        continue
                    if process_candidate(
                        session,
                        candidate,
                        requested_versions,
                        managers,
                        output_dirs,
                        counts,
                        seen_song_ids,
                        args.target,
                        fallback_counter,
                        download_limiter,
                        progress,
                    ):
                        added_this_page += 1
                        progress.set_description(
                            build_progress_desc(counts, args.target, requested_versions)
                        )
                    if targets_filled():
                        break

                next_last_id = data.get("last_id")
                if not next_last_id or next_last_id == last_id:
                    break
                last_id = int(next_last_id)

                if added_this_page == 0 and targets_filled():
                    break

        if not targets_filled():
            recommend_payload = fetch_json(
                session,
                "/api/pgc/song/recommend_list",
                page_limiter,
                params={"size": 20},
            )
            data = (
                recommend_payload.get("data")
                if isinstance(recommend_payload, dict)
                else None
            )
            if isinstance(data, dict):
                raw_recommend_feeds = data.get("feeds")
                recommend_feeds: List[Any] = (
                    raw_recommend_feeds if isinstance(raw_recommend_feeds, list) else []
                )
            else:
                recommend_feeds = []
            for feed in recommend_feeds:
                if not isinstance(feed, dict):
                    continue
                raw_song = feed.get("song")
                recommend_song_dict: Dict[str, Any] = (
                    raw_song if isinstance(raw_song, dict) else {}
                )
                candidate = to_song_candidate(
                    recommend_song_dict,
                    feed,
                    "recommend_list",
                    None,
                )
                if not candidate:
                    continue
                if process_candidate(
                    session,
                    candidate,
                    requested_versions,
                    managers,
                    output_dirs,
                    counts,
                    seen_song_ids,
                    args.target,
                    fallback_counter,
                    download_limiter,
                    progress,
                ):
                    progress.set_description(
                        build_progress_desc(counts, args.target, requested_versions)
                    )
                if targets_filled():
                    break

    finally:
        for manager in managers.values():
            manager.update_summary()
        progress.close()

    logger.info(
        "Finished Mureka crawl with counts: "
        + ", ".join(f"{v}={counts.get(v, 0)}" for v in requested_versions)
    )
    logger.info(f"Discovered API hints: {len(known_api_endpoints)} endpoints")


if __name__ == "__main__":
    main()