#!/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"

PROJECT_NAME="${1:-}"
OS="$(uname -s)"
TARGET_BASE=""
PROJECT_PATH=""

PROJECT_SCOPE=""
PROJECT_STACK=""
PROJECT_STATE="dev"

if [ -z "$PROJECT_NAME" ]; then
  echo "Usage: mkproj <nom_du_projet>"
  exit 1
fi

choose_mac_target_base() {
  echo "Environnement détecté : Mac"
  echo "Choisir le type de projet :"
  echo "  1) Projet perso      -> /Volumes/TeraSSD/Projets_Dev"
  echo "  2) Projet Mindleaf   -> /Volumes/TeraSSD/Projets_Dev/__Mindleaf"
  echo "  3) Projet lab        -> /Volumes/TeraSSD/Labs"
  echo "  4) Projet archive    -> /Volumes/TeraSSD/Archives_Projets"
  printf "Votre choix [1/2/3/4] : "
  read -r choice

  case "$choice" in
    1)
      PROJECT_SCOPE="perso"
      TARGET_BASE="/Volumes/TeraSSD/Projets_Dev"
      ;;
    2)
      PROJECT_SCOPE="mindleaf"
      TARGET_BASE="/Volumes/TeraSSD/Projets_Dev/__Mindleaf"
      ;;
    3)
      PROJECT_SCOPE="lab"
      TARGET_BASE="/Volumes/TeraSSD/Labs"
      ;;
    4)
      PROJECT_SCOPE="archive"
      TARGET_BASE="/Volumes/TeraSSD/Archives_Projets"
      ;;
    *)
      echo "Choix invalide."
      exit 1
      ;;
  esac
}

choose_target_base() {
  case "$OS" in
    Linux)
      echo "Environnement détecté : NUC/Linux"
      TARGET_BASE="/srv/projects"
      echo "Choisir le scope logique du projet :"
      echo "  1) perso"
      echo "  2) mindleaf"
      echo "  3) lab"
      echo "  4) archive"
      printf "Votre choix [1/2/3/4] : "
      read -r choice

      case "$choice" in
        1) PROJECT_SCOPE="perso" ;;
        2) PROJECT_SCOPE="mindleaf" ;;
        3) PROJECT_SCOPE="lab" ;;
        4) PROJECT_SCOPE="archive" ;;
        *)
          echo "Choix invalide."
          exit 1
          ;;
      esac
      ;;
    Darwin)
      choose_mac_target_base
      ;;
    *)
      echo "Système non supporté : $OS"
      exit 1
      ;;
  esac
}

prompt_project_metadata() {
  printf "Stack principale [à préciser] : "
  read -r PROJECT_STACK
  PROJECT_STACK="${PROJECT_STACK:-à préciser}"

  printf "État du projet [dev] : "
  read -r PROJECT_STATE
  PROJECT_STATE="${PROJECT_STATE:-dev}"
}

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

  if grep -Eq "^${PROJECT_NAME}\|" "$PROJECTS_CONF"; then
    echo "Erreur : le projet $PROJECT_NAME existe déjà dans _projects.conf" >&2
    exit 1
  fi

  printf "%s|%s|%s|%s\n" "$PROJECT_NAME" "$PROJECT_STACK" "$PROJECT_SCOPE" "$PROJECT_STATE" >> "$PROJECTS_CONF"
}

create_readme() {
  cat <<EOF > "$PROJECT_PATH/README.md"
# $PROJECT_NAME

Projet initialisé avec l'environnement Lead_tech.

## Structure attendue

- \`CLAUDE.md\` : mémoire active du projet
- \`AGENTS.md\` : symlink vers \`CLAUDE.md\`
- \`README.md\` : documentation projet
- \`.gitignore\` : exclusions Git de base
- \`_projects.conf\` (Lead_tech) : registre logique des projets

## Commandes utiles

\`\`\`bash
# Initialiser la mémoire projet
 gen-claude

# Démarrer la stack Docker
 docker compose up -d
\`\`\`
EOF
}

create_gitignore() {
  local with_bmad="${1:-false}"
  cat <<'EOF' > "$PROJECT_PATH/.gitignore"
# dependencies
node_modules/

# logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*

# env
.env
.env.*
!.env.example

# build outputs
dist/
build/
coverage/
.next/
out/

# editors / OS
.DS_Store
.vscode/
.idea/

# local runtime data
.tmp/
tmp/

# Agent compatibility file (symlink to CLAUDE.md)
AGENTS.md
EOF

  if [ "$with_bmad" = "false" ]; then
    cat <<'EOF' >> "$PROJECT_PATH/.gitignore"

# AI tools
.claude/
.codex/
EOF
  else
    cat <<'EOF' >> "$PROJECT_PATH/.gitignore"

# AI tools (BMAD : .claude et .agents sont des symlinks centralisés, non versionnés)
.claude
.agents
.codex/

# BMAD artefacts locaux (versionnés séparément si besoin)
_bmad-output/
EOF
  fi
}

choose_target_base
prompt_project_metadata

printf "Initialiser BMAD ? [o/N] : "
read -r bmad_choice
USE_BMAD="false"
if [[ "$bmad_choice" =~ ^[oO]$ ]]; then
  USE_BMAD="true"
fi

if [ ! -d "$TARGET_BASE" ]; then
  echo "Le dossier cible n'existe pas : $TARGET_BASE"
  exit 1
fi

PROJECT_PATH="$TARGET_BASE/$PROJECT_NAME"

if [ -e "$PROJECT_PATH" ]; then
  echo "Le dossier existe déjà : $PROJECT_PATH"
  exit 1
fi

mkdir -p "$PROJECT_PATH"
cd "$PROJECT_PATH"

git init

create_readme
create_gitignore "$USE_BMAD"

if [ "$USE_BMAD" = "true" ]; then
  "$SCRIPT_DIR/bmad-init-project.sh" "$PROJECT_PATH"
else
  gen-claude "$PROJECT_NAME"
fi

register_project_in_conf

echo ""
echo "Projet créé : $PROJECT_PATH"
echo "Projet enregistré dans : $PROJECTS_CONF"
echo ""
echo "Prochaines étapes :"
echo "  cd $PROJECT_PATH"
echo "  git remote add origin <repo>"
echo "  docker compose up -d"