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
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
"""
Utility functions for YouTube-related operations.
Optimized for free yt-dlp downloads with optional Apify fallback.
"""

import asyncio
from datetime import datetime
import logging
import json
import uuid
import re
import time
from pathlib import Path
from typing import Any, Dict, Optional
from urllib.parse import parse_qs, urlparse

import requests
import yt_dlp

from .apify_youtube_downloader import ApifyDownloadError, download_video_via_apify
from .config import get_config
from .download_progress import DownloadRecovery, report_download_recovery
from .media.ffmpeg import ffprobe_video_size
from .youtube_proxy import (
    YOUTUBE_DOWNLOAD_PROVIDER_YTDLP_PROXY,
    ByteBudget,
    DownloadBudgetExceeded,
    base_proxy_params,
    download_full_with_proxy,
    extract_video_info_with_proxy,
    extract_video_info,
    YouTubeDownloadError,
    YouTubeGeoRestrictedError,
    is_geo_restricted_error,
    log_youtube_attempt,
    proxy_configured,
    public_download_error,
    redact_secrets,
    video_format_selector,
)
from .rapidapi_youtube_downloader import RapidAPIDownloadError, download_video_via_rapidapi

logger = logging.getLogger(__name__)

YOUTUBE_METADATA_PROVIDER_YTDLP = "yt_dlp"
YOUTUBE_METADATA_PROVIDER_DATA_API = "youtube_data_api"
YOUTUBE_DOWNLOAD_PROVIDER_YTDLP = "yt_dlp"
YOUTUBE_DOWNLOAD_PROVIDER_APIFY = "apify"
YOUTUBE_DOWNLOAD_PROVIDER_RAPIDAPI = "rapidapi"
YOUTUBE_DATA_API_URL = "https://www.googleapis.com/youtube/v3/videos"


class YouTubeDownloader:
    """Enhanced YouTube downloader with optimized settings."""

    def __init__(self):
        self.temp_dir = Path(get_config().temp_dir)
        self.temp_dir.mkdir(parents=True, exist_ok=True)

    def get_optimal_download_options(
        self,
        video_id: str,
        max_height: Optional[int] = None,
    ) -> Dict[str, Any]:
        """Get optimal yt-dlp options for high-quality downloads.

        ``max_height`` caps the video height for plans with a lower output
        resolution, falling back to the best stream if nothing fits.
        """
        output_path = self.temp_dir / f"{video_id}.%(ext)s"

        opts = {
            "outtmpl": str(output_path),
            # Cap at 1080p. Vertical clips are 1080x1920, and a 4K source
            # multiplies bandwidth without improving the export.
            "format": video_format_selector(max_height),
            "format_sort": ["res", "fps"],
            "merge_output_format": "mp4",
            "writesubtitles": False,
            "writeautomaticsub": False,
            "noplaylist": True,
            "overwrites": True,
            # Optimized for speed and reliability
            "socket_timeout": 30,
            "retries": 5,  # Increased retries
            "fragment_retries": 5,
            "http_chunk_size": 10485760,  # 10MB chunks
            # Quiet operation - only errors/warnings
            "quiet": True,
            "no_warnings": False,  # Show warnings but not info
            "ignoreerrors": False,
            # Enhanced headers to avoid 403 errors
            "http_headers": {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.9",
                "Accept-Encoding": "gzip, deflate",
                "Connection": "keep-alive",
            },
            # Metadata extraction
            "extract_flat": False,
            "writeinfojson": False,
            # Additional bypass options
            "nocheckcertificate": True,
            "prefer_insecure": False,
            "age_limit": None,
        }

        return opts


def _build_info_options(task_id: Optional[str] = None) -> Dict[str, Any]:
    ydl_opts = {
        "quiet": True,
        "no_warnings": True,
        "extractaudio": False,
        "skip_download": True,
        # A watch?v=X&list=Y link otherwise resolves to the whole playlist,
        # which has no duration and can take minutes to walk.
        "noplaylist": True,
        "socket_timeout": 30,
        "http_headers": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.9",
            "Connection": "keep-alive",
        },
        "nocheckcertificate": True,
    }
    if proxy_configured():
        # Metadata must leave through the same proxy as the media, or YouTube
        # bot-checks the server IP before a download starts. No player client
        # is pinned; yt-dlp keeps its defaults.
        ydl_opts.update(base_proxy_params(task_id))
        ydl_opts["skip_download"] = True
        ydl_opts["quiet"] = True
    return ydl_opts


