# docker-compose.dev.yml — Dev testability stack (no custom Dockerfile)
#
# Usage (from repo root):
#   docker compose -f packaging/docker/docker-compose.dev.yml up
#
# Then open the printed Web UI URL — already wired to headless, no config needed.
#
# Env overrides (optional, via .env or export):
#   OPENWORK_TOKEN        — shared client token (auto-generated if unset)
#   OPENWORK_HOST_TOKEN   — host/admin token (auto-generated if unset)
#   OPENWORK_WORKSPACE    — host path to mount as workspace (default: ./workspace)
#   OPENWORK_PORT         — host port to map to container :8787 (default: 8787)
#   WEB_PORT              — host port to map to container :5173 (default: 5173)
#   OPENWORK_DEV_ID       — unique ID for this stack (default: default)
#   OPENWORK_DEV_MODE     — enables isolated OpenCode dev state
#   OPENWORK_PUBLIC_HOST  — browser-facing host/IP for LAN-accessible URLs
#   OPENWORK_DOCKER_DEV_MOUNT_HOST_OPENCODE=1 — import host OpenCode config/auth into the isolated dev state
#   OPENWORK_OPENCODE_CONFIG_DIR      — host OpenCode config dir detection override
#   OPENWORK_OPENCODE_DATA_DIR        — host OpenCode data dir detection override
#   OPENWORK_HOST_OPENCODE_CONFIG_DIR — import source for OpenCode config
#   OPENWORK_HOST_OPENCODE_DATA_DIR   — import source for OpenCode auth/data

x-shared: &shared
  image: node:22-bookworm-slim
  working_dir: /app
  volumes:
    # Mount the entire repo so both services share node_modules + source
    - ../../:/app
    - pnpm-store:/root/.local/share/pnpm/store
    - bun-install:/root/.bun
    - ${OPENWORK_WORKSPACE:-./workspace}:/workspace
    - ${OPENWORK_HOST_OPENCODE_CONFIG_DIR:-./workspace/.openwork-host-opencode-config}:/persist/.config/opencode:ro
    - ${OPENWORK_HOST_OPENCODE_DATA_DIR:-./workspace/.openwork-host-opencode-data}:/persist/.openwork-host-opencode-data:ro

