# ============================================================================
# HR Portal Backend Dockerfile
# FastAPI + Python 3.11 + PostgreSQL
# ============================================================================

FROM python:3.11-slim as base

# 設定環境變數
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

# 設定工作目錄
WORKDIR /app

# 安裝系統依賴
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    postgresql-client \
    && rm -rf /var/lib/apt/lists/*

# ============================================================================
# Builder Stage - 安裝 Python 依賴
# ============================================================================
FROM base as builder

# 複製需求檔案
COPY requirements.txt .

# 安裝 Python 依賴
RUN pip install --user --no-warn-script-location -r requirements.txt

# ============================================================================
# Runtime Stage - 最終映像
# ============================================================================
FROM base

# 從 builder 複製已安裝的套件
COPY --from=builder /root/.local /root/.local

# 確保 scripts 在 PATH 中
ENV PATH=/root/.local/bin:$PATH

# 複製應用程式碼
COPY . /app

# 創建日誌目錄
RUN mkdir -p /app/logs

# 暴露端口
EXPOSE 8000

# 健康檢查
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD python -c "import httpx; httpx.get('http://localhost:8000/health', timeout=5.0)" || exit 1

# 啟動命令
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
