# Honcho — Memory infrastructure for stateful AI agents
# Builds the Honcho FastAPI server from the official GitHub repository.
#
# Usage:
#   docker compose build honcho
#   docker compose up honcho
#
# Reference: https://github.com/plastic-labs/honcho

# ---------------------------------------------------------------------------
# Stage 1 — clone source & install dependencies
# ---------------------------------------------------------------------------
FROM python:3.13-slim-bookworm AS builder

RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*

COPY --from=ghcr.io/astral-sh/uv:0.9.24 /uv /bin/uv

WORKDIR /src
RUN git clone --depth 1 --branch main https://github.com/plastic-labs/honcho.git .

ENV UV_COMPILE_BYTECODE=1
ENV UV_LINK_MODE=copy

# Install project dependencies (frozen from lockfile, no dev)
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-install-project --no-group dev

# ---------------------------------------------------------------------------
# Stage 2 — runtime image
# ---------------------------------------------------------------------------
FROM python:3.13-slim-bookworm AS runtime

COPY --from=ghcr.io/astral-sh/uv:0.9.24 /uv /bin/uv

RUN apt-get update && \
    apt-get install -y --no-install-recommends ca-certificates && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app

ENV UV_COMPILE_BYTECODE=1
ENV UV_LINK_MODE=copy
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV PATH="/app/.venv/bin:$PATH"
ENV HOME=/app
ENV UV_CACHE_DIR=/tmp/uv-cache

# Copy the dependency layer from the builder
COPY --from=builder /src/uv.lock /src/pyproject.toml /app/
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-group dev

# Copy application source and config
COPY --from=builder /src/src/ /app/src/
COPY --from=builder /src/migrations/ /app/migrations/
COPY --from=builder /src/scripts/ /app/scripts/
COPY --from=builder /src/docker/ /app/docker/
COPY --from=builder /src/alembic.ini /app/alembic.ini

# Create non-root user
RUN addgroup --system app && \
    adduser --system --ingroup app app && \
    mkdir -p /tmp/uv-cache && \
    chown -R app:app /app /tmp/uv-cache

USER app
EXPOSE 8000

# The entrypoint.sh script runs database migrations then starts the FastAPI server
ENTRYPOINT ["sh", "docker/entrypoint.sh"]
