#!/bin/bash
# {{ name }} - Setup Plan Script
# Generated by MetaSpec

set -e

# Configuration
SPECS_DIR="{{ specs_dir | default('specs') }}"
CLI_PREFIX="{{ cli_prefix | default('metaspec') }}"

# Parse options
JSON_OUTPUT=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --json)
            JSON_OUTPUT=true
            shift
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1
            ;;
    esac
done

# Detect current feature directory
if [ -n "$SPECIFY_FEATURE" ]; then
    FEATURE_DIR="${SPECS_DIR}/${SPECIFY_FEATURE}"
elif command -v git &> /dev/null && git rev-parse --git-dir > /dev/null 2>&1; then
    BRANCH=$(git branch --show-current 2>/dev/null)
    if [[ "$BRANCH" =~ ^[0-9]+-.*$ ]]; then
        FEATURE_DIR="${SPECS_DIR}/${BRANCH}"
    else
        echo "Error: Not on a feature branch. Set SPECIFY_FEATURE environment variable." >&2
        exit 1
    fi
else
    echo "Error: Cannot detect feature. Set SPECIFY_FEATURE environment variable." >&2
    exit 1
fi

# Check if feature directory exists
if [ ! -d "$FEATURE_DIR" ]; then
    echo "Error: Feature directory not found: $FEATURE_DIR" >&2
    echo "Run: /${CLI_PREFIX}.specify first" >&2
    exit 1
fi

# Check if spec.md exists
SPEC_FILE="${FEATURE_DIR}/spec.md"
if [ ! -f "$SPEC_FILE" ]; then
    echo "Error: Specification not found: $SPEC_FILE" >&2
    echo "Run: /${CLI_PREFIX}.specify first" >&2
    exit 1
fi

# Define plan file path
PLAN_FILE="${FEATURE_DIR}/plan.md"

# Check if plan already exists
if [ -f "$PLAN_FILE" ]; then
    echo "Warning: Plan already exists: $PLAN_FILE" >&2
    echo "This command will update it." >&2
fi

# Copy plan template if it exists
TEMPLATE_FILE=".metaspec/templates/plan-template.md"
if [ -f "$TEMPLATE_FILE" ]; then
    cp "$TEMPLATE_FILE" "$PLAN_FILE"
    echo "Initialized plan from template" >&2
else
    # Create basic plan structure if template not found
    cat > "$PLAN_FILE" << EOF
# Implementation Plan: [NAME]

**Date**: $(date +%Y-%m-%d)
**Spec**: [Link to spec.md]

## Summary

[Extract from specification: primary requirement + approach]

## Technical Context

**Primary Method**: [Approach or NEEDS CLARIFICATION]
**Key Dependencies**: [Dependencies or NEEDS CLARIFICATION]
**Target Environment**: [Environment or NEEDS CLARIFICATION]

## Constitution Check

*GATE: Must pass before Phase 0 research.*

[Gates determined based on constitution file]

## Structure

### Documentation (this context)

\`\`\`text
${FEATURE_DIR}/
├── spec.md              # Specification
├── plan.md              # This file
├── research.md          # Phase 0 output
├── model.md             # Phase 1 output
└── tasks.md             # Phase 2 output
\`\`\`

## Phases

### Phase 0: Research

[Research unknowns and resolve NEEDS CLARIFICATION items]

### Phase 1: Design

[Design artifacts: model, contracts, etc.]

### Phase 2: Ready for Tasks

[Complete when ready for /${CLI_PREFIX}.tasks]
EOF
    echo "Created basic plan structure" >&2
fi

# Output JSON result
if [ "$JSON_OUTPUT" = true ]; then
    echo "{"
    echo "  \"FEATURE_DIR\": \"$(realpath "$FEATURE_DIR")\","
    echo "  \"FEATURE_SPEC\": \"$(realpath "$SPEC_FILE")\","
    echo "  \"IMPL_PLAN\": \"$(realpath "$PLAN_FILE")\","
    echo "  \"SPECS_DIR\": \"$(realpath "$SPECS_DIR")\","
    
    # Extract branch/feature name
    FEATURE_NAME=$(basename "$FEATURE_DIR")
    if command -v git &> /dev/null && git rev-parse --git-dir > /dev/null 2>&1; then
        BRANCH=$(git branch --show-current 2>/dev/null)
        echo "  \"BRANCH\": \"$BRANCH\""
    else
        echo "  \"BRANCH\": \"$FEATURE_NAME\""
    fi
    
    echo "}"
else
    echo "FEATURE_DIR=$(realpath "$FEATURE_DIR")"
    echo "FEATURE_SPEC=$(realpath "$SPEC_FILE")"
    echo "IMPL_PLAN=$(realpath "$PLAN_FILE")"
fi

