# ==============================================================================
# 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.8'

# ==============================================================================
# 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
    # internal: true 
    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:
  # PostgreSQL database data persistence
  postgres_data:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: ./docker/database/postgres/data 
  # Redis cache data persistence
  redis_data:
    driver: local
  # Static files volume for Nginx serving
  static_volume:
    driver: local
  # Media files volume for user uploads
  media_volume:
    driver: local
  # Application logs volume
  logs_volume:
    driver: local
  # Celery beat data volume
  celery_beat_data:
    driver: local
  # Prometheus monitoring data
  prometheus_data:
    driver: local
  # Grafana dashboard data
  grafana_data:
    driver: local

# ==============================================================================
# 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 PostgreSQL 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
    environment:
      # Database credentials (use .env file in production)
      POSTGRES_DB: ${POSTGRES_DB:-adtlas_db}
      POSTGRES_USER: ${POSTGRES_USER:-adtlas_user}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-adtlas_secure_password_2025} 
      # PostgreSQL performance tuning
      POSTGRES_INITDB_ARGS: "--encoding=UTF8 --locale=en_US.UTF-8" 
      # Connection and memory settings
      POSTGRES_SHARED_PRELOAD_LIBRARIES: 'pg_stat_statements' 
    #   POSTGRES_HOST_AUTH_METHOD: trust
    #   PGDATA: /var/lib/postgresql/data/pgdata 
    # command: >
    #   postgres
    #   -c config_file=/etc/postgresql/postgresql.conf
    #   -c log_statement=all
    #   -c log_destination=stderr 
    # Volume mounts for data persistence and configuration
    volumes:
      - postgres_data:/var/lib/postgresql/data 
      - ./docker/postgres/postgresql.conf:/etc/postgresql/postgresql.conf
      - ./docker/postgres/init-scripts:/docker-entrypoint-initdb.d
      - logs_volume:/var/log/postgresql 
    # Network configuration
    networks:
      - backend 
    # Port mapping (only for development - remove in production)
    # ports:
    #   - "5432:5432" 
    # Health check to ensure database is ready
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-adtlas_user} -d ${POSTGRES_DB:-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
      start_period: 30s # Time to wait before starting health check 
    # Resource limits for production stability
    deploy:
      resources:
        limits:
          memory: 2G
          cpus: '0.5'
        reservations:
          memory: 512M
          cpus: '0.25'    
    security_opt:
      - no-new-privileges:true 
    # # Memory and swap configuration to address kernel warnings
    # mem_limit: 2G
    # memswap_limit: 2G
    # mem_swappiness: 10 

  # ============================================================================
  # 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 
    # Redis configuration
    command: redis-server /etc/redis/redis.conf 
    environment:
      REDIS_PASSWORD: ${REDIS_PASSWORD:-}
    # Volume mounts
    volumes:
      - redis_data:/data
      - ./docker/redis/redis.conf:/etc/redis/redis.conf
      - logs_volume:/var/log/redis 
    # Network configuration
    networks:
      - backend 
    # Port mapping (only for development)
    # ports:
    #   - "6379:6379" 
    # Health check
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 10s 
    # Resource limits
    deploy:
      resources:
        limits:
          memory: 512M
          cpus: '0.25'
        reservations:
          memory: 256M
          cpus: '0.1'
    # security_opt:
    #   - no-new-privileges:true 
    # # Memory and swap configuration to address kernel warnings
    # mem_limit: 512M
    # memswap_limit: 512M
    # mem_swappiness: 10
  
  # ============================================================================
  # WEB APPLICATION SERVICE - Django
  # ============================================================================
  # Main Django application serving the Adtlas TV advertising platform
  web:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
      target: development
      args:
        BUILD_DATE: ${BUILD_DATE:-$(date -u +'%Y-%m-%dT%H:%M:%SZ')}
        VCS_REF: ${VCS_REF:-$(git rev-parse --short HEAD)}
        VERSION: ${VERSION:-2.0.0} 
    container_name: adtlas_web
    restart: unless-stopped
    # Environment variables
    environment:
      # Django Core Settings
      DJANGO_SETTINGS_MODULE: core.settings
      DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY:-your-super-secret-key-change-in-production-minimum-50-characters}
      DJANGO_DEBUG: ${DJANGO_DEBUG:-True}
      DJANGO_ALLOWED_HOSTS: ${DJANGO_ALLOWED_HOSTS:-localhost,127.0.0.1,0.0.0.0,adtlas.tv,*.adtlas.tv}
      
      # Database Configuration
      DATABASE_URL: postgresql://${POSTGRES_USER:-adtlas_user}:${POSTGRES_PASSWORD:-adtlas_secure_password_2025}@db:5432/${POSTGRES_DB:-adtlas_db}
      POSTGRES_DB: ${POSTGRES_DB:-adtlas_db}
      POSTGRES_USER: ${POSTGRES_USER:-adtlas_user}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-adtlas_secure_password_2025}
      POSTGRES_HOST: db
      POSTGRES_PORT: 5432
      
      # Redis Configuration
      REDIS_URL: redis://redis:6379/0
      CELERY_BROKER_URL: redis://redis:6379/1
      CELERY_RESULT_BACKEND: redis://redis:6379/2
      REDIS_HOST: redis
      REDIS_PORT: 6379
      REDIS_PASSWORD: ${REDIS_PASSWORD:-}
      
      # Application Settings
      PYTHONPATH: /app
      PYTHONDONTWRITEBYTECODE: 1
      PYTHONUNBUFFERED: 1
    # Volume mounts
    volumes:
      - static_volume:/app/staticfiles
      - media_volume:/app/media
      - logs_volume:/app/logs
      - ./src:/app
      # - ./src:/app:ro  # Read-only mount for development 
    # Network configuration
    networks:
      - frontend
      - backend  
    # Service dependencies
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy 
    # Health check
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health/"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 60s 
    # 
    security_opt:
      - no-new-privileges:true 
    # Resource limits
    deploy:
      resources:
        limits:
          memory: 1G
          cpus: '0.5'
        reservations:
          memory: 512M
          cpus: '0.25'
    # # Memory and swap configuration to address kernel warnings
    # mem_limit: 1G
    # memswap_limit: 1G
    # mem_swappiness: 10 
  
  # ============================================================================
  # REVERSE PROXY SERVICE - Nginx
  # ============================================================================
  # High-performance reverse proxy and static file server
  nginx:
    build:
      context: .
      dockerfile: ./docker/nginx/Dockerfile 
    container_name: adtlas_nginx
    restart: unless-stopped 
    # Volume mounts for static files and SSL certificates
    volumes:
      - static_volume:/app/static:ro
      - media_volume:/app/media:ro
      - ./docker/nginx/ssl:/etc/nginx/ssl:ro
      - logs_volume:/var/log/nginx 
    # Network configuration
    networks:
      - frontend 
    # Port mapping
    ports:
      - "8082:80"
      - "8443:443" 
    # Service dependencies
    depends_on:
      - web 
    # Health check
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health/"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 30s 
    # Resource limits
    deploy:
      resources:
        limits:
          memory: 256M
          cpus: '0.25'
        reservations:
          memory: 128M
          cpus: '0.1'
  # ============================================================================
  # 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
      target: development 
    container_name: adtlas_celery_worker
    restart: unless-stopped 
    # Override the default command to run Celery workers
    command: > 
      celery -A core worker 
      --loglevel=info 
      --concurrency=4
      --max-tasks-per-child=1000
      --time-limit=300
      --soft-time-limit=240
      --prefetch-multiplier=1
    # Environment variables (same as web service)
    environment:
      DJANGO_SETTINGS_MODULE: core.settings
      DATABASE_URL: postgresql://${POSTGRES_USER:-adtlas_user}:${POSTGRES_PASSWORD:-adtlas_secure_password_2025}@db:5432/${POSTGRES_DB:-adtlas_db}
      REDIS_URL: redis://redis:6379/0
      CELERY_BROKER_URL: redis://redis:6379/1
      CELERY_RESULT_BACKEND: redis://redis:6379/2 
    # Volume mounts
    volumes:
      - media_volume:/app/media
      - logs_volume:/app/logs
      # - ./src:/app:ro 
      - ./src:/app
    # Network configuration
    networks:
      - backend 
    # Service dependencies
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy 
    # Resource limits
    deploy:
      resources:
        limits:
          memory: 1G
          cpus: '0.5'
        reservations:
          memory: 512M
          cpus: '0.25'
  
  # ============================================================================
  # TASK SCHEDULER - Celery Beat
  # ============================================================================
  # Periodic task scheduler for:
  # - Analytics data aggregation
  # - Content recognition updates
  # - System maintenance tasks
  celery_beat:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
      target: development 
    container_name: adtlas_celery_beat
    restart: unless-stopped 
    # Override the default command to run Celery beat
    command: celery -A core beat --loglevel=info --scheduler django_celery_beat.schedulers:DatabaseScheduler
    # Environment variables (same as web service)
    environment:
      DJANGO_SETTINGS_MODULE: core.settings
      DATABASE_URL: postgresql://${POSTGRES_USER:-adtlas_user}:${POSTGRES_PASSWORD:-adtlas_secure_password_2025}@db:5432/${POSTGRES_DB:-adtlas_db}
      REDIS_URL: redis://redis:6379/0
      CELERY_BROKER_URL: redis://redis:6379/1
      CELERY_RESULT_BACKEND: redis://redis:6379/2 
    # Volume mounts
    volumes:
      - logs_volume:/app/logs
      - ./src:/app
      # - ./src:/app:ro 
    # Network configuration
    networks:
      - backend 
    # Service dependencies
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
      celery_worker:
        condition: service_started 
    # Resource limits
    deploy:
      resources:
        limits:
          memory: 256M
          cpus: '0.1'
        reservations:
          memory: 128M
          cpus: '0.05'
  
  # ============================================================================
  # MONITORING SERVICE - Prometheus
  # ============================================================================
  # Metrics collection and monitoring system
  prometheus:
    image: prom/prometheus:latest
    container_name: adtlas_prometheus
    restart: unless-stopped 
    # Prometheus configuration
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
      - '--web.console.libraries=/etc/prometheus/console_libraries'
      - '--web.console.templates=/etc/prometheus/consoles'
      - '--storage.tsdb.retention.time=200h'
      - '--web.enable-lifecycle' 
    # Volume mounts
    volumes:
      - ./docker/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheus_data:/prometheus 
    # Network configuration
    networks:
      - monitoring
      - backend 
    # Port mapping
    ports:
      - "9091:9090" 
    # Resource limits
    deploy:
      resources:
        limits:
          memory: 512M
          cpus: '0.25'
        reservations:
          memory: 256M
          cpus: '0.1'
  
  # ============================================================================
  # VISUALIZATION SERVICE - Grafana
  # ============================================================================
  # Dashboard and visualization platform for monitoring and analytics
  grafana:
    image: grafana/grafana:latest
    container_name: adtlas_grafana
    restart: unless-stopped 
    # Environment variables
    environment:
      GF_SECURITY_ADMIN_USER: ${GRAFANA_USER:-admin}
      GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD:-adtlas_grafana_2025}
      GF_USERS_ALLOW_SIGN_UP: false
      GF_INSTALL_PLUGINS: grafana-clock-panel,grafana-simple-json-datasource 
    # Volume mounts
    volumes:
      - grafana_data:/var/lib/grafana
      - ./docker/grafana/provisioning:/etc/grafana/provisioning
      - ./docker/grafana/dashboards:/var/lib/grafana/dashboards 
    # Network configuration
    networks:
      - monitoring 
    # Port mapping
    ports:
      - "3001:3000" 
    # Service dependencies
    depends_on:
      - prometheus 
    # Resource limits
    deploy:
      resources:
        limits:
          memory: 256M
          cpus: '0.25'
        reservations:
          memory: 128M
          cpus: '0.1'

# ==============================================================================
# DEVELOPMENT OVERRIDES
# ==============================================================================
# For development environment, create a docker-compose.override.yml file
# with the following content to enable development-specific settings:
#
# version: '3.8'
# services:
#   web:
#     environment:
#       DJANGO_DEBUG: 'True'
#       DJANGO_SETTINGS_MODULE: core.settings.development
#     volumes:
#       - ./src:/app
#     command: python manage.py runserver 0.0.0.0:8000
#
# ==============================================================================
# PRODUCTION NOTES
# ==============================================================================
# For production deployment:
# 1. Use environment variables for all sensitive data
# 2. Remove port mappings for internal services
# 3. Configure proper SSL certificates
# 4. Set up log rotation and monitoring
# 5. Configure backup strategies for volumes
# 6. Use secrets management for sensitive data
# ==============================================================================