FROM node:18.12.0-alpine3.16 AS web

WORKDIR /opt/build
COPY /web ./web
RUN npm install pnpm -g --registry=https://registry.npmmirror.com && cd /opt/build/web && pnpm i --registry=https://registry.npmmirror.com && pnpm run build

# === Python 依赖构建阶段（带编译工具）===
FROM python:3.11-slim-bullseye AS builder

# 切换为中科大源
RUN sed -i "s@http://.*.debian.org@http://mirrors.ustc.edu.cn@g" /etc/apt/sources.list \
    && rm -f /etc/apt/apt.conf.d/docker-clean \
    && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
    && apt-get update \
    && apt-get install -y --no-install-recommends gcc python3-dev \
    && rm -rf /var/lib/apt/lists/*

# 创建虚拟环境
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# 安装 Python 依赖（使用阿里云源，避免清华限流）
ADD app ./app
COPY requirements.txt ./app
RUN find app -name "requirement*.txt" | xargs -n 1 pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ -r

FROM python:3.11-slim-bullseye
WORKDIR /opt/backend-server

# 设置时区 & 安装最小运行依赖
RUN sed -i 's@http://.*.debian.org@http://mirrors.ustc.edu.cn@g' /etc/apt/sources.list \
    && apt-get update \
    && apt-get install -y --no-install-recommends nginx tzdata bash curl \
    && rm -rf /var/lib/apt/lists/* \
    && ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
    && echo "Asia/Shanghai" > /etc/timezone

# 从 builder 阶段拷贝已安装的 Python 依赖
COPY --from=builder /opt/venv /opt/venv

# 激活虚拟环境（通过 PATH）
ENV PATH="/opt/venv/bin:$PATH"
ENV LANG=zh_CN.UTF-8

# 拷贝应用代码（只拷贝必需目录和文件）
COPY app ./app
COPY static ./static
COPY templates ./templates
COPY run.py . 
COPY deploy/entrypoint.sh .

# 拷贝前端产物
COPY --from=web /opt/build/web/dist ./web/dist

# Nginx 配置
COPY deploy/web.conf /etc/nginx/sites-available/web.conf
RUN rm -f /etc/nginx/sites-enabled/default \
    && ln -s /etc/nginx/sites-available/web.conf /etc/nginx/sites-enabled/web.conf; \
    python -c "import sys; print(sys.path)" 

EXPOSE 80

ENTRYPOINT ["sh", "entrypoint.sh"]