def _empty_video_info(video_id: Optional[str] = None) -> Dict[str, Any]:
    return {
        "id": video_id,
        "title": None,
        "description": "",
        "duration": None,
        "uploader": None,
        "upload_date": None,
        "view_count": None,
        "like_count": None,
        "thumbnail": None,
        "format_id": None,
        "resolution": None,
        "fps": None,
        "filesize": None,
    }


def _parse_iso8601_duration_to_seconds(value: str) -> int:
    match = re.fullmatch(
        r"P(?:(?P<days>\d+)D)?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?",
        value or "",
    )
    if not match:
        raise ValueError(f"Unsupported ISO 8601 duration: {value}")

    days = int(match.group("days") or 0)
    hours = int(match.group("hours") or 0)
    minutes = int(match.group("minutes") or 0)
    seconds = int(match.group("seconds") or 0)
    return (((days * 24) + hours) * 60 + minutes) * 60 + seconds


def _pick_best_thumbnail(thumbnails: Optional[Dict[str, Any]]) -> Optional[str]:
    if not thumbnails:
        return None

    for key in ("maxres", "standard", "high", "medium", "default"):
        candidate = thumbnails.get(key)
        if isinstance(candidate, dict) and candidate.get("url"):
            return candidate["url"]

    for candidate in thumbnails.values():
        if isinstance(candidate, dict) and candidate.get("url"):
            return candidate["url"]

    return None


def _normalize_upload_date(published_at: Optional[str]) -> Optional[str]:
    if not published_at:
        return None

    try:
        return (
            datetime.fromisoformat(published_at.replace("Z", "+00:00"))
            .strftime("%Y%m%d")
        )
    except ValueError:
        logger.warning("Could not parse YouTube publishedAt value: %s", published_at)
        return None


def _parse_optional_int(value: Any) -> Optional[int]:
    if value is None or value == "":
        return None
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def _get_local_video_dimensions(path: Path) -> tuple[int, int]:
    """Displayed width/height of a local file, or (0, 0) if it cannot be read.

    Download ranking only uses this to compare candidates. A probe failure
    leaves the file eligible by size instead of failing the download.
    """
    try:
        return ffprobe_video_size(path)
    except Exception:
        return (0, 0)


def _remove_cached_downloads(temp_dir: Path, video_id: str) -> None:
    cached_files = [
        file_path
        for file_path in temp_dir.glob(f"{video_id}.*")
        if file_path.is_file()
        and file_path.suffix.lower() in [".mp4", ".mkv", ".webm", ".mov", ".m4v"]
    ]
    if not cached_files:
        return

    logger.info(
        "Refreshing download for %s (found %s cached file(s))",
        video_id,
        len(cached_files),
    )
    for cached_file in cached_files:
        try:
            cached_file.unlink()
        except Exception as exc:
            logger.warning("Failed to remove stale cache file %s: %s", cached_file, exc)


_YOUTUBE_ID = re.compile(r"[A-Za-z0-9_-]{11}")
_YOUTUBE_PATH_MARKERS = {"embed", "shorts", "live", "v"}


def _is_youtube_host(host: str) -> bool:
    host = host.lower().removeprefix("www.")
    return (
        host in {"youtu.be", "youtube.com", "youtube-nocookie.com"}
        or host.endswith(".youtube.com")
        or host.endswith(".youtube-nocookie.com")
    )


