FROM smanx/opencode:latest AS base
USER root
ARG UBUNTU_APT_MIRROR=
ARG PYPI_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
ARG PYPI_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn
ENV VIRTUAL_ENV=/opt/venv
ENV PATH="$VIRTUAL_ENV/bin:/root/.local/bin:$PATH"
ENV PIP_INDEX_URL=${PYPI_INDEX_URL}
ENV PIP_TRUSTED_HOST=${PYPI_TRUSTED_HOST}
ENV UV_INDEX_URL=${PYPI_INDEX_URL}

COPY vendor/bun-linux-x64.zip /tmp/bun.zip

RUN if [ -n "${UBUNTU_APT_MIRROR}" ]; then \
      sed -i "s|http://archive.ubuntu.com|https://${UBUNTU_APT_MIRROR}|g; s|http://security.ubuntu.com|https://${UBUNTU_APT_MIRROR}|g" /etc/apt/sources.list 2>/dev/null || true; \
      sed -i "s|http://archive.ubuntu.com|https://${UBUNTU_APT_MIRROR}|g; s|http://security.ubuntu.com|https://${UBUNTU_APT_MIRROR}|g" /etc/apt/sources.list.d/*.sources 2>/dev/null || true; \
    fi && \
    apt-get update && apt-get install -y --no-install-recommends \
    curl \
    jq \
    unzip \
    python3 \
    python3-venv && \
    unzip -q /tmp/bun.zip -d /usr/local && \
    mv /usr/local/bun-linux-x64 /usr/local/bun && \
    ln -sf /usr/local/bun/bun /usr/local/bin/bun && \
    rm -f /tmp/bun.zip && \
    curl -LsSf https://astral.sh/uv/install.sh | sh && \
    ln -s /root/.local/bin/uv /usr/local/bin/uv && \
    ln -sf /usr/bin/python3 /usr/local/bin/python && \
    mkdir -p /root/.config/pip && \
    printf "[global]\nindex-url = %s\ntrusted-host = %s\n" "$PIP_INDEX_URL" "$PIP_TRUSTED_HOST" > /root/.config/pip/pip.conf && \
    uv venv "$VIRTUAL_ENV" && \
    uv pip install --python "$VIRTUAL_ENV/bin/python" \
    --index-url "$UV_INDEX_URL" \
    pip \
    setuptools \
    wheel \
    requests \
    httpx \
    pydantic \
    python-dotenv \
    rich \
    ipython \
    pytest && \
    rm -rf /var/lib/apt/lists/*

FROM base AS deps

WORKDIR /app

COPY package.json bun.lock ./
COPY .opencode/package.json .opencode/bun.lock ./.opencode/
RUN bun install --frozen-lockfile

FROM base AS build
WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/.opencode/node_modules ./.opencode/node_modules
COPY tsconfig.json opencode.json README.md .gitignore ./
COPY src ./src
COPY cli ./cli
COPY .opencode ./.opencode
RUN bun run check

FROM base AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=8787
ENV TJWATER_CLI_PATH=./cli/tjwater-cli

COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/.opencode/node_modules ./.opencode/node_modules
COPY package.json bun.lock ./
COPY tsconfig.json opencode.json .gitignore ./
COPY src ./src
COPY .opencode ./.opencode
COPY cli ./cli

COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh ./cli/tjwater-cli

ENTRYPOINT ["/entrypoint.sh"]

EXPOSE 8787
CMD ["bun", "src/server.ts"]
