#!/bin/bash
# Generate docker-compose.multi-tenant.yml from tenants/ directory
#
# Usage:
#   ./scripts/generate-compose.sh > docker-compose.multi-tenant.yml
#   docker compose -f docker-compose.multi-tenant.yml up -d

set -e

TENANTS_DIR="tenants"
VERSION="${ZEPTOCLAW_VERSION:-0.1.0}"
ENV="${ZEPTOCLAW_ENV:-production}"

if [ ! -d "$TENANTS_DIR" ] || [ -z "$(ls -A "$TENANTS_DIR" 2>/dev/null)" ]; then
    echo "Error: No tenants found in $TENANTS_DIR/" >&2
    echo "Run ./scripts/add-tenant.sh first" >&2
    exit 1
fi

cat << 'HEADER'
# Auto-generated by scripts/generate-compose.sh
# Regenerate with: ./scripts/generate-compose.sh > docker-compose.multi-tenant.yml

x-zeptoclaw-defaults: &defaults
  image: zeptoclaw:latest
  restart: unless-stopped
  logging:
    driver: json-file
    options:
      max-size: "10m"
      max-file: "3"
  deploy:
    resources:
      limits:
        memory: 128M
        cpus: "0.25"
      reservations:
        memory: 32M
        cpus: "0.05"

services:
HEADER

count=0
for dir in "$TENANTS_DIR"/*/; do
    [ -d "$dir" ] || continue
    name=$(basename "$dir")

    if [ ! -f "$dir/config.json" ]; then
        echo "Warning: $dir/config.json not found, skipping" >&2
        continue
    fi

    cat << EOF
  tenant-$name:
    <<: *defaults
    container_name: zc-$name
    volumes:
      - ${name}-data:/data
      - ./tenants/$name/config.json:/data/config.json:ro
    environment:
      - RUST_LOG=zeptoclaw=info
      - RUST_LOG_FORMAT=json
      - ZEPTOCLAW_HEALTH_PORT=9090
    labels:
      com.zeptoclaw.tenant: $name
      com.zeptoclaw.version: "$VERSION"
      com.zeptoclaw.env: "$ENV"
    healthcheck:
      test: ["CMD-SHELL", "wget -qO- http://localhost:9090/healthz || exit 1"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s
    command: ["zeptoclaw", "gateway"]

EOF
    count=$((count + 1))
done

echo "volumes:"
for dir in "$TENANTS_DIR"/*/; do
    [ -d "$dir" ] || continue
    name=$(basename "$dir")
    [ -f "$dir/config.json" ] || continue
    echo "  ${name}-data:"
done

echo "Generated compose file with $count tenant(s)" >&2