def get_youtube_video_id(url: str) -> Optional[str]:
    """
    Extract the 11-character video id from a YouTube link.

    Mirrors ``frontend/src/lib/youtube-url.ts``: watch (``v=`` anywhere in the
    query), youtu.be share, shorts, live, embed and ``/v/`` paths on
    youtube.com, its subdomains (www, m, music) and youtube-nocookie.com.
    Only the host decides, so a YouTube link inside another site's query
    string is not a YouTube source.
    """
    if not isinstance(url, str) or not url.strip():
        return None

    url = url.strip()
    if "://" not in url:
        url = f"https://{url}"
    try:
        parsed = urlparse(url)
        host = parsed.hostname or ""
    except ValueError:
        return None
    if parsed.scheme.lower() not in {"http", "https"} or not _is_youtube_host(host):
        return None

    parts = [part for part in parsed.path.split("/") if part]
    if host.lower().removeprefix("www.") == "youtu.be":
        candidate = parts[0] if parts else None
    else:
        candidate = next(
            (value for value in parse_qs(parsed.query).get("v", []) if _YOUTUBE_ID.fullmatch(value)),
            None,
        )
        if not candidate and len(parts) >= 2 and parts[0].lower() in _YOUTUBE_PATH_MARKERS:
            candidate = parts[1]
    return candidate if candidate and _YOUTUBE_ID.fullmatch(candidate) else None


def canonical_youtube_url(url: str) -> Optional[str]:
    """``https://www.youtube.com/watch?v=ID`` for any supported YouTube link, else None."""
    video_id = get_youtube_video_id(url)
    return f"https://www.youtube.com/watch?v={video_id}" if video_id else None


def validate_youtube_url(url: str) -> bool:
    """Validate if URL is a proper YouTube URL."""
    video_id = get_youtube_video_id(url)
    return video_id is not None


def _fetch_video_info_with_ytdlp(
    url: str, task_id: Optional[str] = None, *,
    budget: Optional[ByteBudget] = None, deadline: Optional[float] = None,
) -> Dict[str, Any]:
    video_id = get_youtube_video_id(url)
    if not video_id:
        raise ValueError(f"Invalid YouTube URL: {url}")

    if proxy_configured():
        # Duration preflight must recover regions too, including self-hosted
        # deployments without the independent YouTube Data API configured.
        info = extract_video_info_with_proxy(
            url, video_id, task_id=task_id, budget=budget, deadline=deadline,
        )
    else:
        ydl_opts = _build_info_options(task_id)
        if deadline is not None:
            ydl_opts["_youtube_deadline"] = deadline
            info = extract_video_info(url, ydl_opts)
        else:
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(url, download=False)

    return {
        "id": info.get("id"),
        "title": info.get("title"),
        "description": info.get("description", ""),
        "duration": info.get("duration"),
        "uploader": info.get("uploader"),
        "upload_date": info.get("upload_date"),
        "view_count": info.get("view_count"),
        "like_count": info.get("like_count"),
        "thumbnail": info.get("thumbnail"),
        "format_id": info.get("format_id"),
        "resolution": info.get("resolution"),
        "fps": info.get("fps"),
        "filesize": info.get("filesize"),
    }


def _fetch_video_info_with_youtube_data_api(
    url: str, *, deadline: Optional[float] = None,
) -> Dict[str, Any]:
    video_id = get_youtube_video_id(url)
    if not video_id:
        raise ValueError(f"Invalid YouTube URL: {url}")

    config = get_config()
    api_key = config.resolve_youtube_data_api_key()
    if not api_key:
        raise ValueError("Missing YOUTUBE_DATA_API_KEY and GOOGLE_API_KEY")

    timeout = (10, 30)
    if deadline is not None:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError("YouTube metadata deadline exceeded")
        # Divide the remaining allowance between connection and read-idle
        # timeouts. Check elapsed time too; these are not total wall-clock limits.
        timeout = (min(10, remaining / 2), min(30, remaining / 2))
    response = requests.get(
        YOUTUBE_DATA_API_URL,
        params={
            "part": "snippet,contentDetails,statistics",
            "id": video_id,
            "key": api_key,
            "fields": (
                "items(id,"
                "snippet(title,description,channelTitle,publishedAt,"
                "thumbnails(default(url),medium(url),high(url),standard(url),maxres(url))),"
                "contentDetails(duration),"
                "statistics(viewCount,likeCount))"
            ),
        },
        timeout=timeout,
    )
    response.raise_for_status()
    payload = response.json()
    if deadline is not None and time.monotonic() >= deadline:
        raise TimeoutError("YouTube metadata deadline exceeded")
    items = payload.get("items") or []
    if not items:
        raise ValueError(f"No YouTube Data API results for video {video_id}")

    item = items[0]
    snippet = item.get("snippet") or {}
    content_details = item.get("contentDetails") or {}
    statistics = item.get("statistics") or {}
    normalized = _empty_video_info(item.get("id") or video_id)
    normalized.update(
        {
            "title": snippet.get("title"),
            "description": snippet.get("description", ""),
            "duration": _parse_iso8601_duration_to_seconds(
                content_details.get("duration", "")
            ),
            "uploader": snippet.get("channelTitle"),
            "upload_date": _normalize_upload_date(snippet.get("publishedAt")),
            "view_count": _parse_optional_int(statistics.get("viewCount")),
            "like_count": _parse_optional_int(statistics.get("likeCount")),
            "thumbnail": _pick_best_thumbnail(snippet.get("thumbnails")),
        }
    )
    return normalized


