FROM python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Static Docker CLI (pinned). community.docker + Molecule invoke `docker` against the mounted host socket.
# The Debian docker.io metapackage is unreliable here (missing/wrong PATH for ansible-playbook children).
ARG DOCKER_CLI_VERSION=27.4.1

# Do not install ansible from Debian — it pins an old ansible-core. Tooling comes from pyproject.toml (pip).
RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    rsync \
    ca-certificates \
    curl \
    && rm -rf /var/lib/apt/lists/* \
  && set -eux; \
  arch="$(dpkg --print-architecture)"; \
  case "$arch" in \
    amd64) darch=x86_64 ;; \
    arm64) darch=aarch64 ;; \
    *) echo "unsupported architecture: $arch"; exit 1 ;; \
  esac; \
  curl -fsSL "https://download.docker.com/linux/static/stable/${darch}/docker-${DOCKER_CLI_VERSION}.tgz" \
    | tar -xz --strip-components=1 -C /usr/local/bin docker/docker; \
  chmod +x /usr/local/bin/docker; \
  /usr/local/bin/docker --version

WORKDIR /app

COPY . /app
RUN pip install --no-cache-dir uv && uv pip install --system .

# Molecule docker driver playbooks use community.docker and ansible.posix (synchronize in create.yml).
# Install at build time so ephemeral runners do not rely on Galaxy NG at test time.
RUN bash -ec '\
  ok=0; \
  for attempt in 1 2 3 4 5; do \
    if ansible-galaxy collection install ansible.posix "community.docker:>=3.10.2"; then ok=1; break; fi; \
    echo "ansible-galaxy install attempt ${attempt} failed, retrying in 10s..."; \
    sleep 10; \
  done; \
  test "$ok" -eq 1' \
  && rm -rf /root/.ansible/galaxy_cache /root/.ansible/tmp 2>/dev/null || true

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