FROM python:3.11-slim

WORKDIR /app

# 安装系统依赖（含编译bcrypt/cryptography所需的build-essential）
# Use Tsinghua mirror for faster downloads in China
RUN sed -i 's|deb.debian.org|mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || true
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    ca-certificates \
    build-essential \
    libffi-dev \
    libssl-dev \
    default-mysql-client \
    redis-tools \
    netcat-openbsd \
    nginx \
    && rm -rf /var/lib/apt/lists/*

# 先复制依赖文件，利用 Docker 构建缓存
COPY backend/python/requirements.txt /app/backend/python/requirements.txt
COPY frontend/package.json /app/frontend/package.json
COPY frontend/package-lock.json /app/frontend/package-lock.json

# 安装Python依赖（build-essential/libffi-dev确保bcrypt/cryptography能编译）
RUN pip install --no-cache-dir -r /app/backend/python/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

# 安装Node.js (用于前端构建) 并构建前端
# Use Tsinghua mirror for faster downloads in China
RUN sed -i 's|deb.debian.org|mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || true
RUN apt-get update && apt-get install -y --no-install-recommends \
    nodejs \
    npm \
    && rm -rf /var/lib/apt/lists/*

COPY frontend/ /app/frontend/
RUN cd /app/frontend && npm install --registry=https://registry.npmmirror.com && npm run build

# 验证前端构建产物
RUN test -f /app/frontend/dist/index.html || (echo "ERROR: 前端构建失败，index.html 不存在" && exit 1)
RUN test -d /app/frontend/dist/assets || (echo "ERROR: 前端构建失败，assets 目录不存在" && exit 1)
RUN echo "前端构建完成，dist 目录大小: $(du -sh /app/frontend/dist | cut -f1)"

# 复制项目源码（排除前端源码，已单独构建）
COPY backend/ /app/backend/
COPY migrations/ /app/migrations/
COPY nginx.conf /app/nginx.conf
COPY VERSION /app/VERSION
COPY CHANGELOG.md /app/CHANGELOG.md
COPY run.sh /app/run.sh

# 配置nginx: 移除默认站点，写入自定义配置，确保日志目录权限
RUN rm -f /etc/nginx/sites-enabled/default && \
    rm -f /etc/nginx/conf.d/default.conf 2>/dev/null || true; \
    cp /app/nginx.conf /etc/nginx/conf.d/aiflow.conf && \
    sed -i 's/include \/etc\/nginx\/sites-enabled\/\*;/# include \/etc\/nginx\/sites-enabled\/*;/' /etc/nginx/nginx.conf && \
    mkdir -p /var/log/nginx && \
    chown -R www-data:www-data /var/log/nginx && \
    chown -R www-data:www-data /var/lib/nginx

# 复制启动脚本并设置权限
RUN chmod +x /app/run.sh

EXPOSE 8080 18080

CMD ["/app/run.sh"]
