# Deploying HomeBuddy API to the VPS

Stack: Docker Compose runs PostgreSQL 16 + Redis (WebSocket channel layer) + Django (Gunicorn, ASGI) on `127.0.0.1:8002`. Redis is required for realtime with more than one worker.
The host's existing Caddy terminates HTTPS, proxies to it, and serves `/media` from disk.

Ports already in use on the VPS (don't touch): 8000 (ludo), 8001 (portfolio), 2019 (Caddy admin), 80/443 (Caddy).

## 1. DNS

Add an **A record** for `homebuddyai` on `amritduwal.com.np` → VPS IP.

## 2. Get the code

```bash
sudo mkdir -p /opt/homebuddy-api && sudo chown $USER /opt/homebuddy-api
git clone <your-api-repo-url> /opt/homebuddy-api
cd /opt/homebuddy-api
mkdir -p media logs
```

## 3. Configure

```bash
cp .env.vps.example .env
python3 -c "import secrets; print(secrets.token_urlsafe(50))"   # paste as SECRET_KEY
nano .env    # set ALLOWED_HOSTS, CSRF_TRUSTED_ORIGINS, POSTGRES_PASSWORD
```

## 4. Start the app

```bash
docker compose up -d --build
docker compose exec web python manage.py createsuperuser
curl -H "Host: homebuddyai.amritduwal.com.np" http://127.0.0.1:8002/api/health/
```

Migrations and `collectstatic` run automatically whenever the `web` container starts.

Optional YOLO object detection (adds ~1 GB, fine with 7.8 GB RAM):
`docker compose build --build-arg INSTALL_ML=1 && docker compose up -d`

## 5. Hook up Caddy

The VPS Caddyfile is just `import sites/*.caddy`, with one file per site. Add HomeBuddy's:

```bash
sudo cp /opt/homebuddy-api/deploy/Caddyfile.snippet /etc/caddy/sites/homebuddyai.caddy
```

Then:

```bash
sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
curl https://homebuddyai.amritduwal.com.np/api/health/
```

## 6. Point the Flutter app at it

Change `_defaultHost` in `homebuddyai/lib/core/config/api_config.dart`, or build with:

```bash
flutter build apk --dart-define=HOME_BUDDY_API_BASE_URL=https://homebuddyai.amritduwal.com.np
```

## Updating

```bash
cd /opt/homebuddy-api && git pull && docker compose up -d --build
```

## Moving existing data (optional)

Media: copy the old `media/` folder contents into `/opt/homebuddy-api/media/`.

Database from the old cPanel Postgres:

```bash
pg_dump -h OLD_HOST -U OLD_USER -Fc OLD_DB > homebuddy.dump      # on old server
docker compose exec -T db pg_restore -U homebuddy -d homebuddy --clean --no-owner < homebuddy.dump
```

## Useful commands

```bash
docker compose logs -f web
docker compose ps
docker compose restart web
docker compose exec db pg_dump -U homebuddy homebuddy > backup_$(date +%F).sql
```

## Notes

- The VPS has no swap. If you enable YOLO, consider adding a 2–4 GB swapfile.
- ufw is inactive. Ports are bound to 127.0.0.1 so the app isn't exposed directly;
  if you enable ufw, allow OpenSSH, 80 and 443 first.
