#!/bin/bash
# Product Manager - Create and manage Symph Agency products
# Usage: product-manager.sh <command> [args]

PROJECTS_DIR="/home/aria/projects"
WORKSPACE_DIR="/home/aria/.openclaw/workspace"
AGENCY_DIR="$WORKSPACE_DIR/agency"
TEMPLATES_DIR="$AGENCY_DIR/templates/product"
PRODUCTS_FILE="$AGENCY_DIR/pipeline/_products.md"

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

create_product() {
    local product_name="$1"
    local entry_path="${2:-discover}"  # discover, space, or client
    local start_phase="discovery"
    
    if [[ -z "$product_name" ]]; then
        echo -e "${RED}❌ Usage: product-manager.sh create <product-name> [entry-path]${NC}"
        echo "   entry-path: discover (default), space, client"
        exit 1
    fi
    
    # Sanitize product name (lowercase, hyphens only)
    product_name=$(echo "$product_name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9-]/-/g')
    
    local product_path="$PROJECTS_DIR/$product_name"
    
    # Check if product already exists
    if [[ -d "$product_path" ]]; then
        echo -e "${YELLOW}⚠️  Product '$product_name' already exists at $product_path${NC}"
        exit 1
    fi
    
    # Determine starting phase based on entry path
    if [[ "$entry_path" == "client" ]]; then
        start_phase="design"
        echo -e "${BLUE}📋 Client-ready path: Skipping Discovery, starting at Design${NC}"
    else
        start_phase="discovery"
        echo -e "${BLUE}🔍 Starting with Discovery phase${NC}"
    fi
    
    # Create product directory structure
    echo -e "${BLUE}📁 Creating product structure...${NC}"
    mkdir -p "$product_path/agency/artifacts"/{discovery,design,build,market,sell,deliver,operate}
    mkdir -p "$product_path/clients"
    
    # Copy templates
    echo -e "${BLUE}📄 Copying templates...${NC}"
    cp "$TEMPLATES_DIR/brain.md" "$product_path/agency/"
    cp "$TEMPLATES_DIR/context.md" "$product_path/agency/"
    cp "$TEMPLATES_DIR/prd.md" "$product_path/agency/"
    cp "$TEMPLATES_DIR/decisions.md" "$product_path/agency/"
    cp "$TEMPLATES_DIR/learnings.md" "$product_path/agency/"
    cp "$TEMPLATES_DIR/_today.md" "$product_path/agency/"
    
    # Update brain.md with product name and phase
    sed -i "s/\[Product Name\]/$product_name/g" "$product_path/agency/brain.md"
    sed -i "s/Phase: Discovery/Phase: ${start_phase^}/g" "$product_path/agency/brain.md"
    sed -i "s/Status: Not Started/Status: Started/g" "$product_path/agency/brain.md"
    sed -i "s/\[Date\]/$(date +%Y-%m-%d)/g" "$product_path/agency/brain.md"
    
    # Update context.md with product name
    sed -i "s/\[Product Name\]/$product_name/g" "$product_path/agency/context.md"
    sed -i "s/\[Date\]/$(date +%Y-%m-%d)/g" "$product_path/agency/context.md"
    
    # Update other files
    for file in prd.md decisions.md learnings.md _today.md; do
        sed -i "s/\[Product Name\]/$product_name/g" "$product_path/agency/$file"
        sed -i "s/\[Date\]/$(date +%Y-%m-%d)/g" "$product_path/agency/$file"
    done
    
    # Add to products registry
    echo -e "${BLUE}📝 Adding to products registry...${NC}"
    local created_date=$(date +%Y-%m-%d)
    local new_entry="| $product_name | $product_path/ | ${start_phase^} | Active | $created_date |"
    
    # Use awk to add entry after the table header row
    awk -v entry="$new_entry" '
        /^\| Product \| Path/ { print; getline; print; print entry; next }
        { print }
    ' "$PRODUCTS_FILE" > "${PRODUCTS_FILE}.tmp" && mv "${PRODUCTS_FILE}.tmp" "$PRODUCTS_FILE"
    
    echo -e "${GREEN}✅ Product '$product_name' created successfully!${NC}"
    echo ""
    echo "📍 Location: $product_path"
    echo "📊 Phase: ${start_phase^}"
    echo "📋 Entry path: $entry_path"
    echo ""
    echo "Next steps:"
    if [[ "$start_phase" == "discovery" ]]; then
        echo "  1. Run discovery research (discovery-agent skill)"
        echo "  2. Generate PRD"
        echo "  3. Get human approval to advance to Design"
    else
        echo "  1. Update context.md with client/brand info"
        echo "  2. Create PRD from client requirements"
        echo "  3. Start Design phase"
    fi
}

list_products() {
    echo -e "${BLUE}📋 Symph Agency Products${NC}"
    echo "---"
    
    # Parse the products file and display
    if [[ -f "$PRODUCTS_FILE" ]]; then
        # Skip header lines and extract product rows
        grep -E "^\| [a-z]" "$PRODUCTS_FILE" | while IFS='|' read -r _ name path phase status created _; do
            name=$(echo "$name" | xargs)
            phase=$(echo "$phase" | xargs)
            status=$(echo "$status" | xargs)
            
            # Color based on status
            local status_color=$NC
            case "$status" in
                Active) status_color=$GREEN ;;
                Paused) status_color=$YELLOW ;;
                Archived) status_color=$RED ;;
            esac
            
            echo -e "  ${BLUE}$name${NC} | Phase: $phase | Status: ${status_color}$status${NC}"
        done
    fi
    
    echo "---"
}

