# Deployment Guide

## Production Deployment

### Prerequisites
- Ubuntu 22.04 LTS server
- PostgreSQL 15+
- Redis
- Nginx
- Python 3.9+

### Steps

1. **Install Dependencies**
```bash
sudo apt update
sudo apt install python3-pip python3-venv postgresql postgresql-contrib redis-server nginx
```

2. **Setup PostgreSQL**
```bash
sudo -u postgres psql
CREATE DATABASE daleeli_db;
CREATE USER daleeli_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE daleeli_db TO daleeli_user;
\q
```

3. **Setup Project**
```bash
cd /var/www
git clone <your-repo> daleeli-backend
cd daleeli-backend/backend
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```

4. **Configure Environment**
```bash
cp .env.example .env
# Edit .env with production settings
```

5. **Run Migrations**
```bash
python manage.py migrate
python manage.py collectstatic --noinput
```

6. **Create Superuser**
```bash
python manage.py createsuperuser
```

7. **Setup Gunicorn**
```bash
pip install gunicorn
```

Create `/etc/systemd/system/daleeli-backend.service`:
```ini
[Unit]
Description=Daleeli IQ Backend
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/daleeli-backend/backend
Environment="PATH=/var/www/daleeli-backend/backend/venv/bin"
ExecStart=/var/www/daleeli-backend/backend/venv/bin/gunicorn --workers 3 --bind unix:/var/www/daleeli-backend/backend/daleeli.sock config.wsgi:application

[Install]
WantedBy=multi-user.target
```

8. **Setup Nginx**
Create `/etc/nginx/sites-available/daleeli-backend`:
```nginx
server {
    listen 80;
    server_name your-domain.com;

    location / {
        include proxy_params;
        proxy_pass http://unix:/var/www/daleeli-backend/backend/daleeli.sock;
    }

    location /static/ {
        alias /var/www/daleeli-backend/backend/staticfiles/;
    }

    location /media/ {
        alias /var/www/daleeli-backend/backend/media/;
    }
}
```

9. **Enable Services**
```bash
sudo systemctl enable daleeli-backend
sudo systemctl start daleeli-backend
sudo ln -s /etc/nginx/sites-available/daleeli-backend /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

10. **Setup SSL (Let's Encrypt)**
```bash
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com
```

11. **Setup Celery**
Create `/etc/systemd/system/daleeli-celery.service`:
```ini
[Unit]
Description=Daleeli IQ Celery Worker
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/daleeli-backend/backend
Environment="PATH=/var/www/daleeli-backend/backend/venv/bin"
ExecStart=/var/www/daleeli-backend/backend/venv/bin/celery -A config worker --loglevel=info

[Install]
WantedBy=multi-user.target
```

```bash
sudo systemctl enable daleeli-celery
sudo systemctl start daleeli-celery
```

## Monitoring

- Check logs: `journalctl -u daleeli-backend -f`
- Check Celery: `journalctl -u daleeli-celery -f`
- Check Nginx: `sudo tail -f /var/log/nginx/error.log`

