#!/usr/bin/env python3
"""
macOS setup script for Karaoke Video Downloader.
This script helps users set up yt-dlp and FFmpeg on macOS.
"""

import os
import sys
import subprocess
from pathlib import Path


def check_ffmpeg():
    """Check if FFmpeg is installed."""
    try:
        result = subprocess.run(["ffmpeg", "-version"], capture_output=True, text=True, timeout=10)
        return result.returncode == 0
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return False


def check_yt_dlp():
    """Check if yt-dlp is installed via pip or binary."""
    # Check pip installation
    try:
        result = subprocess.run([sys.executable, "-m", "yt_dlp", "--version"], 
                              capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            return True
    except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
        pass
    
    # Check binary file
    binary_path = Path("downloader/yt-dlp_macos")
    if binary_path.exists():
        try:
            result = subprocess.run([str(binary_path), "--version"], 
                                  capture_output=True, text=True, timeout=10)
            return result.returncode == 0
        except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
            pass
    
    return False


def install_ffmpeg():
    """Install FFmpeg via Homebrew."""
    print("🎬 Installing FFmpeg...")
    
    # Check if Homebrew is installed
    try:
        subprocess.run(["brew", "--version"], capture_output=True, check=True)
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("❌ Homebrew is not installed. Please install Homebrew first:")
        print("   /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"")
        return False
    
    try:
        print("🍺 Installing FFmpeg via Homebrew...")
        result = subprocess.run(["brew", "install", "ffmpeg"], 
                              capture_output=True, text=True, check=True)
        print("✅ FFmpeg installed successfully!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to install FFmpeg: {e}")
        return False


def download_yt_dlp_binary():
    """Download yt-dlp binary for macOS."""
    print("📥 Downloading yt-dlp binary for macOS...")
    
    # Create downloader directory if it doesn't exist
    downloader_dir = Path("downloader")
    downloader_dir.mkdir(exist_ok=True)
    
    # Download yt-dlp binary
    binary_path = downloader_dir / "yt-dlp_macos"
    url = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos"
    
    try:
        print(f"📡 Downloading from: {url}")
        result = subprocess.run(["curl", "-L", "-o", str(binary_path), url], 
                              capture_output=True, text=True, check=True)
        
        # Make it executable
        binary_path.chmod(0o755)
        print(f"✅ yt-dlp binary downloaded to: {binary_path}")
        
        # Test the binary
        test_result = subprocess.run([str(binary_path), "--version"], 
                                   capture_output=True, text=True, timeout=10)
        if test_result.returncode == 0:
            version = test_result.stdout.strip()
            print(f"✅ Binary test successful! Version: {version}")
            return True
        else:
            print(f"❌ Binary test failed: {test_result.stderr}")
            return False
            
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to download yt-dlp binary: {e}")
        return False
    except Exception as e:
        print(f"❌ Error downloading binary: {e}")
        return False


def install_yt_dlp():
    """Install yt-dlp via pip."""
    print("📦 Installing yt-dlp...")
    
    try:
        result = subprocess.run([sys.executable, "-m", "pip", "install", "yt-dlp"], 
                              capture_output=True, text=True, check=True)
        print("✅ yt-dlp installed successfully!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to install yt-dlp: {e}")
        return False


def test_installation():
    """Test the installation."""
    print("\n🧪 Testing installation...")
    
    # Test FFmpeg
    if check_ffmpeg():
        print("✅ FFmpeg is working!")
    else:
        print("❌ FFmpeg is not working")
        return False
    
    # Test yt-dlp
    if check_yt_dlp():
        print("✅ yt-dlp is working!")
    else:
        print("❌ yt-dlp is not working")
        return False
    
    return True


def main():
    print("🍎 macOS Setup for Karaoke Video Downloader")
    print("=" * 50)
    
    # Check current status
    print("🔍 Checking current installation...")
    ffmpeg_installed = check_ffmpeg()
    yt_dlp_installed = check_yt_dlp()
    
    print(f"FFmpeg: {'✅ Installed' if ffmpeg_installed else '❌ Not installed'}")
    print(f"yt-dlp: {'✅ Installed' if yt_dlp_installed else '❌ Not installed'}")
    
    if ffmpeg_installed and yt_dlp_installed:
        print("\n🎉 Everything is already installed and working!")
        return
    
    # Install missing components
    print("\n🚀 Installing missing components...")
    
    # Install FFmpeg if needed
    if not ffmpeg_installed:
        print("\n🎬 FFmpeg Installation Options:")
        print("1. Install via Homebrew (recommended)")
        print("2. Download from ffmpeg.org")
        print("3. Skip FFmpeg installation")
        
        choice = input("\nChoose an option (1-3): ").strip()
        
        if choice == "1":
            if not install_ffmpeg():
                print("❌ FFmpeg installation failed")
                return
        elif choice == "2":
            print("📥 Please download FFmpeg from: https://ffmpeg.org/download.html")
            print("   Extract and add to your PATH, then run this script again.")
            return
        elif choice == "3":
            print("⚠️ FFmpeg is required for video processing. Some features may not work.")
        else:
            print("❌ Invalid choice")
            return
    
    # Install yt-dlp if needed
    if not yt_dlp_installed:
        print("\n📦 yt-dlp Installation Options:")
        print("1. Install via pip (recommended)")
        print("2. Download binary file")
        print("3. Skip yt-dlp installation")
        
        choice = input("\nChoose an option (1-3): ").strip()
        
        if choice == "1":
            if not install_yt_dlp():
                print("❌ yt-dlp installation failed")
                return
        elif choice == "2":
            if not download_yt_dlp_binary():
                print("❌ yt-dlp binary download failed")
                return
        elif choice == "3":
            print("❌ yt-dlp is required for video downloading.")
            return
        else:
            print("❌ Invalid choice")
            return
    
    # Test installation
    if test_installation():
        print("\n🎉 Setup completed successfully!")
        print("You can now use the Karaoke Video Downloader on macOS.")
        print("Run: python download_karaoke.py --help")
    else:
        print("\n❌ Setup failed. Please check the error messages above.")


if __name__ == "__main__":
    main() 