get_status() {
    local product_name="$1"
    
    if [[ -z "$product_name" ]]; then
        echo -e "${RED}❌ Usage: product-manager.sh status <product-name>${NC}"
        exit 1
    fi
    
    local product_path="$PROJECTS_DIR/$product_name"
    local brain_file="$product_path/agency/brain.md"
    
    if [[ ! -f "$brain_file" ]]; then
        echo -e "${RED}❌ Product '$product_name' not found${NC}"
        exit 1
    fi
    
    echo -e "${BLUE}📊 Status: $product_name${NC}"
    echo "---"
    cat "$brain_file"
    echo "---"
}

update_phase() {
    local product_name="$1"
    local new_phase="$2"
    
    if [[ -z "$product_name" || -z "$new_phase" ]]; then
        echo -e "${RED}❌ Usage: product-manager.sh phase <product-name> <new-phase>${NC}"
        echo "   Phases: discovery, design, build, market, sell, deliver, operate"
        exit 1
    fi
    
    local valid_phases=("discovery" "design" "build" "market" "sell" "deliver" "operate")
    new_phase=$(echo "$new_phase" | tr '[:upper:]' '[:lower:]')
    
    if [[ ! " ${valid_phases[*]} " =~ " ${new_phase} " ]]; then
        echo -e "${RED}❌ Invalid phase: $new_phase${NC}"
        echo "   Valid phases: ${valid_phases[*]}"
        exit 1
    fi
    
    local product_path="$PROJECTS_DIR/$product_name"
    local brain_file="$product_path/agency/brain.md"
    
    if [[ ! -f "$brain_file" ]]; then
        echo -e "${RED}❌ Product '$product_name' not found${NC}"
        exit 1
    fi
    
    # Update brain.md
    sed -i "s/^\*\*Phase:\*\* .*/\*\*Phase:\*\* ${new_phase^}/" "$brain_file"
    
    # Update products registry
    sed -i "s/| $product_name |.*| [A-Za-z]* | Active/| $product_name | $product_path\/ | ${new_phase^} | Active/" "$PRODUCTS_FILE"
    
    echo -e "${GREEN}✅ Product '$product_name' advanced to ${new_phase^} phase${NC}"
}

archive_product() {
    local product_name="$1"
    local reason="$2"
    
    if [[ -z "$product_name" ]]; then
        echo -e "${RED}❌ Usage: product-manager.sh archive <product-name> \"<reason>\"${NC}"
        exit 1
    fi
    
    local product_path="$PROJECTS_DIR/$product_name"
    
    if [[ ! -d "$product_path" ]]; then
        echo -e "${RED}❌ Product '$product_name' not found${NC}"
        exit 1
    fi
    
    # Update status in registry
    sed -i "s/| $product_name |.*| Active |/| $product_name | $product_path\/ | Archived | Archived |/" "$PRODUCTS_FILE"
    
    # Add to archived section
    local archive_entry="| $product_name | $product_path/ | $(date +%Y-%m-%d) | $reason |"
    sed -i "/^## Archived Products/a $archive_entry" "$PRODUCTS_FILE"
    
    echo -e "${YELLOW}📦 Product '$product_name' archived${NC}"
    echo "   Reason: $reason"
}

# Main
case "$1" in
    create)
        create_product "$2" "$3"
        ;;
    list)
        list_products
        ;;
    status)
        get_status "$2"
        ;;
    phase)
        update_phase "$2" "$3"
        ;;
    archive)
        archive_product "$2" "$3"
        ;;
    *)
        echo "🏭 Product Manager - Symph Agency"
        echo ""
        echo "Usage: product-manager.sh <command> [args]"
        echo ""
        echo "Commands:"
        echo "  create <name> [entry-path]   Create new product (entry-path: discover|space|client)"
        echo "  list                         List all products"
        echo "  status <name>                Get product status"
        echo "  phase <name> <phase>         Update product phase"
        echo "  archive <name> \"<reason>\"    Archive a product"
        echo ""
        echo "Phases: discovery → design → build → market → sell → deliver → operate"
        ;;
esac
