FROM ubuntu:22.04

ENV DEBIAN_FRONTEND=noninteractive
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# System deps: Xvfb (virtual display), fonts, browser libs
RUN apt-get update && apt-get install -y --no-install-recommends \
    python3 python3-pip python3-venv \
    xvfb xauth \
    # Fonts — realistic fingerprint, cover Windows + Mac + Linux families
    fonts-liberation fonts-noto fonts-dejavu-core fonts-freefont-ttf \
    fonts-noto-cjk fonts-noto-color-emoji \
    # Browser runtime deps (Firefox/Camoufox needs these)
    libgtk-3-0 libdbus-glib-1-2 libxt6 libx11-xcb1 \
    libasound2 libpci3 libxcomposite1 libxdamage1 libxrandr2 \
    libxkbcommon0 libgbm1 libpango-1.0-0 libcairo2 libatk1.0-0 \
    # Networking tools (debug)
    curl ca-certificates \
    # noVNC — manual intervention hatch
    supervisor x11vnc novnc python3-websockify \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Upgrade pip + packaging first (hatchling needs packaging>=23)
RUN pip3 install --no-cache-dir --upgrade pip packaging

# Install Python deps first (layer cache)
COPY pyproject.toml /app/
RUN pip3 install --no-cache-dir \
    "camoufox>=0.4" \
    "playwright>=1.40" \
    "httpx>=0.25" \
    "capsolver" \
    "flask>=3.0" \
    && pip3 install --no-cache-dir -e /app 2>/dev/null || true

# Download Camoufox browser binary (must succeed — no runtime fetch)
RUN python3 -m camoufox fetch

# Copy Fantoma source
COPY . /app

# Install Fantoma properly
RUN pip3 install --no-cache-dir -e ".[captcha]"

# Xvfb display setup
ENV DISPLAY=:99

# Create dirs Fantoma expects
RUN mkdir -p /root/.local/share/fantoma/traces \
    /root/.local/share/fantoma/sessions \
    /root/.local/share/fantoma/form_memory \
    /var/log/supervisor

# supervisord config
COPY supervisord.conf /etc/supervisor/conf.d/fantoma.conf

EXPOSE 7860 6080

# supervisord manages all processes
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"]