def fetch_video_info(url: str) -> Optional[Dict[str, Any]]:
    """
    Backward-compatible metadata lookup entrypoint.
    """
    return get_youtube_video_info(url)


async def async_get_youtube_video_info(
    url: str,
    task_id: Optional[str] = None,
    *,
    budget: Optional[ByteBudget] = None,
    deadline: Optional[float] = None,
) -> Optional[Dict[str, Any]]:
    if deadline is None:
        deadline = time.monotonic() + get_config().youtube_preflight_timeout_seconds
    return await asyncio.to_thread(
        get_youtube_video_info, url, task_id, budget=budget, deadline=deadline,
    )


def get_youtube_video_info(
    url: str,
    task_id: Optional[str] = None,
    *,
    errors: Optional[list[str]] = None,
    budget: Optional[ByteBudget] = None,
    deadline: Optional[float] = None,
) -> Optional[Dict[str, Any]]:
    video_id = get_youtube_video_id(url)
    if not video_id:
        logger.error("Invalid YouTube URL: %s", url)
        return None

    config = get_config()
    primary_provider = config.youtube_metadata_provider
    secondary_provider = (
        YOUTUBE_METADATA_PROVIDER_DATA_API
        if primary_provider == YOUTUBE_METADATA_PROVIDER_YTDLP
        else YOUTUBE_METADATA_PROVIDER_YTDLP
    )
    providers = [primary_provider, secondary_provider]
    last_error: Optional[Exception] = None
    geo_error: Optional[Exception] = None

    for index, provider in enumerate(providers):
        try:
            options = {}
            if deadline is not None:
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    raise TimeoutError("YouTube metadata deadline exceeded")
                usable_providers = sum(
                    candidate != YOUTUBE_METADATA_PROVIDER_DATA_API
                    or bool(config.resolve_youtube_data_api_key())
                    for candidate in providers[index:]
                )
                options["deadline"] = time.monotonic() + remaining / max(1, usable_providers)
            if provider == YOUTUBE_METADATA_PROVIDER_DATA_API:
                video_info = _fetch_video_info_with_youtube_data_api(url, **options)
            else:
                if budget is not None:
                    options["budget"] = budget
                video_info = (
                    _fetch_video_info_with_ytdlp(url, task_id, **options)
                    if task_id
                    else _fetch_video_info_with_ytdlp(url, **options)
                )

            if index == 0:
                logger.info(
                    "Fetched YouTube metadata for %s using primary provider %s",
                    video_id,
                    provider,
                )
            else:
                logger.info(
                    "Fetched YouTube metadata for %s using fallback provider %s",
                    video_id,
                    provider,
                )
            return video_info
        except Exception as exc:
            last_error = exc
            if is_geo_restricted_error(exc):
                geo_error = exc
            if index == 0:
                logger.warning(
                    "Primary YouTube metadata provider %s failed for %s: %s. Trying %s.",
                    provider,
                    video_id,
                    exc,
                    secondary_provider,
                )
            else:
                logger.warning(
                    "Fallback YouTube metadata provider %s failed for %s: %s",
                    provider,
                    video_id,
                    exc,
                )

    if last_error:
        logger.warning("YouTube video info fetch failed for %s: %s", video_id, last_error)
        if errors is not None:
            errors.append(public_download_error(last_error))
    if deadline is not None and time.monotonic() >= deadline:
        raise TimeoutError("YouTube metadata deadline exceeded") from last_error
    if geo_error is not None:
        raise YouTubeGeoRestrictedError() from geo_error
    return None


