import os
from pathlib import Path


class ProductionConfig:
    """Production server configuration"""
    
    @staticmethod
    def generate_gunicorn_config(output_file: str = 'gunicorn.conf.py'):
        """Generate Gunicorn configuration"""
        config = '''import multiprocessing

bind = "0.0.0.0:5000"
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = "sync"
worker_connections = 1000
timeout = 30
keepalive = 2
max_requests = 1000
max_requests_jitter = 100
preload_app = True
accesslog = "-"
errorlog = "-"
loglevel = "info"
'''
        
        with open(output_file, 'w') as f:
            f.write(config)
        
        return output_file
    
    @staticmethod
    def generate_uvicorn_config():
        """Generate Uvicorn configuration for async apps"""
        return {
            'host': '0.0.0.0',
            'port': 5000,
            'workers': 4,
            'loop': 'auto',
            'log_level': 'info',
            'access_log': True,
            'reload': False
        }
    
    @staticmethod
    def generate_nginx_config(domain: str = 'example.com', output_file: str = 'nginx.conf'):
        """Generate Nginx reverse proxy configuration"""
        config = f'''server {{
    listen 80;
    server_name {domain};
    
    location / {{
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }}
    
    location /static {{
        alias /var/www/static;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }}
}}
'''
        
        with open(output_file, 'w') as f:
            f.write(config)
        
        return output_file
    
    @staticmethod
    def create_health_check_endpoint(app):
        """Add health check endpoint to Flask app"""
        @app.route('/health')
        def health_check():
            return {'status': 'healthy', 'version': '1.0.0'}, 200
        
        @app.route('/readiness')
        def readiness_check():
            return {'status': 'ready'}, 200


class AssetPipeline:
    """Production asset pipeline"""
    
    def __init__(self, static_dir: str = 'static', output_dir: str = 'dist'):
        self.static_dir = Path(static_dir)
        self.output_dir = Path(output_dir)
    
    def bundle_assets(self):
        """Bundle and minify assets"""
        self.output_dir.mkdir(exist_ok=True)
        
        import shutil
        shutil.copytree(self.static_dir, self.output_dir / 'static', dirs_exist_ok=True)
    
    def generate_cache_manifest(self):
        """Generate asset cache manifest with hashes"""
        import hashlib
        
        manifest = {}
        
        for asset_file in self.output_dir.rglob('*'):
            if asset_file.is_file():
                with open(asset_file, 'rb') as f:
                    content = f.read()
                    file_hash = hashlib.md5(content).hexdigest()[:8]
                
                relative_path = asset_file.relative_to(self.output_dir)
                manifest[str(relative_path)] = {
                    'hash': file_hash,
                    'size': len(content)
                }
        
        import json
        with open(self.output_dir / 'manifest.json', 'w') as f:
            json.dump(manifest, f, indent=2)
        
        return manifest
