# Stage 1: Build Frontend
FROM node:22 AS frontend-builder
WORKDIR /app/frontend

# 使用淘宝 NPM 镜像
RUN npm config set registry https://registry.npmmirror.com
RUN npm config set fetch-retry-maxtimeout 120000
RUN npm config set fetch-retry-mintimeout 20000
RUN npm config set fetch-retries 5

COPY frontend/package*.json ./
RUN rm -f package-lock.json
RUN npm install
COPY frontend/ ./
# Build the frontend. The output should be in frontend/dist
# 由于 vite.config.ts 设置了 outDir 为 ../backend/dist，这里我们需要强制覆盖为 dist
RUN npm run build -- --outDir dist
RUN ls -la dist/

# Stage 2: Backend Runtime
FROM python:3.10-slim

WORKDIR /app

ARG DEBIAN_FRONTEND=noninteractive
# 替换 apt 源为阿里云源 (Debian Bookworm)
RUN echo "deb https://mirrors.aliyun.com/debian/ bookworm main non-free non-free-firmware contrib" > /etc/apt/sources.list && \
    echo "deb-src https://mirrors.aliyun.com/debian/ bookworm main non-free non-free-firmware contrib" >> /etc/apt/sources.list && \
    echo "deb https://mirrors.aliyun.com/debian-security/ bookworm-security main" >> /etc/apt/sources.list && \
    echo "deb-src https://mirrors.aliyun.com/debian-security/ bookworm-security main" >> /etc/apt/sources.list && \
    echo "deb https://mirrors.aliyun.com/debian/ bookworm-updates main non-free non-free-firmware contrib" >> /etc/apt/sources.list && \
    echo "deb-src https://mirrors.aliyun.com/debian/ bookworm-updates main non-free non-free-firmware contrib" >> /etc/apt/sources.list && \
    echo "deb https://mirrors.aliyun.com/debian/ bookworm-backports main non-free non-free-firmware contrib" >> /etc/apt/sources.list && \
    echo "deb-src https://mirrors.aliyun.com/debian/ bookworm-backports main non-free non-free-firmware contrib" >> /etc/apt/sources.list

# Install system dependencies required for OpenCV
RUN apt-get update && apt-get install -y \
    libgl1 \
    libglib2.0-0 \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY backend/requirements.txt .
# 使用清华 PyPI 镜像
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

# Copy backend code
COPY backend/ ./backend/
COPY run.py .

# Copy built frontend assets to backend/dist (as expected by main.py)
COPY --from=frontend-builder /app/frontend/dist ./backend/dist

# Create directories for volumes
RUN mkdir -p reports backend/app/static/snapshots

# Expose the port
EXPOSE 8000

# Run the application
CMD ["python", "run.py"]
