# Co-Prod AI - Deployment Guide

## Overview

This guide covers deploying the Co-Prod AI platform to production environments, including cloud platforms, VPS, and containerized deployments.

---

## Deployment Options

### 1. Traditional VPS Deployment

#### Recommended VPS Providers
- DigitalOcean
- Linode
- AWS EC2
- Google Cloud Compute Engine
- Vultr

#### Server Specifications

**Minimum (Small Scale):**
- 2 CPU cores
- 4GB RAM
- 40GB SSD
- 1TB bandwidth

**Recommended (Medium Scale):**
- 4 CPU cores
- 8GB RAM
- 80GB SSD
- 2TB bandwidth

**High Performance (Large Scale):**
- 8+ CPU cores
- 16GB+ RAM
- 160GB+ SSD
- 4TB+ bandwidth

#### Deployment Steps

1. **Provision Server**
   - Create VPS with Ubuntu 22.04 LTS
   - Enable SSH key authentication
   - Configure firewall (allow ports 22, 80, 443)

2. **Install Dependencies**
   ```bash
   sudo apt update
   sudo apt upgrade -y
   sudo apt install -y apache2 mysql-server php8.3 php8.3-mysql php8.3-mbstring php8.3-json php8.3-openssl php8.3-gd php8.3-curl php8.3-zip php8.3-xml redis-server
   ```

3. **Configure Apache**
   ```bash
   sudo a2enmod rewrite
   sudo a2enmod ssl
   sudo systemctl restart apache2
   ```

4. **Deploy Application**
   ```bash
   # Clone repository
   git clone https://github.com/your-org/coprod-ai.git /var/www/coprod-ai
   
   # Set permissions
   cd /var/www/coprod-ai
   sudo chown -R www-data:www-data .
   sudo chmod -R 755 .
   sudo chmod -R 777 storage
   ```

5. **Configure SSL**
   ```bash
   sudo certbot --apache -d yourdomain.com
   ```

---

### 2. Docker Deployment

#### Dockerfile

Create `Dockerfile` in project root:

```dockerfile
FROM php:8.3-apache

# Install system dependencies
RUN apt-get update && apt-get install -y \
    libpng-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip \
    && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd zip xml

# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Set working directory
WORKDIR /var/www/html

# Copy application files
COPY . .

# Install dependencies
RUN composer install --no-dev --optimize-autoloader

# Set permissions
RUN chown -R www-data:www-data /var/www/html \
    && chmod -R 755 /var/www/html \
    && chmod -R 777 /var/www/html/storage

# Enable Apache mod_rewrite
RUN a2enmod rewrite

# Expose port 80
EXPOSE 80

# Start Apache
CMD ["apache2-foreground"]
```

#### Docker Compose

Create `docker-compose.yml`:

```yaml
version: '3.8'

services:
  web:
    build: .
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./storage:/var/www/html/storage
      - ./config:/var/www/html/config
    depends_on:
      - db
      - redis
    environment:
      - DB_HOST=db
      - DB_NAME=coprod_ai
      - DB_USER=coprod_user
      - DB_PASS=secure_password
      - REDIS_HOST=redis
    restart: unless-stopped

  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_DATABASE: coprod_ai
      MYSQL_USER: coprod_user
      MYSQL_PASSWORD: secure_password
    volumes:
      - mysql_data:/var/lib/mysql
      - ./database/schema.sql:/docker-entrypoint-initdb.d/schema.sql
    ports:
      - "3306:3306"
    restart: unless-stopped

  redis:
    image: redis:alpine
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    restart: unless-stopped

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./ssl:/etc/nginx/ssl
    depends_on:
      - web
    restart: unless-stopped

volumes:
  mysql_data:
  redis_data:
```

#### Deploy with Docker Compose

```bash
# Build and start containers
docker-compose up -d --build

# View logs
docker-compose logs -f

# Stop containers
docker-compose down

# Update and redeploy
git pull
docker-compose up -d --build
```

---

### 3. Kubernetes Deployment

#### Deployment Manifest

