_detect_cpu() {
    # Detect CPU capabilities and symlink appropriate binary
    if grep -q avx512f /proc/cpuinfo 2>/dev/null; then
        ln -sf /usr/lib/voxtype/voxtype-avx512 /usr/bin/voxtype
        echo "avx512"
    else
        ln -sf /usr/lib/voxtype/voxtype-avx2 /usr/bin/voxtype
        echo "avx2"
    fi
}

_detect_gpu() {
    # Detect GPU for Vulkan acceleration recommendation
    GPU_DETECTED=""
    if [ -d /dev/dri ]; then
        if ls /dev/dri/renderD* >/dev/null 2>&1; then
            if command -v lspci >/dev/null 2>&1; then
                GPU_INFO=$(lspci 2>/dev/null | grep -i 'vga\|3d\|display' | head -1 | sed 's/.*: //')
                if [ -n "$GPU_INFO" ]; then
                    GPU_DETECTED="$GPU_INFO"
                fi
            fi
            if [ -z "$GPU_DETECTED" ]; then
                GPU_DETECTED="GPU detected (install pciutils for details)"
            fi
        fi
    fi

    if [ -n "$GPU_DETECTED" ]; then
        echo ""
        echo "    GPU detected: $GPU_DETECTED"
        echo ""
        echo "    For GPU acceleration (faster inference), run:"
        echo "      sudo voxtype setup gpu --enable"
        echo ""
        echo "    Requires: vulkan-icd-loader package"
    fi
}

post_install() {
    echo ""
    echo "==> Voxtype Post-installation Steps:"
    echo ""

    CPU_VARIANT=$(_detect_cpu)
    echo "    CPU backend: $CPU_VARIANT (using voxtype-$CPU_VARIANT)"

    _detect_gpu

    echo ""
    echo "    1. Add your user to the 'input' group:"
    echo "       sudo usermod -aG input \$USER"
    echo ""
    echo "    2. Log out and back in for group changes to take effect"
    echo ""
    echo "    3. Download a whisper model:"
    echo "       voxtype setup --download"
    echo ""
    echo "    4. Start voxtype:"
    echo "       systemctl --user enable --now voxtype"
    echo "       Or run manually: voxtype"
    echo ""
}

post_upgrade() {
    echo ""
    echo "==> Voxtype upgraded"
    echo ""

    CPU_VARIANT=$(_detect_cpu)
    echo "    CPU backend: $CPU_VARIANT (using voxtype-$CPU_VARIANT)"

    _detect_gpu

    echo ""
    echo "    New in 0.4.1-8:"
    echo "      - Clean binaries: no AVX-512/GFNI instruction contamination"
    echo "      - Fixes SIGILL crashes on Zen 3 and older CPUs"
    echo ""
}

post_remove() {
    rm -f /usr/bin/voxtype
}