def get_youtube_video_title(
    url: str,
) -> Optional[str]:
    """
    Get the title of a YouTube video from a URL.
    Enhanced with better error handling and validation.
    """
    video_info = get_youtube_video_info(url)
    return video_info.get("title") if video_info else None


async def async_get_youtube_video_title(url: str) -> Optional[str]:
    video_info = await async_get_youtube_video_info(url)
    return video_info.get("title") if video_info else None


APIFY_LONG_VIDEO_MAX_QUALITY = "1080"


def _resolve_apify_quality(url: str, requested: Optional[str] = None) -> str:
    """Pick the Apify quality: the plan's cap when lower than the default, and
    at most 1080p for long videos so the run finishes before its timeout."""
    config = get_config()
    quality = config.apify_youtube_default_quality
    if requested and int(requested) < int(quality):
        quality = requested
    if int(quality) <= int(APIFY_LONG_VIDEO_MAX_QUALITY):
        return quality

    try:
        video_info = get_youtube_video_info(url)
    except Exception as exc:
        logger.warning("Could not fetch duration for Apify quality cap: %s", exc)
        video_info = None

    duration = (video_info or {}).get("duration") or 0
    if duration > config.apify_long_video_seconds:
        logger.info(
            "Video is %ss long; capping Apify quality at %sp instead of %sp",
            duration,
            APIFY_LONG_VIDEO_MAX_QUALITY,
            quality,
        )
        return APIFY_LONG_VIDEO_MAX_QUALITY
    return quality


def download_youtube_video_with_apify(
    url: str,
    video_id: str,
    quality: Optional[str] = None,
) -> Path:
    config = get_config()
    downloader = YouTubeDownloader()
    quality = _resolve_apify_quality(url, quality)
    logger.info(
        "Attempting Apify YouTube download for %s with quality %s",
        video_id,
        quality,
    )
    return download_video_via_apify(
        url=url,
        video_id=video_id,
        temp_dir=downloader.temp_dir,
        api_token=config.apify_api_token,
        quality=quality,
    )


def _download_youtube_video_with_ytdlp(
    url: str,
    max_retries: int = 3,
    task_id: Optional[str] = None,
    quality: Optional[str] = None,
) -> Optional[Path]:
    """
    Download YouTube video with optimized settings and retry logic.
    Returns the path to the downloaded file, or None if download fails.
    """
    logger.info(f"Starting YouTube download: {url}")

    video_id = get_youtube_video_id(url)
    if not video_id:
        logger.error(f"Could not extract video ID from URL: {url}")
        return None

    downloader = YouTubeDownloader()
    # This is the independent datacenter fallback. yt-dlp extracts metadata
    # during download; a separate proxied lookup must not gate this route.

    last_error: Optional[str] = None

    for attempt in range(max_retries):
        try:
            logger.info("Download attempt %s/%s", attempt + 1, max_retries)

            ydl_opts = downloader.get_optimal_download_options(
                video_id, int(quality) if quality else None
            )

            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])

            logger.info(f"Searching for downloaded file: {video_id}.*")
            downloaded_files = [
                file_path
                for file_path in downloader.temp_dir.glob(f"{video_id}.*")
                if file_path.is_file()
                and file_path.suffix.lower() in [".mp4", ".mkv", ".webm"]
            ]
            if downloaded_files:
                ranked_files = []
                for candidate in downloaded_files:
                    width, height = _get_local_video_dimensions(candidate)
                    ranked_files.append(
                        (
                            height,
                            width,
                            candidate.stat().st_size,
                            candidate,
                        )
                    )
                ranked_files.sort(reverse=True)
                best_downloaded_file = ranked_files[0][3]
                file_size = best_downloaded_file.stat().st_size
                width, height = _get_local_video_dimensions(best_downloaded_file)
                logger.info(
                    f"Download successful: {best_downloaded_file.name} ({file_size // 1024 // 1024}MB, {width}x{height})"
                )
                return best_downloaded_file

            logger.warning("No video file found after download attempt %s", attempt + 1)

        except yt_dlp.utils.DownloadError as e:
            # Retrying the same datacenter cannot change a country restriction.
            # Let independent download providers try their own regions instead.
            if is_geo_restricted_error(e):
                raise YouTubeGeoRestrictedError() from e
            last_error = str(e)
            logger.warning("Download attempt %s failed: %s", attempt + 1, e)
            if attempt < max_retries - 1:
                wait_time = 2**attempt
                logger.info(f"Retrying in {wait_time} seconds...")
                time.sleep(wait_time)
            else:
                logger.error("All download attempts failed")

        except Exception as e:
            if is_geo_restricted_error(e):
                raise YouTubeGeoRestrictedError() from e
            last_error = str(e)
            logger.error(
                "Unexpected error during download attempt %s: %s",
                attempt + 1,
                e,
            )
            if attempt < max_retries - 1:
                wait_time = 2**attempt
                logger.info(f"Retrying in {wait_time} seconds...")
                time.sleep(wait_time)
            else:
                logger.error("All download attempts failed")

    if last_error:
        logger.error("All download attempts failed for %s: %s", url, last_error)
        raise YouTubeDownloadError(public_download_error(last_error))

    return None


