#!/bin/bash
# Backfill missing design artifacts for products with completed Design phase
# Creates: design-system-prompt.md, screen-coverage.md

set -e

PRODUCTS_DIR="/home/aria/.openclaw/workspace/agency/products"
TEMPLATE_DIR="/home/aria/.openclaw/workspace/agency/templates"
LOG_FILE="/tmp/backfill-design-$(date +%Y%m%d-%H%M%S).log"

echo "=== Design Artifacts Backfill ===" | tee -a "$LOG_FILE"
echo "Started at: $(date)" | tee -a "$LOG_FILE"

BACKFILLED=0
SKIPPED=0
FAILED=0

for product_dir in "$PRODUCTS_DIR"/*/; do
  slug=$(basename "$product_dir")
  design_dir="$product_dir/design"
  workflow_file="$design_dir/workflow.json"
  
  # Skip if no design folder
  if [ ! -d "$design_dir" ]; then
    continue
  fi
  
  # Check if design is complete
  if [ -f "$workflow_file" ]; then
    status=$(jq -r '.status // empty' "$workflow_file" 2>/dev/null || echo "")
    if [ "$status" != "complete" ] && [ "$status" != "approved" ]; then
      continue
    fi
  else
    # No workflow file, check if there are design artifacts
    if [ ! -f "$design_dir/brand-guidelines.md" ] && [ ! -f "$design_dir/design.yaml" ]; then
      continue
    fi
  fi
  
  echo "" | tee -a "$LOG_FILE"
  echo "Processing: $slug" | tee -a "$LOG_FILE"
  
  # Check if design-system-prompt.md already exists
  if [ -f "$design_dir/design-system-prompt.md" ]; then
    echo "  ✓ design-system-prompt.md already exists" | tee -a "$LOG_FILE"
  else
    # Generate design-system-prompt.md from available artifacts
    echo "  → Generating design-system-prompt.md..." | tee -a "$LOG_FILE"
    
    # Read available files
    BRAND_GUIDELINES=""
    DESIGN_YAML=""
    BRIEF=""
    
    if [ -f "$design_dir/brand-guidelines.md" ]; then
      BRAND_GUIDELINES=$(cat "$design_dir/brand-guidelines.md" | head -100)
    fi
    
    if [ -f "$design_dir/design.yaml" ]; then
      DESIGN_YAML=$(cat "$design_dir/design.yaml")
    fi
    
    if [ -f "$product_dir/discovery/brief.md" ]; then
      BRIEF=$(cat "$product_dir/discovery/brief.md" | head -50)
    fi
    
    # Extract colors from design.yaml if available
    PRIMARY=""
    SECONDARY=""
    ACCENT=""
    BACKGROUND=""
    SURFACE=""
    TEXT=""
    
    if [ -n "$DESIGN_YAML" ]; then
      PRIMARY=$(echo "$DESIGN_YAML" | grep -A 1 "primary:" | tail -1 | sed 's/.*: *//' | tr -d '"' | head -1)
      SECONDARY=$(echo "$DESIGN_YAML" | grep -A 1 "secondary:" | tail -1 | sed 's/.*: *//' | tr -d '"' | head -1)
      ACCENT=$(echo "$DESIGN_YAML" | grep -A 1 "accent:" | tail -1 | sed 's/.*: *//' | tr -d '"' | head -1)
      BACKGROUND=$(echo "$DESIGN_YAML" | grep -A 1 "background:" | tail -1 | sed 's/.*: *//' | tr -d '"' | head -1)
      SURFACE=$(echo "$DESIGN_YAML" | grep -A 1 "surface:" | tail -1 | sed 's/.*: *//' | tr -d '"' | head -1)
      TEXT=$(echo "$DESIGN_YAML" | grep -A 1 "text:" | tail -1 | sed 's/.*: *//' | tr -d '"' | head -1)
    fi
    
    # Generate the prompt file
    cat > "$design_dir/design-system-prompt.md" << DESIGNEOF
# Design System — $slug

