#!/bin/bash
cd /Users/pierre/dev/geosector/app

# Charger les variables d'environnement
if [ ! -f .env-deploy-dev ]; then
    echo "❌ Fichier .env-deploy-dev manquant"
    exit 1
fi
source .env-deploy-dev

# Fonction pour gérer les erreurs
error_exit() {
    echo "❌ $1"
    exit 1
}

# Construction de l'application Flutter
echo "🧹 Cleaning previous builds..."
flutter clean || error_exit "Flutter clean failed"

echo "📦 Getting dependencies..."
flutter pub get || error_exit "Flutter pub get failed"

# Nettoyage et génération du code
echo "🗑️ Cleaning generated files..."
dart pub run build_runner clean || error_exit "Build runner clean failed"

echo "🔨 Generating code files..."
dart pub run build_runner build --delete-conflicting-outputs || error_exit "Code generation failed"

# Construction de l'application Flutter
echo "🏗️ Building Flutter web application..."
flutter build web --release || error_exit "Flutter build failed"

echo "🖼️ Fixing web assets structure..."
./copy-web-images.sh || error_exit "Failed to fix web assets"

echo "✅ Build completed successfully!"

# Préparation de la commande SSH pour le host
SSH_HOST_CMD="ssh -i $HOST_SSH_KEY -p $HOST_SSH_PORT $HOST_SSH_USER@$HOST_SSH_HOST"

# Préparation du chemin temporaire sur le host
TEMP_DIR="/tmp/geosector-deploy-$(date +%s)"

echo "📤 Copie des fichiers vers le host temporairement..."
rsync -rltz --delete \
    -e "ssh -i $HOST_SSH_KEY -p $HOST_SSH_PORT" \
    $FLUTTER_BUILD_DIR/ \
    $HOST_SSH_USER@$HOST_SSH_HOST:$TEMP_DIR/ || error_exit "Transfert vers le host échoué"

echo "🔄 Transfert des fichiers du host vers le container..."
$SSH_HOST_CMD "sudo incus project switch $INCUS_PROJECT && sudo incus file push -r $TEMP_DIR/* $INCUS_CONTAINER$DEPLOY_TARGET_DIR/" || error_exit "Transfert vers le container échoué"

echo "🧹 Nettoyage du répertoire temporaire sur le host..."
$SSH_HOST_CMD "rm -rf $TEMP_DIR"

echo "🔒 Configuration des permissions dans le container..."
$SSH_HOST_CMD "sudo incus project switch $INCUS_PROJECT && sudo incus exec $INCUS_CONTAINER -- chown -R www-data:www-data $DEPLOY_TARGET_DIR" || error_exit "Configuration des permissions échouée"

echo "✅ Déploiement terminé avec succès à $(date '+%H:%M:%S') !"