def _provider_order(config, *, skip_proxy: bool) -> list[str]:
    """Proxy, API Router, bounded Apify pool, then direct yt-dlp."""
    order: list[str] = []
    if proxy_configured(config) and not skip_proxy:
        order.append(YOUTUBE_DOWNLOAD_PROVIDER_YTDLP_PROXY)
    # A configured proxy always uses the independent paid backups before
    # retrying yt-dlp from the same datacenter that YouTube already blocks.
    primary = config.youtube_download_provider
    paid = [YOUTUBE_DOWNLOAD_PROVIDER_RAPIDAPI, YOUTUBE_DOWNLOAD_PROVIDER_APIFY]
    if proxy_configured(config) or primary == YOUTUBE_DOWNLOAD_PROVIDER_RAPIDAPI:
        rest = [*paid, YOUTUBE_DOWNLOAD_PROVIDER_YTDLP]
    elif primary == YOUTUBE_DOWNLOAD_PROVIDER_APIFY:
        rest = [YOUTUBE_DOWNLOAD_PROVIDER_APIFY, YOUTUBE_DOWNLOAD_PROVIDER_RAPIDAPI,
                YOUTUBE_DOWNLOAD_PROVIDER_YTDLP]
    else:
        rest = [YOUTUBE_DOWNLOAD_PROVIDER_YTDLP, *paid]
    order.extend(rest)
    return order


def _note_attempt(provider: str, video_id: str, task_id: Optional[str], budget: ByteBudget, before: int, *, outcome: str, error: Optional[str] = None) -> None:
    log_youtube_attempt(
        provider=provider,
        video_id=video_id,
        kind="full",
        outcome=outcome,
        nbytes=max(0, budget.snapshot() - before),
        task_id=task_id,
        error=error,
    )


