FROM ghcr.io/astral-sh/uv:0.7.12 AS uv

# First, bundle the dependencies into the task root.
FROM 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:lambda-python313 AS builder

# Enable bytecode compilation, to improve cold-start performance.
ENV UV_COMPILE_BYTECODE=1

# Disable installer metadata, to create a deterministic layer.
ENV UV_NO_INSTALLER_METADATA=1

# Enable copy mode to support bind mount caching.
ENV UV_LINK_MODE=copy

# Bundle the dependencies into the Lambda task root via `uv pip install --target`.
#
# Omit any local packages (`--no-emit-workspace`) and development dependencies (`--no-dev`).
# This ensures that the Docker layer cache is only invalidated when the `pyproject.toml` or `uv.lock`
# files change, but remains robust to changes in the application code.
RUN --mount=from=uv,source=/uv,target=/bin/uv \
    --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv export --frozen --no-emit-workspace --no-dev --no-editable -o requirements.txt && \
    uv pip install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"

FROM 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:lambda-python313 as deploy

ARG version
LABEL Version=$version
ENV build_version=$version

# Copy the runtime dependencies from the builder stage.
COPY --from=builder ${LAMBDA_TASK_ROOT} ${LAMBDA_TASK_ROOT}

# Copy Datadog Lambda extension
COPY --from=public.ecr.aws/datadog/lambda-extension:81 /opt/. /opt/

# Copy the application code.
COPY ./update_waf_ipsets ${LAMBDA_TASK_ROOT}/update_waf_ipsets

# Set the AWS Lambda handler.
EXPOSE 8080
ENV DD_LAMBDA_HANDLER=update_waf_ipsets.app.handler
CMD ["datadog_lambda.handler.handler"]



# Python dev stage
FROM 086679231553.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:lambda-python313 AS python-dev
COPY --from=uv /uv /uvx /bin/

WORKDIR /var/app

ENV UV_LINK_MODE=copy

RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --frozen

COPY --chown=worker:worker update_waf_ipsets/ ./update_waf_ipsets/
COPY --chown=worker:worker tests/ ./tests/
COPY --chown=worker:worker pyproject.toml ./

# Lint and Test Stage
FROM python-dev AS lint-and-test

COPY --chown=worker:worker lint-and-test.sh ./
RUN chmod +x lint-and-test.sh

ENTRYPOINT  ["./lint-and-test.sh"]
