FROM ghcr.io/astral-sh/uv:python3.13-bookworm-slim AS builder

RUN apt-get update
RUN apt-get install --yes --no-install-recommends git build-essential
RUN rm -rf /var/lib/apt/lists/*

ARG KEBLE_AMZ_REF=b6ce544995cd14c6930bdfdfa809cd5ba10e7833
ARG KEBLE_TIKTOK_REF=f14a9c670d270a201f2359e608f6b1e2b0493825
ARG KEBLE_PY_REF=9db27c8c4cac25fcf4993620168c9f77dd95a0f5
ARG KEBLE_KEEPA_REF=5907fe43d3368fec6e64da4c30e33eddb7b1d885

WORKDIR /workspace
RUN --mount=type=secret,id=gh_token \
    sh -eu -c 'TOKEN="$(cat /run/secrets/gh_token)"; BASIC="$(printf "x-access-token:%s" "${TOKEN}" | base64 -w0)"; git -c http.extraHeader="Authorization: Basic ${BASIC}" clone https://github.com/keble-ai/keble-amz.git data-infra/keble-amz'
RUN git -C data-infra/keble-amz checkout ${KEBLE_AMZ_REF}
RUN --mount=type=secret,id=gh_token \
    sh -eu -c 'TOKEN="$(cat /run/secrets/gh_token)"; BASIC="$(printf "x-access-token:%s" "${TOKEN}" | base64 -w0)"; git -c http.extraHeader="Authorization: Basic ${BASIC}" clone https://github.com/keble-ai/keble-tiktok.git data-infra/keble-tiktok'
RUN git -C data-infra/keble-tiktok checkout ${KEBLE_TIKTOK_REF}
RUN --mount=type=secret,id=gh_token \
    sh -eu -c 'TOKEN="$(cat /run/secrets/gh_token)"; BASIC="$(printf "x-access-token:%s" "${TOKEN}" | base64 -w0)"; git -c http.extraHeader="Authorization: Basic ${BASIC}" clone https://github.com/keble-ai/keble-py.git deps/keble-py'
RUN git -C deps/keble-py checkout ${KEBLE_PY_REF}
RUN --mount=type=secret,id=gh_token \
    sh -eu -c 'TOKEN="$(cat /run/secrets/gh_token)"; BASIC="$(printf "x-access-token:%s" "${TOKEN}" | base64 -w0)"; git -c http.extraHeader="Authorization: Basic ${BASIC}" clone https://github.com/keble-ai/keble-keepa.git deps/keble-keepa'
RUN git -C deps/keble-keepa checkout ${KEBLE_KEEPA_REF}

COPY . /workspace/data-infra/keble-data-infra
WORKDIR /workspace/data-infra/keble-data-infra
RUN uv sync --no-editable --no-default-groups --package keble-data-infra-api

FROM python:3.13-slim-bookworm AS runtime

ENV PATH="/workspace/data-infra/keble-data-infra/.venv/bin:${PATH}" \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

RUN useradd --create-home --uid 10001 keble
WORKDIR /workspace/data-infra/keble-data-infra
COPY --from=builder --chown=keble:keble /workspace/data-infra/keble-data-infra/.venv /workspace/data-infra/keble-data-infra/.venv

USER keble
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=5s --start-period=15s --retries=4 \
    CMD ["python", "-c", "from urllib.request import urlopen; urlopen('http://127.0.0.1:8000/ready', timeout=3).read()"]

CMD ["uvicorn", "keble_data_infra_api.main:app", "--host", "0.0.0.0", "--port", "8000"]
