import os
import sys
import tempfile
import subprocess
import re
import time

def download_video(url, output_dir=None, cookies_from_browser=None):
    """Downloads a video from the given URL to a temporary location or specified output directory.

    Args:
        url (str): The URL of the video to download.
        output_dir (str, optional): Directory to save the downloaded file. If None, uses a temporary directory.

    Returns:
        str: The absolute path to the downloaded video file, or None if download fails.
    """
    if output_dir is None:
        output_dir = os.getcwd()

    if not os.path.isdir(output_dir):
        print(f"Error: Output directory '{output_dir}' for download does not exist or is not a directory.", file=sys.stderr)
        return None

    # Construct yt-dlp command
    download_filename = "yt_dlp_downloaded_video.mp4"
    yt_dlp_command = [
        "yt-dlp",
        "--format", "bestvideo[ext!=webm]+bestaudio[ext!=webm]/best[ext!=webm]", # Prioritize non-webm formats
        "--output", os.path.join(output_dir, download_filename),
        "--no-playlist", # Only download single video, not entire playlist
        "--quiet", 
        "--no-warnings",
        url
    ]

    if cookies_from_browser and cookies_from_browser != "none":
        yt_dlp_command.extend(["--cookies-from-browser", cookies_from_browser])

    downloaded_file_path = None
    try:
        # print(f"Executing yt-dlp command: {' '.join(yt_dlp_command)}", file=sys.stderr)
        process = subprocess.run(
            yt_dlp_command,
            capture_output=True,
            text=True,
            check=True
        )
        # print(f"DEBUG: yt-dlp stdout: {process.stdout}", file=sys.stderr)
        # print(f"DEBUG: yt-dlp stderr: {process.stderr}", file=sys.stderr)

        # The downloaded file path is now explicitly set
        downloaded_file_path = os.path.join(output_dir, download_filename)
        
        # print(f"DEBUG: Parsed downloaded_file_path: {downloaded_file_path}", file=sys.stderr)

        # Add retry logic for file existence
        max_retries = 5
        retry_delay = 1 # seconds
        for i in range(max_retries):
            if downloaded_file_path and os.path.exists(downloaded_file_path):
                break
            # print(f"DEBUG: Waiting for downloaded file to appear... (Attempt {i+1}/{max_retries})", file=sys.stderr)
            time.sleep(retry_delay)
        else:
            print(f"Error: Downloaded file not found at expected path after {max_retries} retries: {downloaded_file_path}", file=sys.stderr)
            return None

    except subprocess.CalledProcessError as e:
        print(f"Error running yt-dlp: {e}", file=sys.stderr)
        print(f"yt-dlp Stderr: {e.stderr}", file=sys.stderr)
        return None
    except FileNotFoundError:
        print("Error: yt-dlp not found. Please ensure yt-dlp is installed and in your PATH.", file=sys.stderr)
        return None
    except Exception as e:
        print(f"An unexpected error occurred during download: {e}", file=sys.stderr)
        return None

    return downloaded_file_path