services:
  openwork-server:
    <<: *shared
    entrypoint: ["/bin/sh", "-c"]
    command:
      - |
        set -e

        # --- Ensure workspace dir is writable ---
        mkdir -p /workspace && touch /workspace/.keep 2>/dev/null || true

        # --- Install system deps ---
        apt-get update -qq && apt-get install -y -qq --no-install-recommends \
          curl ca-certificates unzip git >/dev/null 2>&1

        # --- Install bun (cached in named volume) ---
        export BUN_INSTALL="/root/.bun"
        export PATH="$$BUN_INSTALL/bin:$$PATH"
        if ! command -v bun >/dev/null 2>&1; then
          echo "[openwork-server] Installing bun..."
          curl -fsSL https://bun.sh/install | bash
        fi

        # --- Enable pnpm via corepack ---
        corepack enable && corepack prepare pnpm@10.27.0 --activate

        # --- Install deps ---
        echo "[openwork-server] Installing dependencies..."
        pnpm install --no-frozen-lockfile --network-concurrency 1 --child-concurrency 1

        # --- Build the server plugins and install the pinned OpenCode binary ---
        pnpm --filter openwork-server build
        OPENCODE_VERSION=$$(node -e 'const fs=require("fs"); const parsed=JSON.parse(fs.readFileSync("/app/constants.json", "utf8")); process.stdout.write(String(parsed.opencodeVersion || "").trim().replace(/^v/, ""));')
        export OPENCODE_INSTALL_DIR="/root/.opencode/bin"
        mkdir -p "$$OPENCODE_INSTALL_DIR"
        if ! command -v opencode >/dev/null 2>&1; then
          curl -fsSL https://opencode.ai/install | bash -s -- --version "$$OPENCODE_VERSION" --no-modify-path
        fi
        export PATH="$$OPENCODE_INSTALL_DIR:$$PATH"
        export OPENWORK_MANAGE_OPENCODE=1
        export OPENWORK_OPENCODE_BIN="$$(command -v opencode)"
        export OPENWORK_EXTENSIONS_PLUGIN_DIR="/app/apps/server/dist/opencode-plugins"

        # --- Resolve tokens ---
        if [ -z "$$OPENWORK_TOKEN" ]; then
          OPENWORK_TOKEN=$$(cat /proc/sys/kernel/random/uuid)
          export OPENWORK_TOKEN
        fi
        if [ -z "$$OPENWORK_HOST_TOKEN" ]; then
          OPENWORK_HOST_TOKEN=$$(cat /proc/sys/kernel/random/uuid)
          export OPENWORK_HOST_TOKEN
        fi

        # Write tokens so the web service can source them
        mkdir -p /app/tmp
        printf 'OPENWORK_TOKEN=%s\nOPENWORK_HOST_TOKEN=%s\n' \
          "$$OPENWORK_TOKEN" "$$OPENWORK_HOST_TOKEN" > "/app/tmp/.dev-env-${OPENWORK_DEV_ID:-default}"

        echo ""
        echo "============================================"
        echo "  OpenWork server"
        echo "  Server:     http://localhost:${OPENWORK_PORT:-8787}"
        echo "  Health:     http://localhost:${OPENWORK_PORT:-8787}/health"
        echo "  Token:      $$OPENWORK_TOKEN"
        echo "  Host token: $$OPENWORK_HOST_TOKEN"
        echo "============================================"
        echo ""

        exec pnpm --filter openwork-server exec bun dist/cli.js \
          --workspace /workspace \
          --host 0.0.0.0 \
          --port 8787 \
          --token "$$OPENWORK_TOKEN" \
          --host-token "$$OPENWORK_HOST_TOKEN" \
          --approval auto \
          --cors "*" \
          --verbose
    ports:
      - "${OPENWORK_PORT:-8787}:8787"
    healthcheck:
      test: ["CMD-SHELL", "curl -sf http://localhost:8787/health || exit 1"]
      interval: 5s
      timeout: 5s
      retries: 30
      start_period: 90s
    environment:
      CI: "true"
      OPENWORK_TOKEN: ${OPENWORK_TOKEN:-}
      OPENWORK_HOST_TOKEN: ${OPENWORK_HOST_TOKEN:-}
      OPENWORK_DEV_ID: ${OPENWORK_DEV_ID:-default}
      OPENWORK_DEV_MODE: ${OPENWORK_DEV_MODE:-1}
      OPENWORK_DEV_OPENCODE_IMPORT_CONFIG_DIR: /persist/.config/opencode
      OPENWORK_DEV_OPENCODE_IMPORT_DATA_DIR: /persist/.openwork-host-opencode-data

  web:
    <<: *shared
    depends_on:
      openwork-server:
        condition: service_healthy
    entrypoint: ["/bin/sh", "-c"]
    command:
      - |
        set -e

        # --- Install system deps ---
        apt-get update -qq && apt-get install -y -qq --no-install-recommends \
          curl ca-certificates >/dev/null 2>&1

        # --- Bun + pnpm ---
        export BUN_INSTALL="/root/.bun"
        export PATH="$$BUN_INSTALL/bin:$$PATH"
        if ! command -v bun >/dev/null 2>&1; then
          curl -fsSL https://bun.sh/install | bash
        fi
        corepack enable && corepack prepare pnpm@10.27.0 --activate

        # --- Read token written by openwork-server ---
        if [ -f "/app/tmp/.dev-env-${OPENWORK_DEV_ID:-default}" ]; then
          . "/app/tmp/.dev-env-${OPENWORK_DEV_ID:-default}"
          export VITE_OPENWORK_TOKEN="$$OPENWORK_TOKEN"
        fi

        echo ""
        echo "============================================"
        echo "  OpenWork web UI"
        echo "  URL:   http://localhost:${WEB_PORT:-5173}"
          echo "  Token: $${VITE_OPENWORK_TOKEN:-<see openwork-server logs>}"
        echo "============================================"
        echo ""

        export VITE_OPENWORK_URL="http://${OPENWORK_PUBLIC_HOST:-localhost}:${OPENWORK_PORT:-8787}"
        export VITE_OPENWORK_PORT="${OPENWORK_PORT:-8787}"
        export VITE_ALLOWED_HOSTS="all"
        export HOST="0.0.0.0"
        export PORT="5173"

        exec pnpm --filter @openwork/app exec vite \
          --host 0.0.0.0 \
          --port 5173 \
          --strictPort
    ports:
      - "${WEB_PORT:-5173}:5173"
    environment:
      OPENWORK_DEV_ID: ${OPENWORK_DEV_ID:-default}

volumes:
  pnpm-store:
    name: openwork-dev-pnpm-store
  bun-install:
    name: openwork-dev-bun-install
