#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PROJECTS_CONF="$REPO_ROOT/_projects.conf"
OS="$(uname -s)"
PROJECT_NAME="${1:-}"

usage() {
  echo "Usage: resolve-project-path.sh <nom_du_projet>" >&2
}

if [ -z "$PROJECT_NAME" ]; then
  usage
  exit 1
fi

if [ ! -f "$PROJECTS_CONF" ]; then
  echo "Erreur : fichier introuvable : $PROJECTS_CONF" >&2
  exit 1
fi

resolve_base_path() {
  local scope="$1"

  case "$OS" in
    Linux)
      case "$scope" in
        perso|mindleaf|lab|archive)
          echo "/srv/projects"
          ;;
        *)
          echo "Erreur : scope inconnu sur Linux : $scope" >&2
          exit 1
          ;;
      esac
      ;;
    Darwin)
      case "$scope" in
        perso)
          echo "/Volumes/TeraSSD/Projets_Dev"
          ;;
        mindleaf)
          echo "/Volumes/TeraSSD/Projets_Dev/__Mindleaf"
          ;;
        lab)
          echo "/Volumes/TeraSSD/Labs"
          ;;
        archive)
          echo "/Volumes/TeraSSD/Archives_Projets"
          ;;
        *)
          echo "Erreur : scope inconnu sur macOS : $scope" >&2
          exit 1
          ;;
      esac
      ;;
    *)
      echo "Erreur : système non supporté : $OS" >&2
      exit 1
      ;;
  esac
}

while IFS='|' read -r name stack scope state; do
  [[ -z "$name" || "$name" == \#* ]] && continue

  if [ "$name" = "$PROJECT_NAME" ]; then
    BASE_PATH="$(resolve_base_path "$scope")"
    echo "$BASE_PATH/$name"
    exit 0
  fi
done < "$PROJECTS_CONF"

echo "Erreur : projet introuvable dans _projects.conf : $PROJECT_NAME" >&2
exit 1