# syntax=docker/dockerfile:1
FROM python:3.11-slim AS builder

# Pinned — a moving :latest would resolve independently at each of the three
# sites that name this image (here and the train stage's two RUN mounts), so
# stages could silently build with different uv versions. Bump all three together.
# 0.13.5 drops emSign ECC Root CA - G3 and rejects the compromised eMudhra
# intermediate keys.
# https://discuss.python.org/t/information-for-python-users-regarding-emudhra-emsign-ca-certificate-security-incident/109576
COPY --from=ghcr.io/astral-sh/uv:0.13.5 /uv /uvx /bin/

WORKDIR /app

# Hash-pinned pip: uv installs the app, but the base image's pip is copied into
# the runtime stage with site-packages and would keep trusting emSign G3.
# Above COPY/ARG so a source change or a release VERSION doesn't re-download it.
RUN python -m pip install --no-cache-dir \
    "pip @ https://files.pythonhosted.org/packages/3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/pip-26.2.2-py3-none-any.whl#sha256=fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70"

# The base image has no `git`, so hatch-vcs can't derive the version from
# history — hand it in via the VERSION build arg (the release tag, sans "v").
# Defaults to 0.0.0+local so a locally built image is distinguishable on
# /health from a real release rather than claiming to be a plain 0.0.0.
ARG VERSION=0.0.0+local

COPY . /app

# The version is exported for this RUN only. As an `ENV` it would join the cache
# key of every layer below it (so a release build, whose VERSION always differs,
# could never reuse one) and would persist into the runtime image, where the
# unscoped name would stamp itself onto any setuptools-scm package installed
# later. hatch-vcs does not read the scoped SETUPTOOLS_SCM_PRETEND_VERSION_FOR_*
# form, so the unscoped one is the only option — confining it to this
# instruction is what keeps the blast radius to this install.
# The cache mount keeps wheel downloads across builds even when this layer runs.
RUN --mount=type=cache,target=/root/.cache/uv \
    SETUPTOOLS_SCM_PRETEND_VERSION="${VERSION}" \
    uv pip install --system "certifi>=2026.10.19" ".[server,cli]"

FROM python:3.11-slim AS runtime-base

