# Installation et Deploiement - Smart Calendar

## 1. Prerequis
- Node.js 20+
- Un compte Google Cloud (OAuth)
- Un compte Microsoft Entra ID (OAuth)
- Une cle OpenAI active
- Un hebergement o2switch avec acces cPanel
- Un nom de domaine ou sous-domaine configure sur o2switch
- Acces SSH recommande (plus fiable que le terminal web cPanel pour `npm`)

## 2. Installation locale

### 2.1 Installer dependances
```bash
npm install
```

### 2.2 Configurer l'environnement
Copier [.env.example](.env.example) vers `.env.local` puis renseigner:

- `OPENAI_API_KEY`
- `OPENAI_INTENT_MODEL` (par defaut `gpt-4o-mini`)
- `OPENAI_TRANSCRIBE_MODEL` (par defaut `gpt-4o-mini-transcribe`)
- `OPENAI_CONTEXT_MODEL` (par defaut `gpt-4o-mini`)
- `NEXTAUTH_URL` (local: `http://localhost:3000`)
- `NEXTAUTH_SECRET` (chaine longue aleatoire)
- `MS_CLIENT_ID`
- `MS_CLIENT_SECRET`
- `GOOGLE_CLIENT_ID`
- `GOOGLE_CLIENT_SECRET`
- `CONTEXT_MAX_UPLOAD_BYTES` (optionnel, par defaut `8388608`)

### 2.3 Lancer
```bash
npm run dev
```

### 2.4 Verifier
- UI: `http://localhost:3000`
- API context upload: `POST /api/context`
- API intent: `POST /api/intent`
- API planning: `POST /api/work-plan`

## 3. Configuration OAuth

## 3.1 Google OAuth
- Type: Web application
- Redirect URI locale: `http://localhost:3000/api/auth/callback/google`
- Redirect URI prod: `https://VOTRE_DOMAINE/api/auth/callback/google`
- Scopes: 
  - `openid`
  - `email`
  - `profile`
  - `https://www.googleapis.com/auth/calendar`
  - `https://www.googleapis.com/auth/calendar.events`

## 3.2 Microsoft OAuth (Entra ID)
- Redirect URI locale: `http://localhost:3000/api/auth/callback/azure-ad`
- Redirect URI prod: `https://VOTRE_DOMAINE/api/auth/callback/azure-ad`
- Permissions Graph:
  - `Calendars.ReadWrite`
  - `User.Read`
  - `offline_access`
  - `openid`
  - `profile`
  - `email`
- Donner le consentement admin si necessaire.

## 4. Deploiement o2switch (cPanel Setup Node.js App)

Reference officielle o2switch:
- `https://faq.o2switch.fr/cpanel/logiciels/hebergement-nodejs-multi-version`

## 4.1 Preparer le projet avant envoi
Depuis votre machine locale:

```bash
npm install
npm run test:unit
npm run build
```

Puis envoyez le projet vers o2switch (FTP, Git ou SSH) dans un dossier dedie, par exemple:
- `~/smart-calendar-app`

