# Build stage
FROM python:3.12-slim as builder

WORKDIR /tmp/build

# Install system dependencies for building
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    libxml2-dev \
    libxslt1-dev \
    && rm -rf /var/lib/apt/lists/*

# Copy source files
COPY pyproject.toml ./
COPY finn_eiendom ./finn_eiendom
COPY README.md ./

# Create virtual environment and install dependencies
RUN python -m venv /venv && \
    /venv/bin/pip install --upgrade pip setuptools wheel && \
    /venv/bin/pip install . --no-cache-dir

# Runtime stage
FROM python:3.12-slim

WORKDIR /app

# Install runtime system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    libxml2 \
    libxslt1.1 \
    && rm -rf /var/lib/apt/lists/*

# Copy virtual environment from builder
COPY --from=builder /venv /venv

# Copy application code
COPY finn_eiendom /app/finn_eiendom

# Set environment variables
ENV PATH="/venv/bin:$PATH" \
    PYTHONUNBUFFERED=1 \
    MCP_HOST=0.0.0.0 \
    MCP_PORT=8010 \
    FINN_CACHE_PATH=/app/data/finn.sqlite

RUN mkdir -p /app/data

# Expose HTTP port
EXPOSE 8010

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
    CMD python -c "import requests; requests.get('http://localhost:8010/health', timeout=5)" || exit 1

# Run the MCP HTTP server
CMD ["python", "-m", "finn_eiendom.http_server"]
