# Evaluation-container image ("测评容器"): the inference service on port 8000 (dev spec, 推理服务api要求) and the
# training entry points (python -m compmodels.training.track<N> ...). CODE ONLY: no model weights and no datasets are
# in the image (the user's rule, 2026-09-27; a final RUN fails the build otherwise). Weights are mounted at run time:
# our own ones as the weights bundle extracted into team storage (/2026aicompetition/workspace/models/...,
# platform/h100/export_weights_bundle.sh), the committee's under /2026aicompetition/public_models; compmodels.paths
# resolves every path (env > <workspace>/config/model_paths.json > default) and `python -m compmodels.paths check`
# lists what is missing. Datasets come from the platform mounts (/2026aicompetition/datasets, input.dataset_path).
#
#   docker build -f competition_models/platform/Dockerfile -t compmodels-infer-slim:h100 competition_models
#
# FLAVOR is still accepted (scripts pass FLAVOR=slim / full) but changes nothing: there is one code-only flavour. The
# former `full` flavour (every track's weights baked in, 39.6 GB) and its weights / trained / totalseg build contexts
# are gone; build_track_image_h100.sh now builds this image under a per-track tag.
#
# Base: CUDA 12.8 / torch 2.8 since 2026-09-26. The platform's GPU is an RTX 5090 class card (Blackwell, sm_120,
# CUDA 12.8, cuDNN 9; docs/06-platform-workflow.md section 5.1). The earlier torch 2.4 / CUDA 12.4 base carried
# kernels up to sm_90 only and cannot run there; pytorch/pytorch:2.8.0-cuda12.8-cudnn9-runtime lists sm_70..sm_120
# (and still runs on the H100 test box, sm_90).
#
# Layer order (bottom to top): CUDA/torch base, pip dependencies, test extra, code. A code change rebuilds only the
# top layers (seconds).
ARG FLAVOR=slim

FROM pytorch/pytorch:2.8.0-cuda12.8-cudnn9-runtime AS base

ENV PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    COMP_TRACK=4 \
    COMP_PORT=8000 \
    COMP_PROFILE=full \
    COMP_DEVICE=cuda \
    COMP_ANSWER_BASE=/2026aicompetition/workspace/answer \
    COMP_CONFIG_DIR=/opt/compmodels/configs
# COMP_CALLBACK_URL has no default on purpose: copy it from the container page on the platform.

WORKDIR /opt/compmodels
# 1. dependencies first (cached layer: only pyproject.toml invalidates it)
COPY pyproject.toml ./
# torch / torchvision / numpy come with the base image and are pinned as pip constraints (read from the base image
# itself, so a base bump needs no edit here) so no dependency (MONAI's newest release wants a newer torch) can drag
# in another CUDA build of torch or another numpy. torchaudio is pinned only when the base ships it.
RUN python -c "import importlib.util, importlib.metadata as m; \
pk = ['torch', 'torchvision', 'numpy'] + [p for p in ('torchaudio',) if importlib.util.find_spec(p)]; \
print('\n'.join(f'{p}=={m.version(p)}' for p in pk))" > /tmp/constraints.txt \
    && cat /tmp/constraints.txt \
    && python -c "import tomllib; d = tomllib.load(open('pyproject.toml', 'rb'))['project']; \
deps = d['dependencies'] + d['optional-dependencies']['platform'] + d['optional-dependencies']['baselines'] + d['optional-dependencies']['full']; \
print('\n'.join(x for x in deps if not x.lower().startswith('torch')))" > /tmp/requirements.txt \
    && cat /tmp/requirements.txt && pip install -c /tmp/constraints.txt -r /tmp/requirements.txt \
    && python -c "import torch, torchvision, numpy; assert torch.__version__.startswith('2.8'), torch.__version__; print(torch.__version__, torch.cuda.get_arch_list())" \
    && pip list | grep -iE '^(torch|monai|numpy|scikit|nnunet)'
# 1b. the `test` extra (pytest), its own small layer so the dependency layer above stays cached
RUN python -c "import tomllib; print('\n'.join(tomllib.load(open('pyproject.toml', 'rb'))['project']['optional-dependencies']['test']))" \
       > /tmp/test-requirements.txt && pip install -c /tmp/constraints.txt -r /tmp/test-requirements.txt
# 1c. (no weights: the former FLAVOR=full COPY of /LLM/models and /root/.totalsegmentator is removed)
FROM base AS final
ARG FLAVOR
# 2. the code (rebuilds after a code change take seconds)
COPY src ./src
COPY configs ./configs
COPY platform ./platform
COPY mockdata ./mockdata
COPY benchmarks ./benchmarks
# the pytest suite and the spec texts it checks against (run_tests_h100.sh:
#   docker run --rm --entrypoint python compmodels-infer:h100 -m pytest -q /opt/compmodels/tests)
COPY tests ./tests
COPY reference ./reference
# editable install keeps configs/ next to src/ (predict.CONFIG_DIR) and lets team storage override code.
RUN pip install --no-deps -e . \
    && python -c "import compmodels.platform.serve, compmodels.predict, compmodels.baselines, skimage, sklearn, pydicom, monai, torchvision"

# no weights and no data in the image (the user's rule, platform/README.md "Weights"): fail the build on any
# checkpoint / volume / DICOM / array file outside site-packages (library test samples live there)
RUN hits=$(find /opt/compmodels /LLM /root/.totalsegmentator -path '*/site-packages' -prune -o -type f \( \
        -name '*.pth' -o -name '*.pt' -o -name '*.safetensors' -o -name '*.ckpt' -o -name '*.nii.gz' -o -name '*.dcm' \
        -o -name '*.npz' \) -print 2>/dev/null | head -50); \
    if [ -n "$hits" ]; then echo "weight or dataset files in the image (mount them at run time instead):"; echo "$hits"; exit 1; fi; \
    echo "weight-free: no *.pth|*.pt|*.safetensors|*.ckpt|*.nii.gz|*.dcm|*.npz under /opt/compmodels /LLM /root/.totalsegmentator"

EXPOSE 8000
# mirrors the platform liveness probe (every 30 s, 3 failures)
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)" || exit 1

# long-lived foreground process, as the spec requires. Training uses the same image with another entrypoint:
#   docker run --rm --gpus '"device=1"' --shm-size 16g --entrypoint python -v <data>:/data -v <work>:/work \
#       -v <models>:/2026aicompetition/workspace/models:ro compmodels-infer-slim:h100 -m compmodels.training.track4 train --cache /work/cache --out /work/run1 ...
ENTRYPOINT ["python", "-m", "compmodels.platform.serve"]