Important:
- Ne pas envoyer `node_modules/` et `.next/` depuis Windows, ils seront regeneres sur le serveur.
- Conserver le fichier `server.js` du projet (point d'entree de production pour o2switch).

## 4.2 Creer l'application Node.js dans cPanel
Dans cPanel > `Setup Node.js App` > `Create Application`:

- Node.js version: `20` (ou version stable compatible)
- Application mode: `Production`
- Application root: `smart-calendar-app` (chemin du code)
- Application URL: votre domaine ou sous-domaine cible
- Application startup file: `server.js`
- Passenger log file: exemple `/home/VOTRE_USER/logs/smart-calendar-passenger.log`

Important:
- Le dossier `Application root` ne doit pas etre le document root public du domaine.
- cPanel/Passenger fait automatiquement le lien domaine <-> application.

## 4.3 Installer dependances et builder sur o2switch
Apres creation de l'app, o2switch affiche une commande `source ...`.
Copiez exactement celle donnee dans cPanel (elle depend de votre compte/version Node).

Exemple de sequence en SSH:

```bash
source /home/VOTRE_USER/nodevenv/smart-calendar-app/20/bin/activate
cd ~/smart-calendar-app
npm install
npm run build
```

Important:
- Ne lancez pas `npm run dev` en production.
- Ne lancez pas manuellement `node server.js` en daemon: utilisez `Restart` dans cPanel (Passenger gere le process).

## 4.4 Configurer les variables d'environnement dans cPanel
Dans la page de l'application Node.js, section `Add Variable`, ajoutez:

- `OPENAI_API_KEY`
- `OPENAI_INTENT_MODEL` (defaut `gpt-4o-mini`)
- `OPENAI_TRANSCRIBE_MODEL` (defaut `gpt-4o-mini-transcribe`)
- `OPENAI_CONTEXT_MODEL` (defaut `gpt-4o-mini`)
- `NEXTAUTH_URL` = `https://VOTRE_DOMAINE`
- `NEXTAUTH_SECRET` (chaine forte et stable)
- `MS_CLIENT_ID`
- `MS_CLIENT_SECRET`
- `GOOGLE_CLIENT_ID`
- `GOOGLE_CLIENT_SECRET`
- `CONTEXT_MAX_UPLOAD_BYTES` (optionnel, defaut `8388608`)

Puis cliquez `Save`, ensuite `Restart`.

## 4.5 Mettre a jour les callbacks OAuth en production
Dans Google Cloud Console:
- `https://VOTRE_DOMAINE/api/auth/callback/google`

Dans Microsoft Entra ID:
- `https://VOTRE_DOMAINE/api/auth/callback/azure-ad`

Sans ces URLs exactes, la connexion OAuth echouera en production.

## 4.6 Verifications post-deploiement
- Login Google OK
- Login Microsoft OK
- `POST /api/context` accepte `.md`, `.pdf`, `.docx`, images
- Cas test cadence:
  - prompt: "Planifie 1h par semaine jusque fin avril pour terminer le projet"
  - attendu: `cadence_type=weekly`, `cadence_per_week_target_minutes=60`

## 4.7 Mise a jour d'une version (workflow court)
1. Envoyer les nouveaux fichiers dans `Application root`
2. En SSH: `source ...` puis `cd ~/smart-calendar-app`
3. Si dependencies changent: `npm install`
4. Rebuild: `npm run build`
5. cPanel: `Restart`

## 5. Nettoyage recommande avant mise en prod
Le runtime n'a pas besoin de:
- fichiers de cadrage produit historiques
- prototypes texte non utilises

Conserver:
- code dans `app/`, `lib/`, `types/`
- config (`package.json`, `tsconfig.json`, `next.config.mjs`)
- docs OAuth utiles

## 6. Depannage rapide

## 6.0 Erreurs npm en terminal web cPanel
Si vous voyez des erreurs `out of memory`, `fork failed` ou `wasm memory`:
- utilisez un vrai client SSH plutot que le terminal web cPanel,
- relancez `source ...`, puis `npm install` / `npm run build`.

## 6.1 Application en timeout au demarrage (Passenger)
- Verifier que `Application startup file` = `server.js`
- Verifier que le build existe: `npm run build`
- Verifier les logs Passenger (`Passenger log file` configure dans cPanel)
- Verifier qu'il n'y a qu'un seul serveur HTTP principal (pas de multiple `listen()` concurrents)

## 6.2 Port 3000 occupe en local
```powershell
$conn = Get-NetTCPConnection -LocalPort 3000 -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -ne $conn) { Stop-Process -Id $conn.OwningProcess -Force }
npm run dev
```

## 6.3 Erreur cache Next (.next verrouille)
```powershell
Get-Process -Name node -ErrorAction SilentlyContinue | Stop-Process -Force
if (Test-Path ".next") { Remove-Item ".next" -Recurse -Force }
npm run dev
```

## 6.4 Upload refuse
- Verifier type/taille fichier
- Types supportes: `.txt`, `.md`, `.markdown`, `.pdf`, `.docx`, `.png`, `.jpg`, `.jpeg`, `.webp`
- Ajuster `CONTEXT_MAX_UPLOAD_BYTES` si besoin

## 7. Commandes de validation
```bash
npm run test:unit
npm run build
```
