#!/usr/bin/env python3
"""
Setup script for Manufacturing App
This script helps with initial project configuration and setup.
"""

import os
import sys
import subprocess
import secrets
from pathlib import Path

def run_command(command, description):
    """Run a shell command and handle errors"""
    print(f"🔄 {description}...")
    try:
        result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
        print(f"✅ {description} completed successfully")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} failed: {e}")
        print(f"Error output: {e.stderr}")
        return False

def create_env_file():
    """Create .env file with secure settings"""
    env_file = Path('.env')
    if env_file.exists():
        print("📝 .env file already exists, skipping creation")
        return True
    
    # Generate a secure secret key
    secret_key = ''.join(secrets.choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50))
    
    env_content = f"""# Django Settings
SECRET_KEY={secret_key}
DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1

# Database Settings (for future PostgreSQL migration)
# DB_ENGINE=django.db.backends.postgresql
# DB_NAME=manufacture_db
# DB_USER=manufacture_user
# DB_PASSWORD=your_password_here
# DB_HOST=localhost
# DB_PORT=5432
"""
    
    try:
        with open(env_file, 'w') as f:
            f.write(env_content)
        print("✅ .env file created successfully")
        return True
    except Exception as e:
        print(f"❌ Failed to create .env file: {e}")
        return False

def create_directories():
    """Create necessary directories"""
    directories = ['static', 'media', 'backups', 'logs']
    
    for directory in directories:
        dir_path = Path(directory)
        if not dir_path.exists():
            dir_path.mkdir(exist_ok=True)
            print(f"📁 Created directory: {directory}")
        else:
            print(f"📁 Directory already exists: {directory}")

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

def install_dependencies():
    """Install Python dependencies"""
    if not run_command("pip install -r requirements.txt", "Installing dependencies"):
        return False
    
    return True

def setup_database():
    """Set up the database"""
    commands = [
        ("python manage.py makemigrations", "Creating database migrations"),
        ("python manage.py migrate", "Applying database migrations"),
    ]
    
    for command, description in commands:
        if not run_command(command, description):
            return False
    
    return True

def create_superuser():
    """Create a superuser account"""
    print("👤 Creating superuser account...")
    print("Please enter the following information:")
    
    try:
        # Run the createsuperuser command interactively
        subprocess.run("python manage.py createsuperuser", shell=True, check=True)
        print("✅ Superuser created successfully")
        return True
    except subprocess.CalledProcessError:
        print("❌ Failed to create superuser")
        return False

def main():
    """Main setup function"""
    print("🚀 Manufacturing App Setup")
    print("=" * 40)
    
    # Check Python version
    if not check_python_version():
        sys.exit(1)
    
    # Create necessary directories
    create_directories()
    
    # Create .env file
    if not create_env_file():
        sys.exit(1)
    
    # Install dependencies
    if not install_dependencies():
        print("❌ Setup failed at dependency installation")
        sys.exit(1)
    
    # Setup database
    if not setup_database():
        print("❌ Setup failed at database setup")
        sys.exit(1)
    
    # Create superuser
    if not create_superuser():
        print("❌ Setup failed at superuser creation")
        sys.exit(1)
    
    print("\n🎉 Setup completed successfully!")
    print("\nNext steps:")
    print("1. Run the development server: python manage.py runserver")
    print("2. Open your browser and go to: http://127.0.0.1:8000/")
    print("3. Log in with your superuser credentials")
    print("4. Start using the Manufacturing App!")
    
    print("\n📚 For more information, check the README.md file")

if __name__ == "__main__":
    main()
