#!/usr/bin/env bash

set -euo pipefail

# If no arguments are provided, infer project name and path from current directory
if [ $# -eq 0 ]; then
  PROJECT_PATH="$(pwd)"
  PROJECT_NAME="$(basename "$PROJECT_PATH")"

# If one argument is provided, treat it as the project name and use current directory
elif [ $# -eq 1 ]; then
  PROJECT_NAME="$1"
  PROJECT_PATH="$(pwd)"

# If two arguments are provided, keep explicit behaviour
elif [ $# -eq 2 ]; then
  PROJECT_NAME="$1"
  PROJECT_PATH="$2"

else
  echo "Usage:"
  echo "generate_project_claude.sh"
  echo "generate_project_claude.sh <project_name>"
  echo "generate_project_claude.sh <project_name> <project_path>"
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEMPLATE="$SCRIPT_DIR/../70_templates/projet_CLAUDE.md"

OUTPUT="$PROJECT_PATH/CLAUDE.md"

if [ ! -f "$TEMPLATE" ]; then
  echo "Template introuvable : $TEMPLATE"
  exit 1
fi

mkdir -p "$PROJECT_PATH"
if [ -e "$PROJECT_PATH/CLAUDE.md" ]; then
  echo "Erreur : $PROJECT_PATH/CLAUDE.md existe déjà" >&2
  exit 1
fi

sed "s/{{PROJECT_NAME}}/${PROJECT_NAME}/g" "$TEMPLATE" > "$OUTPUT"

if [ -e "$PROJECT_PATH/AGENTS.md" ] || [ -L "$PROJECT_PATH/AGENTS.md" ]; then
  rm -f "$PROJECT_PATH/AGENTS.md"
fi
ln -s CLAUDE.md "$PROJECT_PATH/AGENTS.md"

echo "✔ CLAUDE.md créé : $OUTPUT"
echo "✔ AGENTS.md -> CLAUDE.md"