import re
from youtube_transcript_api import YouTubeTranscriptApi


def extract_video_id(url: str) -> str:
    patterns = [
        r"(?:v=|youtu\.be/)([A-Za-z0-9_-]{11})",
        r"(?:embed/)([A-Za-z0-9_-]{11})",
    ]
    for pattern in patterns:
        match = re.search(pattern, url)
        if match:
            return match.group(1)
    raise ValueError(f"Could not extract video ID from URL: {url}")


def fetch_transcript(url: str) -> tuple[str, str, int]:
    """Returns (title, transcript_text, duration_seconds)."""
    video_id = extract_video_id(url)

    api = YouTubeTranscriptApi()
    transcript_list = api.fetch(video_id)

    full_text = " ".join(entry.text for entry in transcript_list)
    duration = int(transcript_list[-1].start + transcript_list[-1].duration) if transcript_list else 0

    # Fetch title via oembed (no API key needed)
    import urllib.request, json
    oembed_url = f"https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={video_id}&format=json"
    try:
        with urllib.request.urlopen(oembed_url, timeout=10) as resp:
            data = json.loads(resp.read())
        title = data.get("title", "Unknown Title")
    except Exception:
        title = "Unknown Title"

    return title, full_text, duration
