# Backend Dockerfile (Context is root)
# 固定 Debian bookworm，避免 python:3.11-slim 随上游切到 trixie/testing 导致 apt 源 404
FROM python:3.11-slim-bookworm

WORKDIR /app

# 构建时若访问 deb.debian.org 不稳定：docker compose build --build-arg APT_CN_MIRROR=true
ARG APT_CN_MIRROR=false

# Install system dependencies（重试 + 超时；可选国内镜像）
RUN set -eux; \
    printf 'Acquire::Retries "5";\nAcquire::http::Timeout "120";\nAcquire::https::Timeout "120";\n' \
      > /etc/apt/apt.conf.d/99dataclaw; \
    if [ "$APT_CN_MIRROR" = "true" ] || [ "$APT_CN_MIRROR" = "1" ] || [ "$APT_CN_MIRROR" = "yes" ]; then \
      for f in /etc/apt/sources.list.d/*.sources /etc/apt/sources.list; do \
        [ -f "$f" ] || continue; \
        sed -i 's|http://deb.debian.org/debian|https://mirrors.tuna.tsinghua.edu.cn/debian|g' "$f"; \
        sed -i 's|https://deb.debian.org/debian|https://mirrors.tuna.tsinghua.edu.cn/debian|g' "$f"; \
        sed -i 's|http://security.debian.org/debian-security|https://mirrors.tuna.tsinghua.edu.cn/debian-security|g' "$f"; \
        sed -i 's|https://security.debian.org/debian-security|https://mirrors.tuna.tsinghua.edu.cn/debian-security|g' "$f"; \
      done; \
    fi; \
    i=1; \
    while [ "$i" -le 8 ]; do \
      apt-get update && \
      DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        build-essential curl libpq-dev && \
      rm -rf /var/lib/apt/lists/* && exit 0; \
      echo "apt attempt $i failed, retry in 25s..."; \
      i=$((i+1)); sleep 25; \
    done; \
    exit 1

# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

# Copy build-related files from dataclaw-api directory
COPY dataclaw-api/pyproject.toml dataclaw-api/uv.lock dataclaw-api/hatch_build.py dataclaw-api/README.md ./

# Install dependencies
RUN uv sync --frozen --no-dev

# Copy dataclaw-api source
COPY dataclaw-api/ .

# Copy the actual agent-core package from the nested directory
COPY agent-core/nanobot/ ./nanobot/
# Copy dataclaw-voice source
COPY dataclaw-voice/ ./whisper/

# Expose port
EXPOSE 8000

# Run the application with uvicorn
CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
