ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}-slim-bookworm

ARG CLAUDE_CODE_VERSION=latest

# System dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    curl \
    sudo \
    zsh \
    fzf \
    jq \
    ripgrep \
    fd-find \
    tmux \
    make \
    iptables \
    ipset \
    iproute2 \
    dnsutils \
    aggregate \
    ca-certificates \
    gnupg \
    && apt-get clean && rm -rf /var/lib/apt/lists/*

# Install Node.js (required for Claude Code CLI)
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
    && apt-get install -y nodejs \
    && apt-get clean && rm -rf /var/lib/apt/lists/*

# Create non-root user
ARG USERNAME=dev
RUN useradd -m -s /bin/zsh ${USERNAME} \
    && echo "${USERNAME} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/${USERNAME}

# Persist command history
RUN mkdir /commandhistory \
    && touch /commandhistory/.zsh_history \
    && chown -R ${USERNAME}:${USERNAME} /commandhistory

# Create workspace and config directories
RUN mkdir -p /workspace /home/${USERNAME}/.claude \
    && chown -R ${USERNAME}:${USERNAME} /workspace /home/${USERNAME}/.claude

WORKDIR /workspace

# Switch to non-root user
USER ${USERNAME}

# Configure zsh
RUN sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended \
    && echo 'export HISTFILE=/commandhistory/.zsh_history' >> ~/.zshrc \
    && echo 'source /usr/share/doc/fzf/examples/key-bindings.zsh 2>/dev/null || true' >> ~/.zshrc

# Install uv for Python package management
RUN curl -LsSf https://astral.sh/uv/install.sh | sh \
    && echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc

ENV PATH="/home/${USERNAME}/.local/bin:${PATH}"

# Install Claude Code CLI
RUN npm install -g @anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}

# Copy firewall script
COPY init-firewall.sh /usr/local/bin/
USER root
RUN chmod +x /usr/local/bin/init-firewall.sh \
    && echo "${USERNAME} ALL=(root) NOPASSWD: /usr/local/bin/init-firewall.sh" > /etc/sudoers.d/${USERNAME}-firewall \
    && chmod 0440 /etc/sudoers.d/${USERNAME}-firewall
USER ${USERNAME}

ENV SHELL=/bin/zsh
ENV DEVCONTAINER=true