def download_youtube_video(
    url: str,
    max_retries: int = 3,
    task_id: Optional[str] = None,
    quality: Optional[str] = None,
    *,
    budget: Optional[ByteBudget] = None,
    skip_proxy: bool = False,
    errors: Optional[list[str]] = None,
) -> Optional[Path]:
    """
    Download a full YouTube video using the configured provider chain.

    When ``YOUTUBE_PROXY_URL`` is set, a 1080p yt-dlp download through that
    proxy is attempted first. The clip pipeline prefers audio-then-sections
    and uses this full-file chain only as a fallback. ``errors`` collects each
    provider's failure reason (redacted) for callers that report it.
    """
    logger.info("Starting YouTube download: %s", url)

    video_id = get_youtube_video_id(url)
    if not video_id:
        logger.error("Could not extract video ID from URL: %s", url)
        return None

    downloader = YouTubeDownloader()
    _remove_cached_downloads(downloader.temp_dir, video_id)

    config = get_config()
    job_budget = budget or ByteBudget(getattr(config, "youtube_download_max_bytes", 2_000_000_000))
    geo_error: Optional[BaseException] = None
    attempted_providers = 0

    for provider in _provider_order(config, skip_proxy=skip_proxy):
        if provider == YOUTUBE_DOWNLOAD_PROVIDER_RAPIDAPI and not config.rapidapi_youtube_api_key:
            continue
        if provider == YOUTUBE_DOWNLOAD_PROVIDER_APIFY and not config.apify_api_token:
            logger.info("APIFY_API_TOKEN not set; skipping Apify download for %s", url)
            continue
        if attempted_providers or skip_proxy:
            report_download_recovery(
                DownloadRecovery.ANOTHER_BACKUP if attempted_providers > (0 if skip_proxy else 1)
                else DownloadRecovery.BACKUP
            )
        attempted_providers += 1
        before = job_budget.snapshot()
        try:
            if provider == YOUTUBE_DOWNLOAD_PROVIDER_YTDLP_PROXY:
                downloaded_path = download_full_with_proxy(
                    url, video_id, downloader.temp_dir, task_id=task_id, budget=job_budget, quality=quality,
                )
            elif provider == YOUTUBE_DOWNLOAD_PROVIDER_RAPIDAPI:
                downloaded_path = download_video_via_rapidapi(
                    video_id, downloader.temp_dir, config.rapidapi_youtube_api_key,
                    quality=_resolve_apify_quality(url, quality),
                    timeout_seconds=config.rapidapi_youtube_timeout_seconds,
                )
            elif provider == YOUTUBE_DOWNLOAD_PROVIDER_YTDLP:
                downloaded_path = _download_youtube_video_with_ytdlp(url, max_retries, task_id, quality)
            else:
                downloaded_path = download_youtube_video_with_apify(url, video_id, quality)
        except DownloadBudgetExceeded as exc:
            _note_attempt(provider, video_id, task_id, job_budget, before, outcome="failure", error=str(exc))
            raise
        except ApifyDownloadError as exc:
            _note_attempt(provider, video_id, task_id, job_budget, before, outcome="failure", error=str(exc))
            if errors is not None:
                errors.append(public_download_error(exc))
            if exc.permanent:
                if geo_error is not None:
                    raise YouTubeGeoRestrictedError() from geo_error
                return None
            continue
        except Exception as exc:
            if is_geo_restricted_error(exc):
                geo_error = exc
            _note_attempt(provider, video_id, task_id, job_budget, before, outcome="failure", error=str(exc))
            logger.warning(
                "%s download failed for %s: %s", provider, url, redact_secrets(str(exc)),
            )
            if errors is not None:
                errors.append(public_download_error(exc))
            continue

        if not downloaded_path:
            _note_attempt(provider, video_id, task_id, job_budget, before, outcome="failure", error="no file")
            logger.warning("%s download failed for %s", provider, url)
            continue

        file_size = downloaded_path.stat().st_size if downloaded_path.is_file() else 0
        if job_budget.snapshot() == before and file_size:
            try:
                job_budget.add(file_size)
            except DownloadBudgetExceeded as exc:
                _note_attempt(provider, video_id, task_id, job_budget, before, outcome="failure", error=str(exc))
                raise
        width, height = _get_local_video_dimensions(downloaded_path)
        logger.info(
            "YouTube download successful via %s: %s (%s bytes, %sx%s)",
            provider,
            downloaded_path.name,
            file_size,
            width,
            height,
        )
        _note_attempt(provider, video_id, task_id, job_budget, before, outcome="success")
        return downloaded_path

    logger.error("All YouTube download providers failed for %s", url)
    if geo_error is not None:
        raise YouTubeGeoRestrictedError() from geo_error
    return None


async def async_download_youtube_video(
    url: str,
    max_retries: int = 3,
    task_id: Optional[str] = None,
    quality: Optional[str] = None,
    *,
    budget: Optional[ByteBudget] = None,
    skip_proxy: bool = False,
) -> Optional[Path]:
    logger.info(f"Starting async YouTube download: {url}")
    return await asyncio.to_thread(
        download_youtube_video,
        url,
        max_retries,
        task_id,
        quality,
        budget=budget,
        skip_proxy=skip_proxy,
    )


def get_video_duration(url: str) -> Optional[int]:
    """Get video duration in seconds without downloading."""
    video_info = get_youtube_video_info(url)
    return video_info.get("duration") if video_info else None


