#!/bin/bash
#
# prepare-build.sh — Generate comprehensive, self-contained build plans
#
# Usage: prepare-build.sh <product_slug> <build_type> "<user_request>"
#
# Output: /tmp/build-task-<slug>.md (ready to paste into spawn)
#
# This script produces a CONDENSED BUT COMPLETE plan:
# - All critical context included (design system, anti-patterns, quality gate)
# - Verbose documentation trimmed
# - Target: ~15-20KB (not 45KB raw dump)
#

set -e

SLUG="$1"
BUILD_TYPE="$2"  # "landing" or "app"
USER_REQUEST="$3"

if [[ -z "$SLUG" || -z "$BUILD_TYPE" || -z "$USER_REQUEST" ]]; then
  echo "Usage: prepare-build.sh <product_slug> <build_type> \"<user_request>\""
  echo "  build_type: landing | app"
  exit 1
fi

# Paths
PRODUCT_DIR="/home/aria/products/$SLUG"
SKILLS_DIR="/home/aria/.openclaw/workspace/skills"
OUTPUT_FILE="/tmp/build-task-$SLUG.md"

echo "🔨 Build Orchestrator: Preparing build plan for $SLUG ($BUILD_TYPE)"

# ═══════════════════════════════════════════════════════════════════
# GATHER RAW CONTENT
# ═══════════════════════════════════════════════════════════════════

PRODUCT_YAML=""
BRAND_GUIDELINES=""
DESIGN_SYSTEM=""
DISCOVERY_BRIEF=""

# Product.yaml
if [[ -f "$PRODUCT_DIR/product.yaml" ]]; then
  PRODUCT_YAML=$(cat "$PRODUCT_DIR/product.yaml")
  echo "  ✓ Found product.yaml"
fi

# Brand guidelines
if [[ -f "$PRODUCT_DIR/design/brand-guidelines.md" ]]; then
  BRAND_GUIDELINES=$(cat "$PRODUCT_DIR/design/brand-guidelines.md")
  echo "  ✓ Found brand-guidelines.md"
elif [[ -f "$PRODUCT_DIR/design/brand.md" ]]; then
  BRAND_GUIDELINES=$(cat "$PRODUCT_DIR/design/brand.md")
  echo "  ✓ Found brand.md"
fi

# Design system prompt (CRITICAL)
if [[ -f "$PRODUCT_DIR/design/design-system-prompt.md" ]]; then
  DESIGN_SYSTEM=$(cat "$PRODUCT_DIR/design/design-system-prompt.md")
  echo "  ✓ Found design-system-prompt.md"
fi

# Discovery brief
if [[ -f "$PRODUCT_DIR/discovery/brief.md" ]]; then
  DISCOVERY_BRIEF=$(cat "$PRODUCT_DIR/discovery/brief.md")
  echo "  ✓ Found discovery/brief.md"
fi

# ═══════════════════════════════════════════════════════════════════
# DETERMINE WORK DIRECTORY
# ═══════════════════════════════════════════════════════════════════

if [[ "$BUILD_TYPE" == "landing" ]]; then
  WORK_DIR="/home/aria/projects/${SLUG}-landing/src/app"
  if [[ ! -d "$WORK_DIR" ]]; then
    WORK_DIR="/home/aria/projects/${SLUG}-landing"
  fi
  DEPLOY_URL="https://${SLUG}.landing.symph.co"
else
  WORK_DIR="/home/aria/products/${SLUG}/apps/main"
  DEPLOY_URL="https://${SLUG}.dev.apps.symph.co"
fi

echo "  📁 Work directory: $WORK_DIR"

# ═══════════════════════════════════════════════════════════════════
# GENERATE CONDENSED BUILD PLAN
# ═══════════════════════════════════════════════════════════════════

echo "  📝 Generating condensed build plan..."

cat > "$OUTPUT_FILE" << 'HEADER'
# ═══════════════════════════════════════════════════════════════════
#  BUILD PLAN — SELF-CONTAINED, READ EVERYTHING
# ═══════════════════════════════════════════════════════════════════
#
#  This plan has ALL context you need. Do not skip sections.
#  Do not reference external files. Everything is here.
#
# ═══════════════════════════════════════════════════════════════════

HEADER

# Section 1: Objective
cat >> "$OUTPUT_FILE" << OBJECTIVE

## 1. OBJECTIVE

