#!/bin/bash
set -euo pipefail
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
RESOURCES="$SCRIPT_DIR/../Resources"
VENV_DIR="$HOME/.dictascribe/venv"
LOG_FILE="$HOME/.dictascribe/launch.log"
mkdir -p "$HOME/.dictascribe"
exec > "$LOG_FILE" 2>&1

alert() { osascript -e "display dialog \"$1\" with title \"DictaScribe\" buttons {\"OK\"} default button \"OK\" with icon caution" 2>/dev/null || true; }
info() { osascript -e "display notification \"$1\" with title \"DictaScribe\"" 2>/dev/null || true; }

if ! command -v python3 &>/dev/null; then
    alert "Python 3 requis. DictaScribe va installer les outils Apple."
    xcode-select --install 2>/dev/null || true
    for i in $(seq 1 120); do command -v python3 &>/dev/null && break; sleep 5; done
    if ! command -v python3 &>/dev/null; then
        alert "Python 3 introuvable. Installez-le depuis python.org"
        exit 1
    fi
fi

if [ ! -f "$VENV_DIR/bin/python3" ]; then
    info "Première installation..."
    python3 -m venv "$VENV_DIR"
    "$VENV_DIR/bin/pip" install --quiet --upgrade pip 2>/dev/null || true
    "$VENV_DIR/bin/pip" install --quiet flask pypdf || {
        alert "Erreur d'installation. Vérifiez votre connexion internet."
        exit 1
    }
else
    "$VENV_DIR/bin/python3" -c "import flask" 2>/dev/null || "$VENV_DIR/bin/pip" install --quiet flask pypdf 2>/dev/null
fi

cd "$RESOURCES"
export DICTASCRIBE_APP_LAUNCHER=1
info "DictaScribe démarre..."
(sleep 2 && open "http://localhost:5124") &
"$VENV_DIR/bin/python3" app.py

EXIT_CODE=$?
if [ $EXIT_CODE -ne 0 ]; then
    alert "DictaScribe erreur (code $EXIT_CODE). Log: $LOG_FILE"
fi