Create `k8s/deployment.yaml`:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: coprod-ai
  labels:
    app: coprod-ai
spec:
  replicas: 3
  selector:
    matchLabels:
      app: coprod-ai
  template:
    metadata:
      labels:
        app: coprod-ai
    spec:
      containers:
      - name: web
        image: your-registry/coprod-ai:latest
        ports:
        - containerPort: 80
        env:
        - name: DB_HOST
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: db-host
        - name: DB_NAME
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: db-name
        - name: DB_USER
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: username
        - name: DB_PASS
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: password
        resources:
          requests:
            memory: "512Mi"
            cpu: "500m"
          limits:
            memory: "1Gi"
            cpu: "1000m"
        volumeMounts:
        - name: storage
          mountPath: /var/www/html/storage
      volumes:
      - name: storage
        persistentVolumeClaim:
          claimName: storage-pvc
---
apiVersion: v1
kind: Service
metadata:
  name: coprod-ai-service
spec:
  selector:
    app: coprod-ai
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  type: LoadBalancer
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: storage-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
```

#### Deploy to Kubernetes

```bash
# Apply manifests
kubectl apply -f k8s/deployment.yaml
kubectl apply -f k8s/service.yaml
kubectl apply -f k8s/configmap.yaml
kubectl apply -f k8s/secrets.yaml

# Check deployment status
kubectl get deployments
kubectl get pods
kubectl get services
```

---

### 4. AWS Deployment

#### Using AWS Elastic Beanstalk

1. **Create Application**
   - Go to AWS Elastic Beanstalk console
   - Create new application
   - Choose "PHP" platform

2. **Upload Application**
   - Zip the application files
   - Upload to Elastic Beanstalk
   - Configure environment variables

3. **Environment Variables**
   ```
   DB_HOST = your-rds-endpoint
   DB_NAME = coprod_ai
   DB_USER = your_db_user
   DB_PASS = your_db_password
   ENVIRONMENT = production
   DEBUG = false
   ```

4. **Configure RDS**
   - Create MySQL RDS instance
   - Configure security groups
   - Import database schema

#### Using AWS EC2 + Load Balancer

1. **Launch EC2 Instances**
   - Use AMI with Ubuntu 22.04
   - Choose instance type (t3.medium or larger)
   - Configure security groups
   - Create launch template

2. **Set Up Application Load Balancer**
   - Create target group
   - Register EC2 instances
   - Configure health checks

3. **Configure Auto Scaling**
   - Set minimum/maximum instances
   - Configure scaling policies
   - Set up CloudWatch alarms

---

### 5. Google Cloud Platform Deployment

#### Using Google App Engine

1. **Create app.yaml**
   ```yaml
   runtime: php83
   env: flex
   
   runtime_config:
     document_root: public
   
   env_variables:
     DB_HOST: "your-cloud-sql-connection"
     DB_NAME: "coprod_ai"
     DB_USER: "your_user"
     DB_PASS: "your_password"
     ENVIRONMENT: "production"
     DEBUG: "false"
   
   automatic_scaling:
     min_num_instances: 1
     max_num_instances: 10
     cool_down_period_sec: 60
     cpu_utilization:
       target_utilization: 0.6
   ```

2. **Deploy**
   ```bash
   gcloud app deploy
   ```

#### Using Google Cloud Run

1. **Containerize Application**
   ```bash
   docker build -t gcr.io/your-project/coprod-ai .
   docker push gcr.io/your-project/coprod-ai
   ```

2. **Deploy to Cloud Run**
   ```bash
   gcloud run deploy coprod-ai \
     --image gcr.io/your-project/coprod-ai \
     --platform managed \
     --region us-central1 \
     --allow-unauthenticated
   ```

---

### 6. Azure Deployment

#### Using Azure App Service

1. **Create Web App**
   - Go to Azure Portal
   - Create "Web App" resource
   - Choose PHP runtime (8.3)

2. **Configure Deployment**
   - Connect to GitHub repository
   - Configure build settings
   - Set environment variables

3. **Configure Database**
   - Create Azure Database for MySQL
   - Configure connection string
   - Import schema

---

## Database Deployment

### Cloud SQL (Google Cloud)

```bash
# Create Cloud SQL instance
gcloud sql instances create coprod-ai-db \
    --tier=db-n1-standard-2 \
    --region=us-central1

