# 多阶段构建 - 本地打包版本
FROM python:3.12-slim as builder

# 设置工作目录
WORKDIR /app

# 安装构建依赖
RUN pip install --no-cache-dir --upgrade pip

# 复制requirements文件
COPY production-requirements.txt .

# 安装依赖到临时目录
RUN pip install --no-cache-dir --target /tmp/deps -r production-requirements.txt

# 生产阶段
FROM python:3.12-slim

# 设置工作目录
WORKDIR /app

# 设置环境变量
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    TZ=Asia/Shanghai

# 安装运行时依赖
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        curl \
        tzdata \
        ca-certificates \
    && rm -rf /var/lib/apt/lists/* \
    && ln -snf /usr/share/zoneinfo/$TZ /etc/localtime \
    && echo $TZ > /etc/timezone

# 创建非root用户
RUN useradd --create-home --shell /bin/bash app

# 从builder阶段复制已安装的包
COPY --from=builder /tmp/deps /usr/local/lib/python3.12/site-packages

# 复制应用代码
COPY . .

# 创建必要的目录并设置权限
RUN mkdir -p /app/uploads /app/logs \
    && chown -R app:app /app

# 切换到非root用户
USER app

# 暴露端口
EXPOSE 8002

# 健康检查
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8002/api/v1/health || exit 1

# 启动命令
CMD ["python", "main.py"]