# ==============================================================================
# ADTLAS TV ADVERTISING PLATFORM - DOCKER COMPOSE CONFIGURATION
# ==============================================================================
# 
# This Docker Compose file defines the complete infrastructure for the Adtlas
# TV advertising platform, including all necessary services for development
# and production environments.
#
# Services included:
# - Web Application (Django)
# - Database (PostgreSQL)
# - Cache (Redis)
# - Reverse Proxy (Nginx)
# - Monitoring (Prometheus + Grafana)
# - Message Queue (Celery with Redis)
#
# Author: Adtlas Development Team
# Version: 2.0.0
# Last Updated: 2025-01-01
# ==============================================================================

version: '3.3'

# ==============================================================================
# NETWORKS CONFIGURATION
# ==============================================================================
# Define custom networks for service isolation and communication
networks:
  # Frontend network for web-facing services
  frontend:
    driver: bridge
    ipam:
      config:
        - subnet: 172.25.0.0/16
  # Backend network for internal service communication
  backend:
    driver: bridge 
    ipam:
      config:
        - subnet: 172.26.0.0/16
  # Monitoring network for observability services
  monitoring:
    driver: bridge
    ipam:
      config:
        - subnet: 172.27.0.0/16

# ==============================================================================
# VOLUMES CONFIGURATION
# ==============================================================================
# Define persistent volumes for data storage
volumes:  
  postgres_data:
  redis_data:
  static_files:
  media_files:

# ==============================================================================
# SERVICES CONFIGURATION
# ==============================================================================
# Services are the individual containers that make up your application
services:
  # ============================================================================
  # DATABASE SERVICE - PostgreSQL
  # ============================================================================
  # Primary database for storing application data including:
  # - User accounts and authentication
  # - TV channels, networks, and zones data
  # - Advertising campaigns and analytics
  # - Content recognition and targeting data 
  db:
    # Use the latest postgres image from Docker Hub
    image: postgres:15-alpine
    # Assign a specific name to the container
    container_name: adtlas_postgres
    # Always restart the container if it stops
    restart: unless-stopped
    # Environment variables for database configuration
    env_file:
      - src/.env
    environment:
      # Database credentials (use .env file in production)
      POSTGRES_DB: adtlas_db
      POSTGRES_USER: adtlas_user
      POSTGRES_PASSWORD: adtlas_password
    # Volume mounts for data persistence and configuration
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./docker/postgres/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
    # Network configuration
    networks:
      - backend 
    # Health check to ensure database is ready
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U adtlas_user -d adtlas_db"]
      interval: 30s # Health check will run every 30 seconds
      timeout: 10s # Timeout for health check command # If health check command doesn't return within 5 seconds, it's considered a failure
      retries: 5 # Number of retries before declaring container as unhealthy 

  # ============================================================================
  # CACHE SERVICE - Redis
  # ============================================================================
  # High-performance caching layer for:
  # - Session storage
  # - API response caching
  # - Real-time analytics data
  # - Celery message broker
  redis:
    image: redis:7-alpine
    container_name: adtlas_redis
    restart: unless-stopped
    command: >
      redis-server
      --appendonly yes
      --appendfsync everysec
      --maxmemory 512mb
      --maxmemory-policy allkeys-lru
    ports:
      - "6380:6379"
    volumes:
      - redis_data:/data
    # Network configuration
    networks:
      - backend 
    # Health check
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 30s
      timeout: 10s
      retries: 3

  # ============================================================================
  # WEB APPLICATION SERVICE - Django
  # ============================================================================
  # Main Django application serving the Adtlas TV advertising platform
  web:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    container_name: adtlas_web
    restart: unless-stopped
    command: >
      sh -c "
        python manage.py collectstatic --noinput &&
        # python manage.py makemigrations && 
        python manage.py migrate &&
        python manage.py runserver 0.0.0.0:8000
      "
    # command: >
    #   gunicorn --bind 0.0.0.0:8000
    #   --workers 3 
    #   --timeout 120 core.wsgi:application 
    env_file:
      - src/.env
    environment:
      - DJANGO_SETTINGS_MODULE=core.settings
      - PYTHONPATH=/app
      - PYTHONUNBUFFERED=1
    volumes:
      - ./src:/app:delegated
      - static_files:/app/staticfiles
      - media_files:/app/media 
      # - ./src/media:/app/media
      # - ./src/static:/app/static
      # - ./src/staticfiles:/app/staticfiles 
      - ./src/logs:/app/logs 
    depends_on: 
      db: 
        condition: service_healthy
      redis: 
        condition: service_healthy
    networks:
      - frontend
      - backend 
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  # ============================================================================
  # BACKGROUND TASK WORKER - Celery
  # ============================================================================
  # Asynchronous task processing for:
  # - Content analysis and recognition
  # - Analytics data processing
  # - Email notifications
  # - Report generation
  celery_worker:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    container_name: adtlas_celery_worker
    restart: unless-stopped
    command: >
      celery -A core worker
      --loglevel=info
      --concurrency=4
      --max-tasks-per-child=1000
    env_file:
      - src/.env
    environment:
      - DJANGO_SETTINGS_MODULE=core.settings
      - PYTHONPATH=/app
      - PYTHONUNBUFFERED=1
      - C_FORCE_ROOT=1
    volumes:
      - ./src:/app:delegated
      - media_files:/app/media
      # - ./src/media:/app/media 
      - ./src/logs:/app/logs
    depends_on:
      db: 
        condition: service_healthy
      redis: 
        condition: service_healthy
      web: 
        condition: service_healthy
    healthcheck:
      test: ["CMD-SHELL", "celery -A core inspect ping"]
      interval: 30s
      timeout: 10s
      retries: 3
    # Network configuration
    networks:
      - backend 

  # ============================================================================
  # TASK SCHEDULER - Celery Beat
  # ============================================================================
  # Periodic task scheduler for:
  # - Analytics data aggregation
  # - Content recognition updates
  # - System maintenance tasks
  celery_beat:
    # healthcheck: disabled for celery beat 
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    container_name: adtlas_celery_beat
    restart: unless-stopped
    command: >
      celery -A core beat
      --loglevel=info
      --scheduler django_celery_beat.schedulers:DatabaseScheduler
    env_file:
      - src/.env
    environment:
      - DJANGO_SETTINGS_MODULE=core.settings
      - PYTHONPATH=/app
      - PYTHONUNBUFFERED=1
    volumes:
      - ./src:/app:delegated
      - ./src/media:/app/media 
      - ./src/logs:/app/logs
    depends_on:
      db: 
        condition: service_healthy
      redis: 
        condition: service_healthy
      web: 
        condition: service_healthy
      celery_worker: 
        condition: service_healthy
    # Network configuration
    networks:
      - backend

  # ============================================================================
  # REVERSE PROXY SERVICE - Nginx
  # ============================================================================
  # High-performance reverse proxy and static file server
  nginx:
    image: nginx:alpine
    container_name: adtlas_nginx
    restart: unless-stopped
    ports:
      - "8090:80"
      # HTTPS port commented out for HTTP-only access
      # - "8443:443"
    volumes:
      - ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      # SSL certificates commented out for HTTP-only access
      # - ./docker/nginx/ssl:/etc/nginx/ssl:ro
      - static_files:/var/www/static:ro
      - media_files:/var/www/media:ro
    env_file:
      - src/.env
    depends_on:
      web: 
        condition: service_healthy
    # Network configuration
    networks:
      - frontend
