# ==========================================
# 阶段 1: 构建阶段 (Builder)
# ==========================================
FROM ubuntu:22.04 AS builder

ENV DEBIAN_FRONTEND=noninteractive

# 安装基础依赖
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    ca-certificates \
    gnupg \
    && rm -rf /var/lib/apt/lists/*

# 安装 Node.js 22
RUN mkdir -p /etc/apt/keyrings \
    && curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg \
    && echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_22.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list \
    && apt-get update && apt-get install -y nodejs --no-install-recommends \
    && rm -rf /var/lib/apt/lists/*

# 安装 uv 并利用 uv 下载 Python 3.11
ENV UV_INSTALL_DIR=/opt/uv
RUN curl -LsSf https://astral.sh/uv/install.sh | sh \
    && /opt/uv/uv python install 3.11


# ==========================================
# 阶段 2: 最终运行阶段 (Final)
# ==========================================
FROM ubuntu:22.04

ENV DEBIAN_FRONTEND=noninteractive

# 安装 ripgrep 工具
COPY ripgrep-15.1.0-x86_64-unknown-linux-musl.tar.gz /tmp/
RUN tar -xzf /tmp/ripgrep-15.1.0-x86_64-unknown-linux-musl.tar.gz -C /opt && \
    ln -s /opt/ripgrep-15.1.0-x86_64-unknown-linux-musl/rg /usr/local/bin/rg
RUN rg --version


# 1. 干净地为最终镜像配置 Node.js 22 环境
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    ca-certificates \
    gnupg \
    git \
    && mkdir -p /etc/apt/keyrings \
    && curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg \
    && echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_22.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list \
    && apt-get update && apt-get install -y nodejs --no-install-recommends \
    && apt-get purge -y curl gnupg \
    && apt-get autoremove -y \
    && rm -rf /var/lib/apt/lists/*

# 2. 从 builder 复制 uv 和由 uv 管理的 Python 3.11
COPY --from=builder /opt/uv/uv /usr/local/bin/uv
COPY --from=builder /root/.local/share/uv/python /root/.local/share/uv/python
RUN uv --version
RUN uv venv /opt/venv --python 3.11
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt /tmp/requirements.txt
RUN uv pip install \
    --index-url https://pypi.tuna.tsinghua.edu.cn/simple/ \
    --requirements /tmp/requirements.txt

# 3. 在最终镜像中用正规的 npm 安装 opencode-ai，确保系统全局软链接生成完整
RUN npm install -g opencode-ai && npm cache clean --force
RUN opencode --version

COPY skills /root/.config/opencode/skills

ENTRYPOINT ["opencode"]