> Auto-generated by backfill script. Review and update as needed.

## Brand Personality
- **Audience:** See discovery/brief.md and discovery/target-market.md
- **Tone:** Professional, clean, modern
- **Key emotion:** Trust and efficiency

## Visual Identity

### Colors
- **Primary:** ${PRIMARY:-#3b82f6}
- **Secondary:** ${SECONDARY:-#64748b}
- **Accent:** ${ACCENT:-#d4ff00}
- **Background:** ${BACKGROUND:-#0a0a0a}
- **Surface:** ${SURFACE:-#141414}
- **Text:** ${TEXT:-#fafafa}

### Typography
- **Headings:** Inter (600-700 weight)
- **Body:** Inter (400 weight) — 16px, line-height 1.6
- **Mono:** JetBrains Mono (for code/data)

## Component Rules
- **Icons:** Lucide React ONLY (no emoji, no other icon libs)
- **Buttons:** Primary uses accent color, secondary uses surface
- **Cards:** Surface background, subtle border, rounded-lg
- **Forms:** Consistent field sizing, clear labels, validation states
- **Animations:** Subtle, 200-300ms, ease-out

## Layout Patterns
- **Max width:** 1280px (container)
- **Spacing:** 4px base unit (4, 8, 12, 16, 24, 32, 48)
- **Breakpoints:** sm:640px, md:768px, lg:1024px, xl:1280px

## Anti-Patterns (DO NOT)
- ❌ No emoji as icons (renders as □ in headless browsers)
- ❌ No mock/placeholder data in production
- ❌ No pure black (#000000) or pure white (#FFFFFF) unless intentional
- ❌ No inconsistent spacing

## Reference Screens
Check design/assets/ for generated screen mockups.
DESIGNEOF
    
    echo "  ✓ Created design-system-prompt.md" | tee -a "$LOG_FILE"
    ((BACKFILLED++))
  fi
  
  # Check if screen-coverage.md already exists
  if [ -f "$design_dir/screen-coverage.md" ]; then
    echo "  ✓ screen-coverage.md already exists" | tee -a "$LOG_FILE"
  else
    echo "  → Generating screen-coverage.md..." | tee -a "$LOG_FILE"
    
    # Count screens in assets folder
    SCREEN_COUNT=0
    if [ -d "$design_dir/assets" ]; then
      SCREEN_COUNT=$(ls -1 "$design_dir/assets/"screen-*.png 2>/dev/null | wc -l || echo "0")
    fi
    
    # Count P0 user stories if available
    STORY_COUNT=0
    if [ -f "$product_dir/discovery/user-stories.md" ]; then
      STORY_COUNT=$(grep -c "P0\|Priority: 0\|\[P0\]" "$product_dir/discovery/user-stories.md" 2>/dev/null || echo "0")
    fi
    
    cat > "$design_dir/screen-coverage.md" << COVERAGEEOF
# Screen Coverage Report — $slug

> Auto-generated by backfill script. Update with actual coverage data.

## Summary
- **P0 User Stories:** ${STORY_COUNT:-Unknown}
- **Screens Generated:** $SCREEN_COUNT
- **Coverage:** Review manually

## Notes
This file was auto-generated. For accurate coverage:
1. Review discovery/user-stories.md for P0 stories
2. Match each P0 story to a screen in design/assets/
3. Update this file with the mapping

## Screen List
$(ls -1 "$design_dir/assets/"*.png 2>/dev/null | sed 's/.*\//- /' || echo "No screens found in assets/")
COVERAGEEOF
    
    echo "  ✓ Created screen-coverage.md" | tee -a "$LOG_FILE"
    ((BACKFILLED++))
  fi
done

echo "" | tee -a "$LOG_FILE"
echo "=== Summary ===" | tee -a "$LOG_FILE"
echo "Backfilled: $BACKFILLED files" | tee -a "$LOG_FILE"
echo "Log: $LOG_FILE" | tee -a "$LOG_FILE"
echo "Completed at: $(date)" | tee -a "$LOG_FILE"
