#!/usr/bin/env python3
"""
Setup script for CBCFacil
"""
import os
import sys
import subprocess
import platform
from pathlib import Path


def check_python_version():
    """Check if Python version is 3.10 or higher"""
    if sys.version_info < (3, 10):
        print("❌ Error: Python 3.10 or higher is required")
        print(f"   Current version: {sys.version}")
        sys.exit(1)
    print(f"✓ Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")


def check_system_dependencies():
    """Check and install system dependencies"""
    system = platform.system().lower()

    print("\n📦 Checking system dependencies...")

    if system == "linux":
        # Check for CUDA (optional)
        if os.path.exists("/usr/local/cuda"):
            print("✓ CUDA found")
        else:
            print("⚠ CUDA not found - GPU acceleration will be disabled")

        # Check for tesseract
        try:
            subprocess.run(["tesseract", "--version"], check=True, capture_output=True)
            print("✓ Tesseract OCR installed")
        except (subprocess.CalledProcessError, FileNotFoundError):
            print("⚠ Tesseract OCR not found - PDF processing may not work")

        # Check for ffmpeg
        try:
            subprocess.run(["ffmpeg", "-version"], check=True, capture_output=True)
            print("✓ FFmpeg installed")
        except (subprocess.CalledProcessError, FileNotFoundError):
            print("⚠ FFmpeg not found - audio processing may not work")

    elif system == "darwin":  # macOS
        # Check for tesseract
        try:
            subprocess.run(["brew", "list", "tesseract"], check=True, capture_output=True)
            print("✓ Tesseract OCR installed")
        except (subprocess.CalledProcessError, FileNotFoundError):
            print("⚠ Tesseract not found. Install with: brew install tesseract")

    print()


def create_virtual_environment():
    """Create Python virtual environment"""
    venv_path = Path("venv")

    if venv_path.exists():
        print("✓ Virtual environment already exists")
        return venv_path

    print("📦 Creating virtual environment...")
    subprocess.run([sys.executable, "-m", "venv", "venv"], check=True)
    print("✓ Virtual environment created")
    return venv_path


def install_requirements(venv_path):
    """Install Python requirements"""
    pip_path = venv_path / ("Scripts" if platform.system() == "Windows" else "bin") / "pip"

    print("📦 Installing Python requirements...")
    subprocess.run([str(pip_path), "install", "--upgrade", "pip"], check=True)
    subprocess.run([str(pip_path), "install", "-r", "requirements.txt"], check=True)
    print("✓ Python requirements installed")


def create_directories():
    """Create necessary directories"""
    directories = [
        "downloads",
        "resumenes_docx",
        "logs",
        "processed"
    ]

    print("\n📁 Creating directories...")
    for directory in directories:
        Path(directory).mkdir(exist_ok=True)
        print(f"  ✓ {directory}")

    print()


def create_env_file():
    """Create .env file if it doesn't exist"""
    env_path = Path(".env")
    example_path = Path(".env.example")

    if env_path.exists():
        print("✓ .env file already exists")
        return

    if not example_path.exists():
        print("⚠ .env.example not found")
        return

    print("\n📝 Creating .env file from template...")
    print("   Please edit .env file and add your API keys")

    with open(example_path, "r") as src:
        content = src.read()

    with open(env_path, "w") as dst:
        dst.write(content)

    print("✓ .env file created from .env.example")
    print("   ⚠ Please edit .env and add your API keys!")


def main():
    """Main setup function"""
    print("=" * 60)
    print("CBCFacil Setup Script")
    print("=" * 60)
    print()

    # Check Python version
    check_python_version()

    # Check system dependencies
    check_system_dependencies()

    # Create virtual environment
    venv_path = create_virtual_environment()

    # Install requirements
    install_requirements(venv_path)

    # Create directories
    create_directories()

    # Create .env file
    create_env_file()

    print("\n" + "=" * 60)
    print("✓ Setup complete!")
    print("=" * 60)
    print("\nNext steps:")
    print("  1. Edit .env file and add your API keys")
    print("  2. Run: source venv/bin/activate  (Linux/macOS)")
    print("           or venv\\Scripts\\activate     (Windows)")
    print("  3. Run: python main_refactored.py")
    print("\nFor dashboard only:")
    print("  python -c \"from api.routes import create_app; app = create_app(); app.run(port=5000)\"")
    print()


if __name__ == "__main__":
    main()
