#!/usr/bin/env bash

# Setup EPIC and TASKS structure for cc-devflow
#
# This script prepares the requirement directory for Epic and Tasks generation.
# Based on spec-kit's setup-plan.sh design.
#
# Usage: ./setup-epic.sh [OPTIONS]
#
# OPTIONS:
#   --json              Output in JSON format
#   --help, -h          Show help message
#
# OUTPUTS:
#   JSON mode: {"REQ_ID":"...", "PRD_FILE":"...", "EPIC_FILE":"...", "TASKS_FILE":"..."}
#   Text mode: REQ_ID: ... \n PRD_FILE: ... \n EPIC_FILE: ... \n TASKS_FILE: ...

set -e

# Parse command line arguments
JSON_MODE=false

for arg in "$@"; do
    case "$arg" in
        --json)
            JSON_MODE=true
            ;;
        --help|-h)
            cat << 'EOF'
Usage: setup-epic.sh [OPTIONS]

Setup EPIC and TASKS structure for cc-devflow requirement.

OPTIONS:
  --json              Output results in JSON format
  --help, -h          Show this help message

EXAMPLES:
  # Setup Epic structure (text output)
  ./setup-epic.sh

  # Setup Epic structure (JSON output)
  ./setup-epic.sh --json

PREREQUISITES:
  - Must be on a feature branch (feature/REQ-XXX-xxx) or
  - Must have DEVFLOW_REQ_ID environment variable set
  - PRD.md must already exist in requirement directory

EOF
            exit 0
            ;;
        *)
            echo "ERROR: Unknown option '$arg'. Use --help for usage information." >&2
            exit 1
            ;;
    esac
done

# Source common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"

# Get all paths and variables from common functions
eval $(get_requirement_paths)

# Validate requirement ID exists
if [[ -z "$REQ_ID" ]]; then
    echo "ERROR: No requirement ID found" >&2
    echo "Please ensure you are on a feature branch (feature/REQ-XXX-title)" >&2
    echo "Or set DEVFLOW_REQ_ID environment variable" >&2
    exit 1
fi

# Validate requirement ID format
validate_req_id "$REQ_ID" || exit 1

# Ensure the requirement directory exists
if [[ ! -d "$REQ_DIR" ]]; then
    echo "ERROR: Requirement directory not found: $REQ_DIR" >&2
    echo "Run /flow-init first to create the requirement structure." >&2
    exit 1
fi

# Check if PRD exists (prerequisite)
if [[ ! -f "$PRD_FILE" ]]; then
    echo "ERROR: PRD.md not found at $PRD_FILE" >&2
    echo "Run prd-writer agent first to create the PRD." >&2
    exit 1
fi

# Copy EPIC template if it doesn't exist
EPIC_TEMPLATE="$REPO_ROOT/.claude/docs/templates/EPIC_TEMPLATE.md"
if [[ ! -f "$EPIC_FILE" ]]; then
    if [[ -f "$EPIC_TEMPLATE" ]]; then
        cp "$EPIC_TEMPLATE" "$EPIC_FILE"
        if ! $JSON_MODE; then
            echo "Copied EPIC template to $EPIC_FILE" >&2
        fi
    else
        # Create basic EPIC file if template doesn't exist
        cat > "$EPIC_FILE" <<EOF
# Epic: $REQ_ID

**Status**: Draft
**Created**: $(get_beijing_time_full)

## Overview

[Epic overview to be filled by planner]

## Success Criteria

[Success criteria to be filled by planner]

## Technical Approach

[Technical approach to be filled by planner]
EOF
        if ! $JSON_MODE; then
            echo "Created basic EPIC file at $EPIC_FILE" >&2
        fi
    fi
fi

# Copy TASKS template if it doesn't exist
TASKS_TEMPLATE="$REPO_ROOT/.claude/docs/templates/TASKS_TEMPLATE.md"
TASKS_FILE="$REQ_DIR/TASKS.md"

if [[ ! -f "$TASKS_FILE" ]]; then
    if [[ -f "$TASKS_TEMPLATE" ]]; then
        cp "$TASKS_TEMPLATE" "$TASKS_FILE"
        if ! $JSON_MODE; then
            echo "Copied TASKS template to $TASKS_FILE" >&2
        fi
    else
        # Create basic TASKS file if template doesn't exist
        cat > "$TASKS_FILE" <<EOF
# Tasks: $REQ_ID

**Status**: Draft
**Created**: $(get_beijing_time_full)

## Tasks

[Tasks to be generated by planner]
EOF
        if ! $JSON_MODE; then
            echo "Created basic TASKS file at $TASKS_FILE" >&2
        fi
    fi
fi

# Log the setup event
log_event "$REQ_ID" "Epic and Tasks structure initialized"

# Output results
if $JSON_MODE; then
    printf '{"%s":"%s","%s":"%s","%s":"%s","%s":"%s","%s":"%s","%s":"%s"}\n' \
        "REQ_ID" "$REQ_ID" \
        "REQ_TYPE" "$REQ_TYPE" \
        "REQ_DIR" "$REQ_DIR" \
        "PRD_FILE" "$PRD_FILE" \
        "EPIC_FILE" "$EPIC_FILE" \
        "TASKS_FILE" "$TASKS_FILE"
else
    echo "REQ_ID: $REQ_ID"
    echo "REQ_TYPE: $REQ_TYPE"
    echo "REQ_DIR: $REQ_DIR"
    echo "PRD_FILE: $PRD_FILE"
    echo "EPIC_FILE: $EPIC_FILE"
    echo "TASKS_FILE: $TASKS_FILE"
fi