"""Utilities for Content Creation From YouTube and Local MP4 Videos"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_yt.ipynb.

# %% auto 0
__all__ = ['yt_chapters', 'transcribe_local_video', 'transcribe']

# %% ../nbs/01_yt.ipynb 3
import re
import subprocess
import tempfile
from pathlib import Path
from typing import Optional, Annotated
import typer
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
from .gem import gem
import whisper

# %% ../nbs/01_yt.ipynb 5
def yt_chapters(url_or_path):
    "Generate YouTube Summary and Chapters from a video (YouTube URL or local MP4)."
    
    chapter_prompt="Generate a succinct video summary (1-2 sentences) followed by video chapter timestamps for this video. Format each line of the chapter summaries as 'MM:SS - Chapter Title' (e.g., '02:30 - Introduction'). Start with 00:00. Include all major topics and transitions and be thorough - do not miss any important topics.  For the summary, do not say 'In this video, we will cover the following topics', 'This video discusses..' or anything like that. Instead, reference the main speaker's name if you know it.  If there is a Q&A Section, enumerate individual questions as additional chapters."
    return gem(prompt=chapter_prompt, o=url_or_path, model="gemini-3-pro-preview")

# %% ../nbs/01_yt.ipynb 11
def _extract_video_id(url: str) -> Optional[str]:
    """Extract YouTube video ID from various URL formats."""
    for pattern in [r'(?:youtube\.com/watch\?v=|youtu\.be/)([^&\n?#]+)', 
                    r'youtube\.com/embed/([^&\n?#]+)', 
                    r'youtube\.com/v/([^&\n?#]+)']:
        if match := re.search(pattern, url): return match.group(1)
    return url if re.match(r'^[a-zA-Z0-9_-]{11}$', url) else None

def _format_timestamp(seconds: float) -> str:
    """Convert seconds to HH:MM:SS format."""
    h, m, s = int(seconds // 3600), int((seconds % 3600) // 60), int(seconds % 60)
    return f"{h:02d}:{m:02d}:{s:02d}"
        
def _format_seconds(seconds: float): return f"{int(seconds):d}s"       

def transcribe_local_video(file_path, seconds_only=False):
    "Transcribe local MP4 video using Whisper."
    with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_audio:
        try:
            # Use ffmpeg to extract audio
            cmd = ["ffmpeg", "-i", str(file_path), "-q:a", "0", "-map", "a", 
                   temp_audio.name, "-y", "-loglevel", "error"]
            subprocess.run(cmd, check=True)
            
            # Load Whisper model and transcribe
            model = whisper.load_model("large-v3-turbo")
            result = model.transcribe(temp_audio.name)
            
            # Format output to match YouTube transcript format
            format_func = _format_seconds if seconds_only else _format_timestamp
            transcript_text = '\n'.join(f"[{format_func(segment['start'])}] {segment['text'].strip()}" 
                                       for segment in result['segments'])
            return transcript_text
        finally:
            # Clean up temp file
            Path(temp_audio.name).unlink(missing_ok=True)

def transcribe(url_or_path, seconds_only=False):
    "Download YouTube transcript or transcribe local video."
    path = Path(url_or_path)
    
    # Check if input is a local file
    if path.exists() and path.suffix.lower() == '.mp4':
        return transcribe_local_video(url_or_path, seconds_only)
    
    # Otherwise treat as YouTube URL
    if not (video_id := _extract_video_id(url_or_path)): 
        raise ValueError(f"Could not extract video ID from '{url_or_path}'")
    try: 
        transcript_data = YouTubeTranscriptApi().fetch(video_id, languages=['en'])
    except (TranscriptsDisabled, NoTranscriptFound) as e: 
        raise ValueError(f"{str(e)} for video: {video_id}")
    format_func = _format_seconds if seconds_only else _format_timestamp
    transcript_text = '\n'.join(f"[{format_func(e.start)}] {e.text}" for e in transcript_data)
    return transcript_text
