#!/usr/bin/env python3 """Environment setup script for the chat agent application.""" import os import sys import shutil import subprocess from pathlib import Path def create_directories(): """Create necessary directories for the application.""" directories = [ 'logs', 'instance', 'ssl', 'backups', 'config' ] for directory in directories: Path(directory).mkdir(exist_ok=True) print(f"Created directory: {directory}") def setup_environment_file(environment='development'): """Set up environment file for specified environment.""" env_file = f"config/{environment}.env" target_file = ".env" if Path(env_file).exists(): shutil.copy(env_file, target_file) print(f"Copied {env_file} to {target_file}") else: print(f"Warning: {env_file} not found") # Create basic .env from .env.example if it exists if Path(".env.example").exists(): shutil.copy(".env.example", target_file) print(f"Copied .env.example to {target_file}") else: print("Warning: No environment template found") def install_dependencies(): """Install Python dependencies.""" print("Installing Python dependencies...") try: subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"], check=True) print("Dependencies installed successfully!") except subprocess.CalledProcessError as e: print(f"Error installing dependencies: {e}") sys.exit(1) def check_system_requirements(): """Check if system requirements are met.""" print("Checking system requirements...") # Check Python version if sys.version_info < (3, 8): print("Error: Python 3.8 or higher is required") sys.exit(1) print(f"✓ Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}") # Check if PostgreSQL is available try: import psycopg2 print("✓ PostgreSQL driver available") except ImportError: print("Warning: PostgreSQL driver not available. Install with: pip install psycopg2-binary") # Check if Redis is available try: import redis print("✓ Redis client available") except ImportError: print("Warning: Redis client not available. Install with: pip install redis") def setup_git_hooks(): """Set up Git hooks for development.""" hooks_dir = Path(".git/hooks") if not hooks_dir.exists(): print("Warning: Not a Git repository, skipping Git hooks setup") return # Pre-commit hook for code quality pre_commit_hook = hooks_dir / "pre-commit" pre_commit_content = """#!/bin/bash # Pre-commit hook for code quality checks echo "Running pre-commit checks..." # Run tests python -m pytest tests/ --quiet if [ $? -ne 0 ]; then echo "Tests failed. Commit aborted." exit 1 fi # Check for common issues python -m flake8 chat_agent/ --max-line-length=100 --ignore=E203,W503 if [ $? -ne 0 ]; then echo "Code style issues found. Please fix before committing." exit 1 fi echo "Pre-commit checks passed!" """ with open(pre_commit_hook, 'w') as f: f.write(pre_commit_content) # Make executable os.chmod(pre_commit_hook, 0o755) print("✓ Git pre-commit hook installed") def generate_secret_key(): """Generate a secure secret key for Flask.""" import secrets secret_key = secrets.token_urlsafe(32) print(f"Generated secret key: {secret_key}") print("Add this to your environment configuration:") print(f"SECRET_KEY={secret_key}") return secret_key def setup_logging(): """Set up logging configuration.""" log_config = """ import logging import logging.config LOGGING_CONFIG = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s', }, 'detailed': { 'format': '[%(asctime)s] %(levelname)s in %(module)s [%(pathname)s:%(lineno)d]: %(message)s', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter': 'default', 'stream': 'ext://sys.stdout' }, 'file': { 'class': 'logging.handlers.RotatingFileHandler', 'level': 'DEBUG', 'formatter': 'detailed', 'filename': 'logs/chat_agent.log', 'maxBytes': 10485760, # 10MB 'backupCount': 5 } }, 'loggers': { 'chat_agent': { 'level': 'DEBUG', 'handlers': ['console', 'file'], 'propagate': False } }, 'root': { 'level': 'INFO', 'handlers': ['console'] } } def setup_logging(): logging.config.dictConfig(LOGGING_CONFIG) """ with open('chat_agent/utils/logging_setup.py', 'w') as f: f.write(log_config) print("✓ Logging configuration created") def main(): """Main setup function.""" import argparse parser = argparse.ArgumentParser(description="Environment setup for chat agent") parser.add_argument( "--environment", default="development", choices=["development", "production", "testing"], help="Environment to set up" ) parser.add_argument( "--skip-deps", action="store_true", help="Skip dependency installation" ) parser.add_argument( "--skip-db", action="store_true", help="Skip database initialization" ) args = parser.parse_args() print(f"Setting up environment: {args.environment}") print("=" * 50) # Check system requirements check_system_requirements() # Create directories create_directories() # Set up environment file setup_environment_file(args.environment) # Install dependencies if not args.skip_deps: install_dependencies() # Set up Git hooks (development only) if args.environment == 'development': setup_git_hooks() # Generate secret key if args.environment != 'testing': generate_secret_key() # Set up logging setup_logging() # Initialize database if not args.skip_db: print("\nInitializing database...") try: from scripts.init_db import init_database init_database(args.environment) except Exception as e: print(f"Database initialization failed: {e}") print("You can run it manually later with: python scripts/init_db.py init") print("\n" + "=" * 50) print("Environment setup completed!") print(f"Environment: {args.environment}") print("\nNext steps:") print("1. Update your .env file with actual API keys and database credentials") print("2. Start the application with: python app.py") print("3. Visit http://localhost:5000 to test the chat interface") if args.environment == 'development': print("4. Run tests with: python -m pytest tests/") if __name__ == "__main__": main()