# Create database
gcloud sql databases create coprod_ai \
    --instance=coprod-ai-db

# Import schema
gcloud sql import sql coprod-ai-db \
    gs://your-bucket/schema.sql
```

### Amazon RDS (AWS)

```bash
# Create RDS instance
aws rds create-db-instance \
    --db-instance-identifier coprod-ai-db \
    --db-instance-class db.t3.medium \
    --engine mysql \
    --master-username admin \
    --master-user-password secure_password \
    --allocated-storage 20

# Import schema
aws rds-data execute-statement \
    --resource-arn your-db-arn \
    --database coprod_ai \
    --sql "source database/schema.sql"
```

### Azure Database for MySQL

```bash
# Create MySQL server
az mysql server create \
    --name coprod-ai-db \
    --resource-group your-resource-group \
    --location eastus \
    --admin-user admin \
    --admin-password secure_password

# Create database
az mysql db create \
    --name coprod-ai \
    --server-name coprod-ai-db \
    --resource-group your-resource-group
```

---

## SSL/TLS Configuration

### Let's Encrypt (Certbot)

```bash
# Install Certbot
sudo apt-get install certbot python3-certbot-apache

# Obtain certificate
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

# Auto-renewal
sudo certbot renew --dry-run
```

### Cloudflare SSL

1. Add domain to Cloudflare
2. Set SSL mode to "Full (strict)"
3. Configure origin certificate
4. Upload certificate to server

### AWS Certificate Manager

```bash
# Request certificate
aws acm request-certificate \
    --domain-name yourdomain.com \
    --validation-method DNS

# Validate via DNS
# Add CNAME record to your DNS provider

# Import certificate to load balancer
```

---

## Load Balancing

### HAProxy Configuration

```haproxy
frontend coprod-ai-http
    bind *:80
    default_backend coprod-ai-web

frontend coprod-ai-https
    bind *:443 ssl crt /etc/ssl/cert.pem
    default_backend coprod-ai-web

backend coprod-ai-web
    balance roundrobin
    server web1 10.0.1.10:80 check
    server web2 10.0.1.11:80 check
    server web3 10.0.1.12:80 check
```

### Nginx Load Balancer

```nginx
upstream coprod-ai {
    least_conn;
    server 10.0.1.10:80 weight=5;
    server 10.0.1.11:80 weight=5;
    server 10.0.1.12:80 weight=5;
}

