services:

  db:
    container_name: app_db
    image: "postgres:17-bullseye"
    restart: always
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "7"
    ports:
      - ${AUTOMATION_DB_PORT:-5432}:5432
    environment:
      POSTGRES_PASSWORD: ${AUTOMATION_DB_PASSWORD:-postgres}
      POSTGRES_USER: ${AUTOMATION_DB_USER:-postgres}
      POSTGRES_DB: ${AUTOMATION_DB_NAME:-app_db}
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 3

  opcua_server_simulator:
    container_name: opcua_server_simulator
    restart: always
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "7"
    image: "knowai/opcua_server_simulator:2.2.1"
    ports:
      - 0.0.0.0:5015:5015
      - 0.0.0.0:4840:4840
    environment:
      - APP_THREADS=5
      - APP_PORT=5015
      - ASYNC_APP=0
    healthcheck:
      test: curl --fail -s -k http://0.0.0.0:5015/api/healthcheck/ || exit 1
      interval: 15s
      timeout: 10s
      retries: 5
    volumes:
      - ./opcua_server_simulator.yml:/app/app/config.yml
      - ./data.csv:/app/app/data/data.csv

  automation:
    container_name: "Automation"
    image: "knowai/automation:${AUTOMATION_VERSION:-latest}"
    restart: always
    ports:
      # Backend API (Flask/Gunicorn)
      - ${AUTOMATION_PORT:-8050}:${AUTOMATION_PORT:-8050}
      # HMI frontend served by Nginx inside the container (listen 3000)
      - ${AUTOMATION_HMI_PORT:-3000}:3000
    volumes:
      - automation_db:/app/db
      - automation_logs:/app/logs
    logging:
      driver: "json-file"
      options:
        max-size: "10m" # Rota cuando llega a 10MB
        max-file: "3" # Guarda máximo 3 archivos (30MB total)
    environment:
      AUTOMATION_OPCUA_SERVER_PORT: ${AUTOMATION_OPCUA_SERVER_PORT:-53530}
      AUTOMATION_APP_SECRET_KEY: ${AUTOMATION_APP_SECRET_KEY:-073821603fcc483f9afee3f1500782a4}
      AUTOMATION_SUPERUSER_PASSWORD: ${AUTOMATION_SUPERUSER_PASSWORD:-super_ultra_secret_password}
      AUTOMATION_DB_TYPE: ${AUTOMATION_DB_TYPE:-postgresql}
      AUTOMATION_DB_HOST: ${AUTOMATION_DB_HOST:-127.0.0.1}
      AUTOMATION_DB_PORT: ${AUTOMATION_DB_PORT:-5432}
      AUTOMATION_DB_NAME: ${AUTOMATION_DB_NAME:-app_db}
      AUTOMATION_DB_USER: ${AUTOMATION_DB_USER:-postgres}
      AUTOMATION_DB_PASSWORD: ${AUTOMATION_DB_PASSWORD:-postgres}
    tmpfs:
      - /tmp:size=500k
    depends_on:
      db:
        condition: service_healthy
      opcua_server_simulator:
        condition: service_healthy
    deploy:
      resources:
        limits:
          cpus: "0.5"
          memory: 256M
    healthcheck:
      test: ["CMD", "python", "/app/healthcheck.py"]
      interval: 15s
      timeout: 10s
      retries: 3

volumes:
  automation_db:
  automation_logs:
