# syntax=docker/dockerfile:1

# ── Stage 1: Build Python agent deps with uv ───────────────────────────────
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS build

ENV PYTHONUNBUFFERED=1
ENV UV_COMPILE_BYTECODE=1

WORKDIR /app

# Install build tools for native extensions (azure-cognitiveservices-speech)
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc g++ python3-dev libasound2-dev \
    && rm -rf /var/lib/apt/lists/*

COPY agent/pyproject.toml ./agent/
RUN cd /app/agent && \
    uv venv .venv && \
    uv pip install --python .venv/bin/python \
        "livekit-agents~=1.7" \
        "livekit-plugins-azure~=1.7" \
        "livekit-plugins-openai~=1.7" \
        "python-dotenv"

# ── Stage 2: Runtime (use same base for Python compat) ─────────────────────
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS runtime

ENV PYTHONUNBUFFERED=1

# Install LiveKit server binary + supervisord + nginx
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl ca-certificates supervisor nginx libasound2 \
    && rm -rf /var/lib/apt/lists/*

# Download LiveKit server (latest stable)
ARG LIVEKIT_VERSION=v1.13.5
ARG LIVEKIT_TAG=1.13.5
RUN curl -sSL "https://github.com/livekit/livekit/releases/download/${LIVEKIT_VERSION}/livekit_${LIVEKIT_TAG}_linux_amd64.tar.gz" \
    | tar xz -C /usr/local/bin/ livekit-server \
    && chmod +x /usr/local/bin/livekit-server \
    && ln -sf /usr/local/bin/livekit-server /usr/local/bin/livekit

# Copy Python agent + venv from build stage
COPY --from=build /app/agent/.venv /opt/voice-agent/.venv
COPY agent/agent.py /opt/voice-agent/agent.py

# Copy web frontend
COPY web/ /var/www/voice/

# Config files
COPY livekit.yaml /etc/livekit.yaml
COPY supervisord.conf /etc/supervisor/conf.d/voice.conf

# Configure nginx to serve the voice UI on port 8090
RUN rm -f /etc/nginx/sites-enabled/default \
    && printf 'server {\n    listen 8090;\n    root /var/www/voice;\n    index index.html;\n    location / {\n        try_files $uri $uri/ =404;\n    }\n}\n' \
    > /etc/nginx/sites-available/voice \
    && ln -sf /etc/nginx/sites-available/voice /etc/nginx/sites-enabled/voice

# Create non-root user for agent
RUN useradd -m -s /bin/bash voiceuser || true

EXPOSE 7880 7881 8090 50000-60000/udp

CMD ["supervisord", "-n", "-c", "/etc/supervisor/conf.d/voice.conf"]