# Runtime TLS (urllib / truststore) uses this bundle, not uv's. Debian's package
# may still ship emSign ECC Root CA - G3; distrust it and the Comodo AAA
# cross-sign root. Unaffected emSign roots stay enabled.
# https://discuss.python.org/t/information-for-python-users-regarding-emudhra-emsign-ca-certificate-security-incident/109576
RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates \
    && sed -i \
        -e 's|^mozilla/emSign_ECC_Root_CA_-_G3|!mozilla/emSign_ECC_Root_CA_-_G3|' \
        -e 's|^mozilla/Comodo_AAA|!mozilla/Comodo_AAA|' \
        /etc/ca-certificates.conf \
    && update-ca-certificates --fresh >/dev/null \
    && rm -rf /var/lib/apt/lists/*

# Only the installed package and its console script — uv (~64 MB of the old
# single-stage image) is a build tool and never runs here.
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin/argus-forge /usr/local/bin/argus-forge

# Both docker-compose.yaml and the README's `docker run -v ...:/data/out` use
# this path. Without a default the published image starts, answers /health with
# "ok", and then refuses every functional request for want of a root — a
# healthy-looking service the frontend cannot use.
ENV ARGUS_FORGE_EXPORT_ROOT=/data/out

# Demo-safe by default: /config renders but never writes, and every /run route is
# refused with 403. The default (`runtime`) image ships no trainer — no torch, no
# sd-scripts — so a run could only ever fail, and the port is published on
# 0.0.0.0 where a run is real code execution on the host (see runner.py's trust
# note) and an unauthenticated /config would overwrite the curator's
# metadata.jsonl. The default therefore has to be the safe one: `docker run` of
# this image is as locked down as `docker compose up`, and .env.example's
# "Defaults to 1" is true of the image itself rather than only of the compose
# file. The `train` variant below keeps this default on purpose — carrying a
# trainer makes flipping the flag *meaningful*, not automatic; arming /run stays
# a deliberate step on a trusted host. See README "Demo-safe mode".
ENV ARGUS_FORGE_READONLY=1

EXPOSE 8103

CMD ["argus-forge", "serve", "--port", "8103", "--cors"]

# ── train variant ────────────────────────────────────────────────────────────
# The runtime stack `POST /run` needs to actually execute a forged kohya
# train.sh: torch (CUDA wheels), accelerate, and a pinned kohya-ss/sd-scripts
# checkout. Published as ghcr.io/smk762/argus-forge:<version>-train — a distinct
# multi-GB tag, so the default `latest`/`<version>` stays the thin
# config-renderer and nobody pulls the trainer stack by accident (issue #24).
# Build: docker build --target train .
# No CUDA base image: torch's cu124 wheels bundle the CUDA runtime as nvidia-*
# pip packages, so python:3.11-slim serves both variants and only the host
# driver (nvidia-container-toolkit, `--gpus all`) is needed at run time.
FROM runtime-base AS train

# opencv-python (an sd-scripts dependency) links libGL/glib at import time.
# gcc + libc6-dev are not build tools here but a RUNTIME dependency: on a GPU
# host, triton (via bitsandbytes, which kohya's default AdamW8bit optimizer
# imports) JIT-compiles a CUDA driver stub at import time and dies without a
# working C toolchain — libc6-dev spelled out because --no-install-recommends
# drops it and gcc alone then fails on <stdlib.h>. CPU-only CI never takes that
# path (bitsandbytes imports fine without a GPU), so the smoke test gates on a
# test compile instead.
RUN apt-get update \
    && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 gcc libc6-dev \
    && rm -rf /var/lib/apt/lists/*

# torch first, alone, and *above* the sd-scripts checkout: by far the largest
# layer (several GB), and it depends on nothing below, so an SD_SCRIPTS_SHA
# bump — the routine maintenance path here — reuses it from cache. The ARG is
# declared *after* this RUN on purpose: a declared ARG joins every later RUN's
# cache key, so hoisting it above would re-bust this layer on every bump. The
# pin is what sd-scripts v0.11.1 recommends — re-check it whenever the SHA
# moves. uv is mounted, not installed: same build-tool hygiene as the builder.
# No certifi pin here: --index-url makes the cu124 index the only source and it
# carries only certifi 2022.12.7, so the pin would be unsatisfiable. torch does
# not pull certifi; the builder's pinned copy (inherited via site-packages) and
# the sd-scripts constraint below cover it.
RUN --mount=from=ghcr.io/astral-sh/uv:0.13.5,source=/uv,target=/bin/uv \
    --mount=type=cache,target=/root/.cache/uv \
    uv pip install --system torch==2.6.0 torchvision==0.21.0 \
      --index-url https://download.pytorch.org/whl/cu124

# kohya-ss/sd-scripts v0.11.1, pinned by commit so the tag can't move under us.
ARG SD_SCRIPTS_SHA=6721028c79ee85a78b3a06dfd8954dae310a1cce

# Tarball by commit SHA instead of a git clone: pinned by construction, and the
# image never needs git. The forged train.sh cds into $SD_SCRIPTS_DIR to run
# sdxl_train_network.py, so the checkout itself stays in the image.
ADD https://github.com/kohya-ss/sd-scripts/archive/${SD_SCRIPTS_SHA}.tar.gz /tmp/sd-scripts.tar.gz
RUN mkdir -p /opt/sd-scripts \
    && tar -xzf /tmp/sd-scripts.tar.gz -C /opt/sd-scripts --strip-components=1 \
    && rm /tmp/sd-scripts.tar.gz

# sd-scripts' own pins (accelerate, diffusers, transformers, ...). The file
# ends in `-e .`, which resolves relative to the cwd — hence the cd; that
# editable install is what makes `import library.train_util` work everywhere.
# The constraint file holds torch/torchvision to the cu124 build above: this
# install resolves against default PyPI, so a future requirements.txt whose
# pins conflicted with 2.6.0 would otherwise silently swap in a PyPI wheel —
# better a loud resolver error here than a wrong-CUDA torch discovered on a
# GPU host. (The smoke test asserts the same pins from the run side.)
RUN --mount=from=ghcr.io/astral-sh/uv:0.13.5,source=/uv,target=/bin/uv \
    --mount=type=cache,target=/root/.cache/uv \
    printf 'torch==2.6.0+cu124\ntorchvision==0.21.0+cu124\ncertifi>=2026.10.19\n' > /tmp/torch-pin.txt \
    && cd /opt/sd-scripts && uv pip install --system -c /tmp/torch-pin.txt -r requirements.txt \
    && rm /tmp/torch-pin.txt

# runner.py spawns train.sh with {**os.environ, **req.env}, so this default
# reaches the script and a caller no longer has to pass SD_SCRIPTS_DIR per run.
ENV SD_SCRIPTS_DIR=/opt/sd-scripts

# ── default ──────────────────────────────────────────────────────────────────
# The thin config-renderer, deliberately LAST: a bare `docker build .` (and the
# compose file's default) must keep producing the demo-safe ~200 MB image,
# never the multi-GB trainer.
FROM runtime-base AS runtime
