# Multi-stage build for Home Assistant MCP Server
FROM node:20-alpine AS builder

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./
COPY tsconfig.json ./

# Copy source code (needed before npm ci because prepare script builds)
COPY src ./src

# Install dependencies and build
# The prepare script will automatically run npm run build
RUN npm ci

# Production stage
FROM node:20-alpine

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install production dependencies only
# Use --ignore-scripts because prepare script requires TypeScript (dev dependency)
# The built code is copied from builder stage, so no need to build again
RUN npm ci --omit=dev --ignore-scripts

# Copy built application from builder stage
COPY --from=builder /app/build ./build

# Create non-root user for security
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nodejs -u 1001 && \
    chown -R nodejs:nodejs /app

# Switch to non-root user
USER nodejs

# Set environment variables with defaults
ENV NODE_ENV=production
ENV HA_BASE_URL=""
ENV HA_ACCESS_TOKEN=""

# Expose stdio for MCP communication
# Note: MCP servers communicate via stdio, not network ports
# Healthchecks are not applicable for stdio-based servers

# Start the MCP server
CMD ["node", "build/index.js"]
