"""
Setup script for the YouTube Processing Workflow project.
"""
import os
import sys
import subprocess
import platform

def check_python_version():
    """Check if Python version is compatible."""
    version = sys.version_info
    if version.major < 3 or (version.major == 3 and version.minor < 8):
        print("❌ Python 3.8+ is required. Current version:", sys.version)
        return False
    print(f"✅ Python version OK: {sys.version}")
    return True

def install_dependencies():
    """Install required dependencies."""
    print("📦 Installing dependencies...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("✅ Dependencies installed successfully!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to install dependencies: {str(e)}")
        return False

def setup_environment():
    """Setup environment configuration."""
    print("⚙️  Setting up environment...")
    
    if os.path.exists(".env"):
        print("✅ .env file already exists")
        return True
    
    if os.path.exists("env.example"):
        print("📝 Creating .env file from example...")
        try:
            with open("env.example", "r") as example_file:
                with open(".env", "w") as env_file:
                    env_file.write(example_file.read())
            print("✅ .env file created!")
            print("💡 Please edit .env to add your API keys")
            return True
        except Exception as e:
            print(f"❌ Failed to create .env file: {str(e)}")
            return False
    else:
        print("⚠️  env.example file not found")
        return False

def check_ffmpeg():
    """Check if FFmpeg is available."""
    print("🎵 Checking FFmpeg installation...")
    
    try:
        result = subprocess.run(["ffmpeg", "-version"], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ FFmpeg is installed and available")
            return True
        else:
            print("❌ FFmpeg not found or not working properly")
            return False
    except FileNotFoundError:
        print("❌ FFmpeg not found")
        print("📖 Please install FFmpeg:")
        
        system = platform.system().lower()
        if system == "windows":
            print("   - Download from https://ffmpeg.org/download.html")
            print("   - Or use chocolatey: choco install ffmpeg")
        elif system == "darwin":  # macOS
            print("   - Homebrew: brew install ffmpeg")
        else:  # Linux
            print("   - Ubuntu/Debian: sudo apt update && sudo apt install ffmpeg")
            print("   - CentOS/RHEL: sudo yum install ffmpeg")
        
        return False

def run_quick_test():
    """Run a quick test to verify installation."""
    print("🧪 Running quick test...")
    
    try:
        # Test imports
        import crewai
        print("✅ CrewAI import successful")
        
        import whisper
        print("✅ Whisper import successful")
        
        import yt_dlp
        print("✅ yt-dlp import successful")
        
        import flask
        print("✅ Flask import successful")
        
        print("✅ All core dependencies imported successfully!")
        return True
        
    except ImportError as e:
        print(f"❌ Import test failed: {str(e)}")
        return False

def print_next_steps():
    """Print next steps for the user."""
    print("\\n🎉 Setup completed!")
    print("=" * 40)
    print("📋 Next Steps:")
    print("")
    print("1. 📝 Edit .env file with your API keys:")
    print("   - PERPLEXITY_API_KEY (or OPENAI_API_KEY)")
    print("   - NOTELETT_API_KEY")
    print("   - NOTELETT_API_URL")
    print("")
    print("2. 🧪 Test the installation:")
    print("   python test.py")
    print("")
    print("3. 🚀 Run an example:")
    print("   python example.py")
    print("")
    print("4. 📖 Read the documentation:")
    print("   See README.md for detailed usage instructions")
    print("")
    print("💡 Quick Examples:")
    print("   python demo.py              # Interactive demo")
    print("   python workflow.py <args>  # Command line usage")
    print("   python api.py               # Start API server")

def main():
    """Main setup function."""
    print("🚀 YouTube Processing Workflow Setup")
    print("=" * 40)
    
    # Check prerequisites
    success = True
    
    success &= check_python_version()
    success &= install_dependencies()
    success &= setup_environment()
    success &= check_ffmpeg()
    success &= run_quick_test()
    
    if success:
        print_next_steps()
    else:
        print("\\n❌ Setup encountered issues. Please fix the problems above.")
        sys.exit(1)

if __name__ == "__main__":
    main()

