# ==============================================================================
# DSCons Enterprise ERP - Production Multi-Stage Dockerfile
# Python 3.11 Slim (Debian Bookworm) with PyTorch CPU & Spatial/CAD Optimization
# ==============================================================================

FROM python:3.11-slim-bookworm

LABEL maintainer="DSCons Engineering Team <tech@dinhsonconstruction.com>"
LABEL description="DSCons ERP Construction Management & AI Operations Platform"

# Thiết lập biến môi trường hệ thống
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    DEBIAN_FRONTEND=noninteractive \
    PORT=8000 \
    APP_ENV=production

# Cài đặt các gói thư viện OS cấp thiết (C/C++ runtime cho AI, PDF, CAD & PostgreSQL)
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    curl \
    git \
    libpq-dev \
    libglib2.0-0 \
    libgomp1 \
    libgl1 \
    fonts-liberation \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Nâng cấp pip và cài đặt PyTorch phiên bản CPU để tối ưu hóa kích thước Docker image (~700MB thay vì 4GB CUDA)
RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \
    pip install --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu

# Sao chép toàn bộ mã nguồn ứng dụng vào container trước khi cài đặt package
COPY . /app

# Cài đặt các thư viện lõi từ pyproject.toml và production dependencies
RUN pip install --no-cache-dir -e . && \
    pip install --no-cache-dir \
        gunicorn \
        pydantic-settings \
        python-multipart \
        pypdf \
        pymupdf \
        ezdxf \
        pandas \
        openpyxl \
        xlrd \
        google-genai \
        google-antigravity

# Tạo thư mục lưu trữ cục bộ và phân quyền
RUN mkdir -p /app/storage /app/deployment/qdrant-data /app/logs

# Mở cổng dịch vụ backend
EXPOSE 8000

# Healthcheck giám sát trạng thái hoạt động của dịch vụ
HEALTHCHECK --interval=15s --timeout=5s --start-period=30s --retries=3 \
    CMD curl -f http://127.0.0.1:8000/health || exit 1

# Khởi chạy Uvicorn production server với 2 workers xử lý đồng thời
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2", "--proxy-headers", "--forwarded-allow-ips=*"]