def is_video_suitable_for_processing(
    url: str, min_duration: int = 60, max_duration: int = 7200
) -> bool:
    """
    Check if video is suitable for processing based on duration and other factors.
    Default limits: 1 minute to 2 hours.
    """
    video_info = get_youtube_video_info(url)
    if not video_info:
        return False

    duration = video_info.get("duration", 0)

    # Check duration constraints
    if duration < min_duration or duration > max_duration:
        logger.warning(
            f"Video duration {duration}s outside allowed range ({min_duration}-{max_duration}s)"
        )
        return False

    # Additional checks could go here (e.g., content type, quality, etc.)

    return True


def cleanup_downloaded_files(video_id: str, source_path: Optional[Path] = None):
    """Remove downloaded media while retaining word timings for cached jobs.

    Files under ``youtube-cache`` are the reusable audio and section store.
    ``youtube-work`` holds a per-job timeline assembled from that store and
    can be removed once clips have been rendered.
    """
    from .youtube_source import WORK_DIRNAME, is_preserved_cache_path, is_youtube_work_path

    if is_preserved_cache_path(source_path):
        logger.info("Keeping cached YouTube source for %s", video_id)
        return
    if is_youtube_work_path(source_path):
        work_dir = source_path if source_path.is_dir() else source_path.parent
        if WORK_DIRNAME in work_dir.parts and work_dir.name != WORK_DIRNAME:
            import shutil
            shutil.rmtree(work_dir, ignore_errors=True)
            logger.info("Removed temporary YouTube timeline for %s", video_id)
        return

    temp_dir = Path(get_config().temp_dir)
    provider_dir = False
    if source_path is not None and source_path.parent.name.startswith((f"apify-{video_id}-", f"rapidapi-{video_id}-", f"proxy-{video_id}-")):
        candidate = source_path.parent.resolve()
        if candidate.parent != temp_dir.resolve():
            logger.warning("Refusing source cleanup outside the configured download directory")
            return
        if candidate.name.startswith(f"proxy-{video_id}-"):
            # A proxy attempt now owns a unique directory. Retain reusable
            # timings at the stable per-video path before removing that media.
            sidecar = source_path.with_suffix(".transcript_cache.json")
            canonical = temp_dir / f"{video_id}.transcript_cache.json"
            temporary = canonical.with_name(f".{canonical.name}.{uuid.uuid4().hex}.tmp")
            try:
                payload = json.loads(sidecar.read_text(encoding="utf-8"))
                if isinstance(payload, dict) and isinstance(payload.get("words"), list) and payload["words"]:
                    temporary.write_text(json.dumps(payload), encoding="utf-8")
                    temporary.replace(canonical)
                    sidecar.unlink(missing_ok=True)
            except (OSError, ValueError):
                pass  # Keep any existing sidecar if canonical persistence fails.
            finally:
                try:
                    temporary.unlink(missing_ok=True)
                except OSError:
                    logger.warning("Could not remove temporary transcript sidecar for %s", video_id)
        temp_dir = candidate
        provider_dir = True

    for file_path in temp_dir.glob(f"{video_id}.*"):
        if file_path.name == f"{video_id}.transcript_cache.json":
            continue
        try:
            if file_path.is_file():
                file_path.unlink()
                logger.info(f"Cleaned up: {file_path.name}")
        except Exception as e:
            logger.warning(f"Failed to cleanup {file_path.name}: {e}")

    # prepare_source leaves an empty flock file next to the download. The
    # inode stays while the video is live so two workers cannot normalize
    # different files under the same name. Once the video is gone, the lock
    # is the only thing that would keep this directory from being removed.
    if source_path is not None and not source_path.is_dir():
        for leftover in (
            source_path.with_name(f".{source_path.name}.normalize.lock"),
            *source_path.parent.glob(f".{source_path.name}.*.capped.mp4"),
        ):
            try:
                leftover.unlink(missing_ok=True)
            except OSError as exc:
                logger.warning("Failed to cleanup %s: %s", leftover.name, exc)

    if provider_dir:
        try:
            temp_dir.rmdir()
        except OSError:
            pass  # Keep a directory containing cached word timings or other files.


# Backward compatibility functions
def extract_video_id(url: str) -> Optional[str]:
    """Backward compatibility wrapper."""
    return get_youtube_video_id(url)