#!/bin/bash
# new-article — Creates a new article from a title and opens it in vim

set -e

if [ -z "$1" ]; then
  echo "Usage: $0 \"Article Title\""
  echo "Example: $0 \"The Telos of Test Automation\""
  exit 1
fi

TITLE="$1"
DATE=$(date +%Y-%m-%d)
SLUG=$(echo "$TITLE" | tr '[:upper:]' '[:lower:]' | sed -e 's/[^a-z0-9]/-/g' -e 's/--*/-/g' -e 's/^-//g' -e 's/-$//g')
FILENAME="articles/drafts/${SLUG}.md"
TEMPLATE="scripts/article-template.md"

if [ ! -f "$TEMPLATE" ]; then
  echo "Error: Template $TEMPLATE not found."
  exit 1
fi

if [ -f "$FILENAME" ]; then
  echo "Error: $FILENAME already exists."
  exit 1
fi

# Generate the file from template
sed -e "s/{{TITLE}}/$TITLE/g" -e "s/{{DATE}}/$DATE/g" "$TEMPLATE" > "$FILENAME"

echo "Created $FILENAME"

# Open in vim (fallback to vi)
if command -v vim >/dev/null 2>&1; then
  vim "$FILENAME"
else
  vi "$FILENAME"
fi
