#!/bin/bash
# Install FaceFusion 3.x for high-quality face+hair swap.
# Clones into ~/facefusion and creates a dedicated venv at ~/facefusion-venv.
# Usage: bash tour-comfy/install_facefusion.sh
set -e

FF_DIR="${FACEFUSION_DIR:-$HOME/facefusion}"
FF_VENV="${FACEFUSION_VENV:-$HOME/facefusion-venv}"
FF_REPO="https://github.com/facefusion/facefusion"

echo "[facefusion] Installing to $FF_DIR (venv: $FF_VENV)"

# 1. Clone or update
if [ -d "$FF_DIR/.git" ]; then
    echo "[facefusion] Updating existing clone ..."
    git -C "$FF_DIR" pull --ff-only
else
    echo "[facefusion] Cloning $FF_REPO ..."
    git clone "$FF_REPO" "$FF_DIR"
fi

# 2. Create dedicated venv (avoids dependency conflicts with ComfyUI)
if [ ! -d "$FF_VENV" ]; then
    echo "[facefusion] Creating venv at $FF_VENV ..."
    python3 -m venv "$FF_VENV"
fi

PIP="$FF_VENV/bin/pip"
PY="$FF_VENV/bin/python"

"$PIP" install --upgrade pip wheel

# 3. Install FaceFusion requirements
cd "$FF_DIR"
"$PIP" install -r requirements.txt \
    --extra-index-url https://download.pytorch.org/whl/cu124

# 4. Download base models (ghost_3_1_256 + gfpgan_1.4 for enhance)
echo "[facefusion] Downloading default models via FaceFusion model manager ..."
"$PY" facefusion.py \
    --processors face_swapper hair_swapper face_enhancer \
    --face-swapper-model ghost_3_1_256 \
    --face-enhancer-model gfpgan_1.4 \
    --execution-providers cpu \
    download-models 2>/dev/null || true

echo ""
echo "[facefusion] Installation complete."
echo "  Binary: $PY $FF_DIR/facefusion.py"
echo "  Config: set facefusion_dir/facefusion_venv in tour-comfy/config.json"
echo ""
echo "Restart the API (start_api.sh) and the 'Hair swap' toggle will activate."
