# 🚀 Guide de Déploiement en Production

## Microservice de Recherche Intelligente

Ce guide vous accompagne pour déployer le microservice de recherche intelligente en production de manière sécurisée et optimisée.

---

## 📋 Prérequis

### Serveur de Production
- **OS**: Ubuntu 20.04+ / Debian 11+ / CentOS 8+
- **RAM**: Minimum 2GB (recommandé 4GB+)
- **CPU**: Minimum 2 cores
- **Stockage**: 10GB+ d'espace libre
- **PHP**: 8.3+
- **Composer**: 2.x
- **Serveur Web**: Nginx ou Apache

### Services Externes
- **Clé OpenAI**: API Key valide
- **API Principale**: Accessible depuis le serveur de production
- **DNS**: Domaine configuré (cours2facu.varascundo.com)

---

## 🔧 Configuration Rapide

### 1. Cloner le Projet
```bash
git clone https://votre-repo.git /var/www/search-microservice
cd /var/www/search-microservice
```

### 2. Configuration de l'Environnement
```bash
# Copier le fichier de configuration
cp .env.prod .env

# Éditer la configuration
nano .env
```

**Variables obligatoires à modifier:**
```bash
# Remplacez par votre vraie clé OpenAI
OPENAI_API_KEY=sk-proj-votre-vraie-cle-openai

# URL de votre API (ajustez si nécessaire)
MAIN_API_BASE_URL=https://cours2facu.varascundo.com/api

# Domaine autorisé pour CORS
CORS_ALLOW_ORIGIN='^https?://(cours2facu\.varascundo\.com)(:[0-9]+)?$'
```

### 3. Déploiement Automatique
```bash
# Rendre le script exécutable
chmod +x deploy.sh

# Lancer le déploiement
sudo ./deploy.sh
```

---

## 🐳 Déploiement avec Docker

### Option 1: Docker Compose (Recommandé)
```bash
# Construire et démarrer
docker-compose -f docker-compose.prod.yml up -d

# Vérifier le statut
docker-compose -f docker-compose.prod.yml ps
```

### Option 2: Docker simple
```bash
# Construire l'image
docker build -f Dockerfile.prod -t search-microservice:prod .

# Lancer le conteneur
docker run -d \
  --name search-microservice \
  -p 8003:8003 \
  --env-file .env.prod \
  search-microservice:prod
```

---

## 🔒 Configuration Nginx (Reverse Proxy)

### Fichier de Configuration
Créez `/etc/nginx/sites-available/search-microservice`:

```nginx
server {
    listen 80;
    server_name search.cours2facu.varascundo.com;
    
    # Redirection HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name search.cours2facu.varascundo.com;
    
    # Configuration SSL
    ssl_certificate /etc/ssl/certs/search.cours2facu.varascundo.com.crt;
    ssl_certificate_key /etc/ssl/private/search.cours2facu.varascundo.com.key;
    
    # Sécurité SSL
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;
    
    # Headers de sécurité
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    location / {
        proxy_pass http://localhost:8003;
        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;
        
        # Timeout configuration
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # Health check endpoint
    location /health {
        proxy_pass http://localhost:8003/api/search/health;
        access_log off;
    }
}
```

### Activation de la Configuration
```bash
# Créer le lien symbolique
sudo ln -s /etc/nginx/sites-available/search-microservice /etc/nginx/sites-enabled/

# Tester la configuration
sudo nginx -t

# Redémarrer Nginx
sudo systemctl reload nginx
```

---

## 📊 Monitoring et Supervision

### 1. Service Systemd
Créez `/etc/systemd/system/search-microservice.service`:

```ini
[Unit]
Description=Search Microservice
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
User=www-data
WorkingDirectory=/var/www/search-microservice
ExecStart=/usr/bin/php -S 0.0.0.0:8003 -t public
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=search-microservice

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

```bash
# Activer et démarrer le service
sudo systemctl enable search-microservice
sudo systemctl start search-microservice
sudo systemctl status search-microservice
```

### 2. Surveillance des Logs
```bash
# Logs du microservice
tail -f /var/log/search-microservice*.log

# Logs Nginx
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

# Logs système
journalctl -u search-microservice -f
```

### 3. Tests de Santé
```bash
# Test de l'endpoint de santé
curl https://search.cours2facu.varascundo.com/health

# Test de recherche
curl -X POST https://search.cours2facu.varascundo.com/api/search/intelligent \
  -H "Content-Type: application/json" \
  -d '{"query": "html div", "limit": 5}'
```

---

## 🔐 Sécurité

### 1. Certificats SSL
```bash
# Avec Let's Encrypt (Certbot)
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d search.cours2facu.varascundo.com
```

### 2. Firewall
```bash
# Configuration UFW
sudo ufw allow ssh
sudo ufw allow 'Nginx Full'
sudo ufw enable
```

### 3. Mise à Jour des Dépendances
```bash
# Mise à jour régulière
composer update --no-dev
php bin/console cache:clear --env=prod
```

---

## 📈 Optimisations de Performance

### 1. Configuration PHP
Éditez `/etc/php/8.3/fpm/php.ini`:
```ini
memory_limit = 512M
max_execution_time = 60
opcache.enable = 1
opcache.memory_consumption = 256
opcache.max_accelerated_files = 20000
```

### 2. Configuration Redis (Cache)
```bash
# Installation Redis
sudo apt install redis-server

# Configuration dans .env
CACHE_ENABLED=true
CACHE_TTL=3600
```

### 3. Optimisation Symfony
```bash
# Pré-compilation des templates
php bin/console cache:warmup --env=prod

# Optimisation de l'autoloader
composer dump-autoload --optimize --no-dev
```

---

## 🚨 Résolution de Problèmes

### Problèmes Courants

**1. Service ne démarre pas**
```bash
# Vérifier les logs
sudo systemctl status search-microservice
journalctl -u search-microservice --no-pager -l

# Vérifier la configuration
php bin/console about --env=prod
```

**2. Erreur OpenAI**
```bash
# Vérifier la clé API
curl -H "Authorization: Bearer $OPENAI_API_KEY" https://api.openai.com/v1/models

# Tester la connectivité
php bin/console search:debug
```

**3. Problèmes CORS**
```bash
# Tester les headers CORS
curl -I -X OPTIONS https://search.cours2facu.varascundo.com/api/search/intelligent
```

**4. Performance lente**
```bash
# Profiler les requêtes
php bin/console debug:container --env=prod
php bin/console cache:pool:clear cache.app
```

---

## 📝 Checklist de Déploiement

- [ ] ✅ Variables d'environnement configurées
- [ ] ✅ Clé OpenAI valide
- [ ] ✅ URL API principale accessible
- [ ] ✅ CORS configuré
- [ ] ✅ SSL/TLS configuré
- [ ] ✅ Nginx configuré
- [ ] ✅ Service systemd activé
- [ ] ✅ Monitoring en place
- [ ] ✅ Sauvegardes configurées
- [ ] ✅ Tests de santé passants

---

## 📞 Support

En cas de problème:
1. Consultez les logs détaillés
2. Vérifiez la checklist ci-dessus
3. Testez l'endpoint de santé
4. Contactez l'équipe de développement

**URL de Test Final**: https://search.cours2facu.varascundo.com/health