**Request:** $USER_REQUEST
**Product:** $SLUG
**Type:** $BUILD_TYPE
**Work Directory:** \`$WORK_DIR\`
**Deploy URL:** $DEPLOY_URL

OBJECTIVE

# Section 2: Product Context (condensed)
cat >> "$OUTPUT_FILE" << 'PRODUCT_HEADER'

## 2. PRODUCT CONTEXT

PRODUCT_HEADER

if [[ -n "$PRODUCT_YAML" ]]; then
  cat >> "$OUTPUT_FILE" << PRODUCT_SECTION
\`\`\`yaml
$PRODUCT_YAML
\`\`\`

PRODUCT_SECTION
fi

if [[ -n "$DISCOVERY_BRIEF" ]]; then
  cat >> "$OUTPUT_FILE" << BRIEF_SECTION
### Brief
$DISCOVERY_BRIEF

BRIEF_SECTION
fi

# Section 3: Design System (FULL - this is critical)
cat >> "$OUTPUT_FILE" << 'DESIGN_HEADER'

## 3. DESIGN SYSTEM (CRITICAL — Use Exact Values)

DESIGN_HEADER

if [[ -n "$DESIGN_SYSTEM" ]]; then
  cat >> "$OUTPUT_FILE" << DESIGN_SECTION
$DESIGN_SYSTEM

DESIGN_SECTION
elif [[ -n "$BRAND_GUIDELINES" ]]; then
  cat >> "$OUTPUT_FILE" << BRAND_SECTION
$BRAND_GUIDELINES

BRAND_SECTION
fi

# Section 4: Layout & Section Guidelines (condensed from landing-page-builder)
cat >> "$OUTPUT_FILE" << 'LAYOUT_SECTION'

## 4. LAYOUT GUIDELINES

### Section Variety (MANDATORY)
Each section MUST use a DIFFERENT layout pattern. Never repeat.

**Hero Options:**
- Asymmetric split (60/40) with visual on one side
- Full-bleed with product screenshot overlay
- Split-screen with form/interactive element

**Features Options:**
- Alternating left-right (image + text)
- Bento grid (mixed card sizes)
- Interactive tabs or accordion
- NOT a simple 3-column icon grid

**Social Proof Options:**
- Single large testimonial quote
- Stats bar with icons
- Logo strip (grayscale)
- NOT fake testimonial cards

**CTA Options:**
- Full-width contrasting background
- Asymmetric with floating elements
- NOT centered text in a box

### Icons
- **USE:** Lucide React ONLY
- **NEVER:** Emoji, Font Awesome, Heroicons, custom SVGs
- **Import:** `import { IconName } from "lucide-react"`

### Typography
- Display font for headlines ONLY (never body)
- Body font for everything else
- Use `next/font` for loading (not CDN)

### Animation Rules
- Duration: 150-300ms max
- Easing: ease-out (NEVER ease-in)
- Hover scale: 1.02 max
- No animations over 500ms

LAYOUT_SECTION

# Section 5: Anti-Patterns (FULL - critical for quality)
cat >> "$OUTPUT_FILE" << 'ANTIPATTERNS'

## 5. ANTI-PATTERNS (DO NOT DO THESE)

### Visual Anti-Patterns
- ❌ Emoji as icons (use Lucide React)
- ❌ Pure black (#000000) or pure white (#FFFFFF)
- ❌ Generic purple/indigo gradient backgrounds
- ❌ 3-column icon-title-description grid (vary layouts!)
- ❌ Stock gradient backgrounds
- ❌ Generic abstract blob illustrations
- ❌ Bootstrap-style equal columns
- ❌ Centered text stacks for every section
- ❌ More than 2 fonts
- ❌ Light mode (if product is dark-theme)

### Copy Anti-Patterns
- ❌ "Transform/Revolutionize/Supercharge your X"
- ❌ Corporate buzzwords: "leverage", "synergize", "streamline"
- ❌ Fake testimonials with stock avatars
- ❌ Lorem ipsum or placeholder text
- ❌ Exclamation marks overuse!!!

### Code Anti-Patterns
- ❌ No hover states on interactive elements
- ❌ No transitions (jarring state changes)
- ❌ ease-in timing (use ease-out)
- ❌ Animations longer than 500ms
- ❌ Mobile afterthought (design mobile-first)

ANTIPATTERNS

# Section 6: Quality Gate / Taste Protocol (FULL - critical)
cat >> "$OUTPUT_FILE" << 'QUALITY_GATE'

## 6. QUALITY GATE (Taste Protocol)

### The Senior Test
Ask: *Would a senior designer at a top agency be embarrassed to show this?*
If yes → fix it before reporting done.

### Required Elements Checklist

**Typography Personality:**
- [ ] Display font for headlines (distinctive, not Inter)
- [ ] Proper scale (hero text LARGE: clamp 3rem to 6rem)
- [ ] Tight letter-spacing on headlines
- [ ] Font pairing that complements

**Visual Depth (need at least 3):**
- [ ] Layered shadows (not just shadow-md)
- [ ] Glassmorphism elements
- [ ] Gradient overlays
- [ ] Subtle background patterns/textures
- [ ] Floating/offset elements
- [ ] Border treatments

**Motion & Interaction:**
- [ ] Button hover states (scale, color shift, shadow lift)
- [ ] Card hover states (lift, glow, or reveal)
- [ ] Scroll animations (fade-in-up)
- [ ] Smooth transitions on all state changes

**Layout Sophistication (need at least 1):**
- [ ] Bento grid layout
- [ ] Asymmetric hero section
- [ ] Overlapping elements
- [ ] Full-bleed sections
- [ ] Horizontal scroll section

### The Squint Test
Squint at the page. You should see:
- Clear visual hierarchy (something dominates)
- Color harmony (not random)
- Intentional whitespace
- A "signature element" (something memorable)

### Reference Bar
Does it look as good as: Linear.app, Stripe.com, Vercel.com?
If not → identify what's missing and fix.

QUALITY_GATE

# Section 7: Technical Requirements
cat >> "$OUTPUT_FILE" << TECHNICAL

## 7. TECHNICAL REQUIREMENTS

### Stack
- Framework: Next.js (App Router)
- Styling: Tailwind CSS
- Icons: lucide-react (REQUIRED)
- Fonts: next/font

### Build & Deploy
\`\`\`bash
# Build
cd $WORK_DIR/..
npm run build

# If build fails, fix errors before continuing

# Restart server (landing pages)
pm2 restart ${SLUG}-landing 2>/dev/null || (
  # If not in pm2, kill old process and start new
  PORT=\$(cat ~/.openclaw/workspace/agency/infra/caddy-ports.json | jq -r '.allocated["$SLUG"]')
  lsof -ti :\$PORT | xargs kill -TERM 2>/dev/null
  npm run start -- -p \$PORT &
)
\`\`\`

### Post-Deploy Hook (MANDATORY)
After deploy, trigger approval capture:
\`\`\`bash
bash ~/.openclaw/workspace/scripts/post-deploy-hook.sh "$SLUG" "$BUILD_TYPE" "Change 1" "Change 2" "Change 3"
\`\`\`

TECHNICAL

# Section 8: Final Verification Checklist
cat >> "$OUTPUT_FILE" << 'VERIFICATION'

## 8. VERIFICATION CHECKLIST (All Must Pass)

### Design Compliance
- [ ] Colors match design system EXACTLY (verify hex values)
- [ ] Typography uses correct fonts (display + body)
- [ ] Icons are Lucide React ONLY (zero emoji)
- [ ] No anti-patterns from Section 5
- [ ] Layout variety — no two sections look the same
- [ ] Quality gate checks from Section 6 pass

### Technical
- [ ] `npm run build` completes without errors
- [ ] No TypeScript errors
- [ ] Mobile responsive (test at 375px width)
- [ ] No console errors in browser

### Deployment
- [ ] Server restarted successfully
- [ ] Site loads at deploy URL
- [ ] **Post-deploy hook triggered** (creates approval card)

### Content
- [ ] No placeholder text
- [ ] No banned copy phrases
- [ ] Tone matches brand personality

---

## 9. EXECUTION

1. **Read this entire plan** — understand the design system before coding
2. **Follow design system exactly** — colors, fonts, spacing as specified
3. **Check anti-patterns** — if about to violate, stop and reconsider
4. **Run quality gate** — must pass the Senior Test
5. **Build and verify** — all checklist items must pass
6. **Deploy and hook** — trigger post-deploy for approval card

**START NOW. Follow this plan exactly.**

VERIFICATION

# ═══════════════════════════════════════════════════════════════════
# OUTPUT STATS
# ═══════════════════════════════════════════════════════════════════

LINE_COUNT=$(wc -l < "$OUTPUT_FILE")
BYTE_COUNT=$(wc -c < "$OUTPUT_FILE")
KB_COUNT=$((BYTE_COUNT / 1024))

echo ""
echo "✅ Build plan generated: $OUTPUT_FILE"
echo "   Lines: $LINE_COUNT"
echo "   Size: ${KB_COUNT}KB ($BYTE_COUNT bytes)"
echo ""
echo "Usage:"
echo "  TASK=\$(cat $OUTPUT_FILE)"
echo "  sessions_spawn({ task: \"\$TASK\", label: \"build-$SLUG\" })"
echo ""
