#!/bin/bash
# {{ name }} - Create New {{ entity_type | default('Feature') }} Script
# Generated by MetaSpec

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
ENTITY_TYPE="{{ entity_type | default('Feature') }}"
ENTITY_TYPE_LOWER="{{ entity_type | lower | default('feature') }}"
SPECS_DIR="{{ specs_dir | default('specs') }}"
CLI_PREFIX="{{ cli_prefix | default('metaspec') }}"

# Variables
FEATURE_NAME=""
AUTO_INCREMENT=true

# Usage
usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -n, --name NAME      ${ENTITY_TYPE} name (e.g., 'user-auth')"
    echo "  -i, --id ID          Explicit ${ENTITY_TYPE_LOWER} ID (e.g., '002')"
    echo "  -h, --help           Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 --name user-auth"
    echo "  $0 --name api-integration --id 005"
    exit 1
}

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -n|--name)
            FEATURE_NAME="$2"
            shift 2
            ;;
        -i|--id)
            FEATURE_ID="$2"
            AUTO_INCREMENT=false
            shift 2
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo -e "${RED}Error: Unknown option $1${NC}"
            usage
            ;;
    esac
done

# Check if feature name is provided
if [ -z "$FEATURE_NAME" ]; then
    echo -e "${YELLOW}Enter ${ENTITY_TYPE_LOWER} name (e.g., 'user-auth'):${NC}"
    read -r FEATURE_NAME
    
    if [ -z "$FEATURE_NAME" ]; then
        echo -e "${RED}Error: ${ENTITY_TYPE} name is required${NC}"
        exit 1
    fi
fi

# Auto-increment feature ID if not specified
if [ "$AUTO_INCREMENT" = true ]; then
    # Find the highest existing feature number
    HIGHEST_NUM=$(find "$SPECS_DIR" -maxdepth 1 -type d -name '[0-9]*-*' 2>/dev/null | \
        sed 's/.*\/\([0-9]*\)-.*/\1/' | \
        sort -n | \
        tail -1)
    
    if [ -z "$HIGHEST_NUM" ]; then
        FEATURE_ID="001"
    else
        FEATURE_ID=$(printf "%03d" $((10#$HIGHEST_NUM + 1)))
    fi
fi

# Create feature directory name
FEATURE_DIR="${SPECS_DIR}/${FEATURE_ID}-${FEATURE_NAME}"

# Check if directory already exists
if [ -d "$FEATURE_DIR" ]; then
    echo -e "${RED}Error: ${ENTITY_TYPE} directory already exists: $FEATURE_DIR${NC}"
    exit 1
fi

# Create feature directory
echo -e "${BLUE}Creating ${ENTITY_TYPE_LOWER}: ${FEATURE_ID}-${FEATURE_NAME}${NC}"
mkdir -p "$FEATURE_DIR"

# Check if template exists
TEMPLATE_FILE=".metaspec/templates/spec-template.md"
if [ ! -f "$TEMPLATE_FILE" ]; then
    echo -e "${RED}Error: Template file not found: $TEMPLATE_FILE${NC}"
    echo -e "${YELLOW}Creating spec.md with basic structure...${NC}"
    
    # Fallback: create basic spec.md
    cat > "$FEATURE_DIR/spec.md" << EOF
# ${FEATURE_NAME} - Specification

> **Status**: 🟡 Draft | **Priority**: Medium | **Created**: $(date +%Y-%m-%d)

---

## 📋 Overview

[Describe what this ${ENTITY_TYPE_LOWER} does and why it's needed]

---

## 🎯 Goals & Success Criteria

### Primary Goals
1. [Goal 1]
2. [Goal 2]

### Success Criteria
- [ ] [Criterion 1]
- [ ] [Criterion 2]

---

## 📝 Next Steps

Run \`/${CLI_PREFIX}.plan\` to create implementation plan
EOF
else
    # Copy template and replace placeholders
    cp "$TEMPLATE_FILE" "$FEATURE_DIR/spec.md"
    
    # Replace [NAME] with actual name (capitalize words)
    FEATURE_TITLE=$(echo "$FEATURE_NAME" | sed 's/-/ /g' | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2));}1')
    sed -i.bak "s/\[NAME\]/$FEATURE_TITLE/g" "$FEATURE_DIR/spec.md"
    
    # Replace [Date] with current date
    CURRENT_DATE=$(date +%Y-%m-%d)
    sed -i.bak "s/\[Date\]/$CURRENT_DATE/g" "$FEATURE_DIR/spec.md"
    
    # Clean up backup file
    rm -f "$FEATURE_DIR/spec.md.bak"
fi

# Success message
echo -e "${GREEN}✓ Created ${ENTITY_TYPE_LOWER}: $FEATURE_DIR${NC}"
echo ""
echo -e "${BLUE}Next steps:${NC}"
echo "  1. Edit $FEATURE_DIR/spec.md"
echo "  2. Run: /${CLI_PREFIX}.plan"
echo "  3. Run: /${CLI_PREFIX}.tasks"
echo "  4. Run: /${CLI_PREFIX}.generate"
echo ""
echo -e "${YELLOW}Tip: Use /${CLI_PREFIX}.specify to let AI help define the specification${NC}"

