# 国内 Jenkins 默认走 DaoCloud 公共镜像代理（完整代理 docker.io/library），避免拉取超时
# 可覆盖: docker build --build-arg NODE_IMAGE=node:20-alpine ...
ARG NODE_IMAGE=docker.m.daocloud.io/library/node:20-alpine
ARG PYTHON_IMAGE=docker.m.daocloud.io/library/python:3.11-slim

# Stage 1: build frontend
FROM ${NODE_IMAGE} AS web-builder

WORKDIR /app/web

COPY web/package.json web/package-lock.json ./
RUN npm config set registry https://registry.npmmirror.com \
    && npm ci

COPY web/ ./
RUN npm run build

# Stage 2: Python runtime
FROM ${PYTHON_IMAGE}

WORKDIR /app

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    TZ=Asia/Shanghai \
    SCHEDULER_TIMEZONE=Asia/Shanghai \
    SCHEDULER_CRON_HOUR=15 \
    SCHEDULER_CRON_MINUTE=0 \
    PIPELINE_WORKER_PROCESSES=4 \
    PIPELINE_MAX_ACTIVE_STEPS=4 \
    FIND_AGENT_TIMEOUT_SECONDS=600 \
    MYSQL_CONNECTION_BUDGET=40

RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g; s|security.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || \
    sed -i 's|deb.debian.org|mirrors.aliyun.com|g; s|security.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list 2>/dev/null || true

RUN apt-get update \
    && apt-get install -y --no-install-recommends gcc ffmpeg supervisor \
    && ffmpeg -version >/dev/null \
    && ffprobe -version >/dev/null \
    && ffmpeg -hide_banner -loglevel error \
        -f lavfi -i testsrc=duration=2:size=160x120:rate=10 \
        -t 2 -c:v libx264 -pix_fmt yuv420p /tmp/verify_src.mp4 \
    && ffmpeg -hide_banner -loglevel error -y \
        -i /tmp/verify_src.mp4 -t 1 -c copy /tmp/verify_clip.mp4 \
    && test -s /tmp/verify_clip.mp4 \
    && rm -f /tmp/verify_src.mp4 /tmp/verify_clip.mp4 \
    && rm -rf /var/lib/apt/lists/*

COPY pyproject.toml requirements.txt README.md ./
COPY supply_agent/ supply_agent/
COPY supply_infra/ supply_infra/
COPY agents/ agents/
COPY api/ api/
COPY alembic.ini ./
COPY alembic/ alembic/
COPY deploy/ deploy/
COPY scripts/verify_video_truncate_runtime.py scripts/
COPY scripts/container-entrypoint.sh scripts/

RUN test -s agents/demand_belong_category_agent/prompt/system_prompt.md \
    && test -s agents/demand_grade_agent/prompt/system_prompt.md \
    && test -s agents/demand_video_expand_agent/prompt/system_prompt.md \
    && pip install -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com ".[odps]" \
    && python scripts/verify_video_truncate_runtime.py \
    && chmod +x scripts/container-entrypoint.sh

COPY --from=web-builder /app/web/dist ./web/dist

EXPOSE 8080

STOPSIGNAL SIGTERM

ENTRYPOINT ["/app/scripts/container-entrypoint.sh"]
