#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
TEMPLATE_DIR="$SCRIPT_DIR/template_shiny_post"

usage() {
  echo "Usage: $0 <project_folder_name> [project_title]"
  echo "Example: $0 tariff_story_2026 \"Tariffs and Wages in 2026\""
}

if [[ $# -lt 1 || $# -gt 2 ]]; then
  usage
  exit 1
fi

project_name="$1"
project_title="${2:-}"

target_dir="$SCRIPT_DIR/$project_name"

if [[ ! -d "$TEMPLATE_DIR" ]]; then
  echo "Template folder not found: $TEMPLATE_DIR" >&2
  exit 1
fi

if [[ -e "$target_dir" ]]; then
  echo "Target already exists: $target_dir" >&2
  exit 1
fi

if [[ -z "$project_title" ]]; then
  project_title="$(printf '%s' "$project_name" | tr '_-' ' ' | perl -pe 's/\b([a-z])/\U$1/g')"
fi

cp -R "$TEMPLATE_DIR" "$target_dir"

export PROJECT_TITLE="$project_title"

perl -0pi -e 's/\[Project Title\]/$ENV{PROJECT_TITLE}/g' \
  "$target_dir/text.txt"

perl -0pi -e 's/^# Template Shiny Post/# $ENV{PROJECT_TITLE}/m' \
  "$target_dir/README.md"

cat <<EOF
Created new project at: $target_dir
Title set to: $project_title

Next steps:
1. Edit $project_name/text.txt
2. Replace placeholder charts in $project_name/process.r
3. Run: cd $project_name && R -e "shiny::runApp()"
EOF