server {
    listen 80;
    server_name yourdomain.com;
    
    location / {
        proxy_pass http://coprod-ai;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
```

---

## Caching Strategy

### Redis Configuration

```php
// config/redis.php
return [
    'host' => env('REDIS_HOST', '127.0.0.1'),
    'port' => env('REDIS_PORT', 6379),
    'password' => env('REDIS_PASSWORD', null),
    'database' => env('REDIS_DB', 0),
    'cache_prefix' => 'coprod_ai_',
    'ttl' => 3600
];
```

### CDN Configuration

#### CloudFront (AWS)

```bash
# Create CloudFront distribution
aws cloudfront create-distribution \
    --origin-domain yourdomain.com \
    --default-cache-behavior \
        TargetOriginId=your-origin \
        ViewerProtocolPolicy=allow-all \
        DefaultTTL=3600 \
        MaxTTL=86400
```

#### Cloudflare

1. Add domain to Cloudflare
2. Configure cache rules
3. Enable auto-minify
4. Set up page rules

---

## Monitoring and Logging

### CloudWatch (AWS)

```bash
# Install CloudWatch agent
sudo apt install amazon-cloudwatch-agent

# Configure agent
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
    -a fetch-config \
    -m ec2 \
    -s \
    -c file:///opt/aws/amazon-cloudwatch-agent/etc/config.json
```

### Prometheus + Grafana

#### Prometheus Configuration

```yaml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'coprod-ai'
    static_configs:
      - targets: ['localhost:80']
```

#### Grafana Dashboard

Import pre-configured dashboards for:
- PHP-FPM metrics
- MySQL metrics
- Apache/Nginx metrics
- Application metrics

### Error Tracking (Sentry)

```php
// config/sentry.php
return [
    'dsn' => env('SENTRY_DSN'),
    'environment' => env('ENVIRONMENT', 'production'),
    'traces_sample_rate' => 0.1
];
```

---

## Backup Strategy

### Automated Backups

#### Database Backups

```bash
#!/bin/bash
# Daily backup script
DATE=$(date +%Y%m%d)
BACKUP_DIR="/backups/mysql"

mysqldump -u root -p coprod_ai | gzip > $BACKUP_DIR/coprod_ai_$DATE.sql.gz

# Upload to S3
aws s3 cp $BACKUP_DIR/coprod_ai_$DATE.sql.gz s3://your-backup-bucket/
```

#### File Backups

```bash
#!/bin/bash
# Storage backup script
DATE=$(date +%Y%m%d)
BACKUP_DIR="/backups/storage"

tar -czf $BACKUP_DIR/storage_$DATE.tar.gz /var/www/coprod-ai/storage

# Upload to S3
aws s3 cp $BACKUP_DIR/storage_$DATE.tar.gz s3://your-backup-bucket/
```

### Disaster Recovery

1. **Database Recovery**
   ```bash
   # Restore from backup
   gunzip < coprod_ai_20240612.sql.gz | mysql -u root -p coprod_ai
   ```

2. **File Recovery**
   ```bash
   # Restore storage
   tar -xzf storage_20240612.tar.gz -C /var/www/coprod-ai/
   ```

---

## Scaling Strategy

### Horizontal Scaling

#### Auto-scaling Groups (AWS)

```bash
# Create launch template
aws ec2 create-launch-template \
    --launch-template-name coprod-ai-template \
    --launch-data file://launch-data.json

# Create auto-scaling group
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name coprod-ai-asg \
    --launch-template LaunchTemplateName=coprod-ai-template \
    --min-size 2 \
    --max-size 10 \
    --desired-capacity 2
```

#### Kubernetes Horizontal Pod Autoscaler

```yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: coprod-ai-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: coprod-ai
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
```

### Vertical Scaling

- Increase instance size during peak hours
- Use AWS Auto Scaling for vertical scaling
- Monitor CPU and memory usage

---

## Security Hardening

### Firewall Configuration

```bash
# UFW (Ubuntu)
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

# AWS Security Groups
# Allow only necessary ports
# Restrict SSH access to specific IPs
```

### Fail2Ban Configuration

```bash
# Install Fail2Ban
sudo apt install fail2ban

# Configure jail.local
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5

[apache-auth]
enabled = true
port = http,https
logpath = /var/log/apache2/error.log
```

### Intrusion Detection

```bash
# Install OSSEC
sudo apt install ossec-hids-server

# Configure rules
# Monitor file integrity
# Detect rootkit attempts
```

---

## Performance Optimization

### Database Optimization

```sql
-- Add indexes for common queries
CREATE INDEX idx_user_generation_type_status ON generations(user_id, generation_type, status);
CREATE INDEX idx_projects_user_status ON projects(user_id, status);

-- Optimize tables
OPTIMIZE TABLE generations;
OPTIMIZE TABLE projects;
OPTIMIZE TABLE users;
```

### PHP OPcache

```ini
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
```

### HTTP/2

Enable HTTP/2 in Apache:

```apache
Protocols h2 h2c http/1.1
```

Enable HTTP/2 in Nginx:

```nginx
listen 443 ssl http2;
```

---

## CI/CD Pipeline

### GitHub Actions

Create `.github/workflows/deploy.yml`:

```yaml
name: Deploy to Production

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v2
    
    - name: Deploy to Server
      uses: appleboy/ssh-action@master
      with:
        host: ${{ secrets.HOST }}
        username: ${{ secrets.USERNAME }}
        key: ${{ secrets.SSH_KEY }}
        script: |
          cd /var/www/coprod-ai
          git pull origin main
          composer install --no-dev
          php artisan migrate
          php artisan cache:clear
          sudo systemctl restart apache2
```

### GitLab CI

Create `.gitlab-ci.yml`:

```yaml
stages:
  - build
  - test
  - deploy

build:
  stage: build
  script:
    - composer install
    - npm install
  artifacts:
    paths:
      - vendor/
      - node_modules/

deploy:
  stage: deploy
  script:
    - ssh user@server "cd /var/www/coprod-ai && git pull"
    - ssh user@server "cd /var/www/coprod-ai && composer install --no-dev"
    - ssh user@server "cd /var/www/coprod-ai && php artisan migrate"
  only:
    - main
```

---

## Health Checks

### Health Check Endpoint

Create `health.php`:

```php
<?php
header('Content-Type: application/json');

$checks = [
    'database' => checkDatabase(),
    'redis' => checkRedis(),
    'storage' => checkStorage(),
    'cache' => checkCache()
];

$allHealthy = array_reduce($checks, function($carry, $item) {
    return $carry && $item['status'] === 'ok';
}, true);

http_response_code($allHealthy ? 200 : 503);
echo json_encode([
    'status' => $allHealthy ? 'healthy' : 'unhealthy',
    'checks' => $checks,
    'timestamp' => time()
]);
```

### Load Balancer Health Check

Configure health check endpoint:
- URL: `/health.php`
- Interval: 30 seconds
- Timeout: 5 seconds
- Healthy threshold: 2
- Unhealthy threshold: 3

---

## Rollback Strategy

### Database Rollback

```bash
# Restore previous database state
mysql -u root -p coprod_ai < backup/coprod_ai_previous.sql
```

### Application Rollback

```bash
# Revert to previous commit
git checkout previous-commit-hash
composer install
php artisan migrate:rollback
```

### Blue-Green Deployment

1. Deploy new version to green environment
2. Test green environment thoroughly
3. Switch traffic from blue to green
4. Keep blue as rollback option
5. Update blue to new version after successful deployment

---

## Post-Deployment Checklist

- [ ] Application is accessible via HTTPS
- [ ] Database connection is working
- [ ] Redis is connected (if configured)
- [ ] File uploads are working
- [ ] Email sending is configured
- [ ] Stripe payments are working (if applicable)
- [ ] WebSocket connections are established
- [ ] Cron jobs are scheduled
- [ ] Backups are running
- [ ] Monitoring is configured
- [ ] Error logging is active
- [ ] SSL certificate is valid
- [ ] Load balancer is distributing traffic
- [ ] Auto-scaling is configured
- [ ] Security headers are set
- [ ] Rate limiting is enabled
- [ ] Firewall rules are correct

---

## Troubleshooting Deployment Issues

### 502 Bad Gateway

**Possible Causes:**
- Web server not running
- PHP-FPM not running
- Database connection failed

**Solutions:**
```bash
# Check Apache/Nginx status
sudo systemctl status apache2

# Check PHP-FPM
sudo systemctl status php8.3-fpm

# Restart services
sudo systemctl restart apache2
sudo systemctl restart php8.3-fpm
```

### Database Connection Timeout

**Possible Causes:**
- Database server not accessible
- Security group blocking connection
- Wrong credentials

**Solutions:**
- Verify database server is running
- Check security group allows connection
- Verify credentials in config
- Test connection from application server

### High Memory Usage

**Possible Causes:**
- Memory leak in application
- Insufficient server resources
- Large file uploads

**Solutions:**
- Monitor memory usage with tools
- Increase server RAM
- Implement memory limits in PHP
- Optimize database queries

---

## Support

For deployment support:
- Documentation: https://docs.coprod.ai/deployment
- Issues: https://github.com/your-org/coprod-ai/issues
- Email: support@coprod.ai

---

Deployment Guide version: 1.0.0
Last updated: June 2026
