services:
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-govcrawler}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-govcrawler}
      POSTGRES_DB: ${POSTGRES_DB:-govcrawler}
    ports: ["5433:5432"]
    volumes: ["./data/pg:/var/lib/postgresql/data"]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-govcrawler}"]
      interval: 5s
      timeout: 3s
      retries: 10

  valkey:
    # BSD-3 licensed Redis 7.2 fork — replaces Redis (SSPL) for commercial use
    image: valkey/valkey:8-alpine
    command: ["valkey-server", "--appendonly", "no", "--save", ""]
    ports: ["6380:6379"]
    volumes: ["./data/valkey:/data"]
    healthcheck:
      test: ["CMD", "valkey-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 10

  scheduler:
    build: .
    depends_on:
      db: { condition: service_healthy }
      valkey: { condition: service_healthy }
    environment:
      DB_URL: ${DB_URL:-postgresql+psycopg://govcrawler:govcrawler@db:5432/govcrawler}
      DATA_DIR: /data/govcrawler
      USER_AGENT: "${USER_AGENT:-GovCrawlerBot/1.0 (+contact: ops@example.com)}"
      VALKEY_URL: redis://valkey:6379/0
      TZ: Asia/Shanghai
    volumes:
      - ./data/govcrawler:/data/govcrawler
      - ./config:/app/config:ro
    restart: unless-stopped
    # DEP-03 防浏览器内存泄漏 — Docker-level auto-restart + app-level watchdog in scheduler.py
    command: ["python", "-m", "govcrawler", "schedule"]
    healthcheck:
      test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
      interval: 60s
      timeout: 10s
      retries: 3

  api:
    build: .
    depends_on:
      db: { condition: service_healthy }
    environment:
      DB_URL: ${DB_URL:-postgresql+psycopg://govcrawler:govcrawler@db:5432/govcrawler}
      DATA_DIR: /data/govcrawler
      USER_AGENT: "${USER_AGENT:-GovCrawlerBot/1.0 (+contact: ops@example.com)}"
      TZ: Asia/Shanghai
    volumes:
      - ./data/govcrawler:/data/govcrawler:ro
    ports: ["8787:8787"]
    restart: unless-stopped
    command: ["python", "-m", "govcrawler", "serve", "--host", "0.0.0.0", "--port", "8787"]
