FROM ghcr.io/home-assistant/amd64-base-debian:bookworm as darknet_builder
ENV DEBIAN_FRONTEND=noninteractive
RUN apt update && apt install -y ca-certificates build-essential gcc g++ cmake git
WORKDIR /

# Lock darknet version for reproducibility.
RUN git clone https://github.com/AlexeyAB/darknet && cd darknet && git checkout 59c86222c5387bffd9108a21885f80e980ece234
RUN cd darknet \
  && sed -i 's/GPU=1/GPU=0/' Makefile \
  && sed -i 's/CUDNN=1/CUDNN=0/' Makefile \
  && sed -i 's/CUDNN_HALF=1/CUDNN_HALF=0/' Makefile \
  && sed -i 's/LIBSO=0/LIBSO=1/' Makefile \
  && make -j 4 && mv libdarknet.so libdarknet_cpu.so

FROM ghcr.io/home-assistant/amd64-base-debian:bookworm

RUN apt update && apt install --no-install-recommends -y ca-certificates python3-pip wget python3 python3-venv

COPY rootfs /
COPY --from=darknet_builder /darknet /darknet

WORKDIR /app

RUN python3 -m venv venv
ENV VIRTUAL_ENV=/app/venv
ENV PATH=/app/venv/bin:$PATH

RUN pip3 install --upgrade pip && \
    pip3 install opencv_python_headless && \
    pip3 install -r requirements.txt

RUN echo 'Downloading the latest failure detection AI model in Darknet format...' && \
    wget -O model/model-weights.darknet $(cat model/model-weights.darknet.url | tr -d '\r') && \
    echo 'Downloading the latest failure detection AI model in ONNX format...' && \
    wget -O model/model-weights.onnx $(cat model/model-weights.onnx.url | tr -d '\r')

RUN chmod +x /etc/services.d/ha-elegoo-spaghetti-detection/run
