#!/usr/bin/env python3
"""
PunimTag CLI Setup Script
Simple setup for the minimal photo tagger
"""

import os
import sys
import subprocess
from pathlib import Path


def check_python_version():
    """Check if Python version is compatible"""
    if sys.version_info < (3, 7):
        print("❌ Python 3.7+ is required")
        return False
    print(f"✅ Python {sys.version_info.major}.{sys.version_info.minor} detected")
    return True


def install_system_dependencies():
    """Install system-level packages required for compilation and runtime"""
    print("🔧 Installing system dependencies...")
    print("   (Build tools, libraries, and image viewer)")
    
    # Check if we're on a Debian/Ubuntu system
    if Path("/usr/bin/apt").exists():
        try:
            # Install required system packages for building Python packages and running tools
            packages = [
                "cmake", "build-essential", "libopenblas-dev", "liblapack-dev",
                "libx11-dev", "libgtk-3-dev", "libboost-python-dev", "feh"
            ]
            
            print(f"📦 Installing packages: {', '.join(packages)}")
            subprocess.run([
                "sudo", "apt", "install", "-y"
            ] + packages, check=True)
            print("✅ System dependencies installed successfully")
            return True
        except subprocess.CalledProcessError as e:
            print(f"❌ Failed to install system dependencies: {e}")
            print("   You may need to run: sudo apt update")
            return False
    else:
        print("⚠️  System dependency installation not supported on this platform")
        print("   Please install manually:")
        print("   - cmake, build-essential")
        print("   - libopenblas-dev, liblapack-dev")
        print("   - libx11-dev, libgtk-3-dev, libboost-python-dev")
        print("   - feh (image viewer)")
        return True


def install_requirements():
    """Install Python requirements"""
    requirements_file = Path("requirements.txt")
    
    if not requirements_file.exists():
        print("❌ requirements.txt not found!")
        return False
    
    print("📦 Installing Python dependencies...")
    try:
        subprocess.run([
            sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'
        ], check=True)
        print("✅ Dependencies installed successfully")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to install dependencies: {e}")
        return False


def create_directories():
    """Create necessary directories"""
    directories = ['data', 'logs']
    
    for directory in directories:
        Path(directory).mkdir(exist_ok=True)
        print(f"✅ Created directory: {directory}")


def test_installation():
    """Test if DeepFace face recognition works"""
    print("🧪 Testing DeepFace face recognition installation...")
    try:
        from deepface import DeepFace
        import numpy as np
        from PIL import Image
        import tensorflow as tf
        print("✅ All required modules imported successfully")
        return True
    except ImportError as e:
        print(f"❌ Import error: {e}")
        return False


def main():
    """Main setup function"""
    print("🚀 PunimTag CLI Setup")
    print("=" * 40)
    
    # Check Python version
    if not check_python_version():
        return 1
    
    # Check if we're in a virtual environment (recommended)
    if sys.prefix == sys.base_prefix:
        print("⚠️  Not in a virtual environment!")
        print("   Recommended: python -m venv venv && source venv/bin/activate")
        response = input("   Continue anyway? (y/N): ").strip().lower()
        if response != 'y':
            print("Setup cancelled. Create a virtual environment first.")
            return 1
    else:
        print("✅ Virtual environment detected")
    
    print()
    
    # Install system dependencies
    if not install_system_dependencies():
        return 1
    print()
    
    # Create directories
    print("📁 Creating directories...")
    create_directories()
    print()
    
    # Install requirements
    if not install_requirements():
        return 1
    print()
    
    # Test installation
    if not test_installation():
        print("⚠️  Installation test failed. You may need to install additional dependencies.")
        print("   For Ubuntu/Debian: sudo apt-get install build-essential cmake")
        print("   For macOS: brew install cmake")
        return 1
    print()
    
    print("✅ Setup complete!")
    print()
    print("🎯 Quick Start:")
    print("   1. Start the web server: python run_api_with_worker.sh")
    print("   2. Access the web interface at http://localhost:8000")
    print("   3. Use the web UI to scan, process, and identify faces")
    print()
    print("📖 For more information, see README.md")
    print()
    print("⚠️  IMPORTANT: Always activate virtual environment first!")
    print("   source venv/bin/activate")
    
    return 0


if __name__ == '__main__':
    sys.exit(main())
