#!/bin/bash
#
# prepare-build-hybrid.sh — Hybrid approach with FULL skill context
#
# Usage: prepare-build-hybrid.sh <product_slug> <build_type> "<user_request>"
#
# This script:
# 1. Creates/updates BUILD-CONTEXT.md in the product repo (static, version-controlled)
# 2. Pulls from ALL relevant skills:
#    - frontend-design (superdesign) — theme patterns, animations
#    - taste-protocol — design philosophy, specific rules, UX laws
#    - frontend-design-excellence — quality gate checklist
#    - landing-page-builder (page structure, section blueprints)
#    - Product-specific design system
# 3. Generates a small spawn task with dynamic instructions
#
# Output:
#   - <repo>/BUILD-CONTEXT.md (committed to repo)
#   - /tmp/build-task-<slug>.md (spawn task)
#

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-hybrid.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 (Hybrid): Preparing build for $SLUG ($BUILD_TYPE)"

# ═══════════════════════════════════════════════════════════════════
# DETERMINE REPO DIRECTORY
# ═══════════════════════════════════════════════════════════════════

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

CONTEXT_FILE="$REPO_DIR/BUILD-CONTEXT.md"

echo "  📁 Repo: $REPO_DIR"
echo "  📁 Work directory: $WORK_DIR"

# ═══════════════════════════════════════════════════════════════════
# GATHER PRODUCT-SPECIFIC CONTENT
# ═══════════════════════════════════════════════════════════════════

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

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

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"
elif [[ -f "$PRODUCT_DIR/design/brand-guidelines.md" ]]; then
  DESIGN_SYSTEM=$(cat "$PRODUCT_DIR/design/brand-guidelines.md")
  echo "  ✓ Found brand-guidelines.md (fallback)"
fi

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

# ═══════════════════════════════════════════════════════════════════
# GATHER SKILL CONTENT
# ═══════════════════════════════════════════════════════════════════

echo "  📚 Loading skills..."

# Frontend Design (superdesign)
FRONTEND_DESIGN=""
if [[ -f "$SKILLS_DIR/superdesign/SKILL.md" ]]; then
  FRONTEND_DESIGN=$(cat "$SKILLS_DIR/superdesign/SKILL.md")
  echo "  ✓ Loaded frontend-design (superdesign)"
fi

# Taste Protocol (comprehensive design philosophy & rules)
TASTE_PROTOCOL=""
if [[ -f "$SKILLS_DIR/taste-protocol/SKILL.md" ]]; then
  TASTE_PROTOCOL=$(cat "$SKILLS_DIR/taste-protocol/SKILL.md")
  echo "  ✓ Loaded taste-protocol (design philosophy & rules)"
fi

# Frontend Design Excellence (quality gate checklist)
DESIGN_EXCELLENCE=""
if [[ -f "$SKILLS_DIR/frontend-design-excellence/SKILL.md" ]]; then
  DESIGN_EXCELLENCE=$(cat "$SKILLS_DIR/frontend-design-excellence/SKILL.md")
  echo "  ✓ Loaded frontend-design-excellence (quality gate)"
fi

# Landing Page Builder (if building landing page)
LANDING_BUILDER=""
if [[ "$BUILD_TYPE" == "landing" && -f "$SKILLS_DIR/landing-page-builder/SKILL.md" ]]; then
  LANDING_BUILDER=$(cat "$SKILLS_DIR/landing-page-builder/SKILL.md")
  echo "  ✓ Loaded landing-page-builder"
fi

# Web App Builder (if building app)
APP_BUILDER=""
if [[ "$BUILD_TYPE" == "app" && -f "$SKILLS_DIR/web-app-builder/SKILL.md" ]]; then
  APP_BUILDER=$(cat "$SKILLS_DIR/web-app-builder/SKILL.md")
  echo "  ✓ Loaded web-app-builder"
fi

# ═══════════════════════════════════════════════════════════════════
# STEP 1: CREATE/UPDATE BUILD-CONTEXT.md (STATIC)
# ═══════════════════════════════════════════════════════════════════

echo "  📝 Writing BUILD-CONTEXT.md to repo..."

cat > "$CONTEXT_FILE" << 'HEADER'
# BUILD-CONTEXT.md
# ═══════════════════════════════════════════════════════════════════
# COMPREHENSIVE BUILD CONTEXT — Read COMPLETELY before any build
# ═══════════════════════════════════════════════════════════════════
#
# This file contains EVERYTHING you need to build for this product:
# - Product context (what we're building)
# - Design system (exact colors, fonts, components)
# - Frontend design principles (how to build beautiful UIs)
# - Taste protocol (quality standards)
# - Page structure (section blueprints)
# - Anti-patterns (what NOT to do)
#
# Dynamic instructions (specific request, overrides) come from spawn task.
# This file provides the HOW and STANDARDS. The task provides the WHAT.
#
# ═══════════════════════════════════════════════════════════════════

HEADER

# ─────────────────────────────────────────────────────────────────
# SECTION 1: PRODUCT CONTEXT
# ─────────────────────────────────────────────────────────────────

cat >> "$CONTEXT_FILE" << PRODUCT_SECTION

# ═══════════════════════════════════════════════════════════════════
# SECTION 1: PRODUCT CONTEXT
# ═══════════════════════════════════════════════════════════════════

## Product Info

\`\`\`yaml
$PRODUCT_YAML
\`\`\`

## Brief
$DISCOVERY_BRIEF

PRODUCT_SECTION

# ─────────────────────────────────────────────────────────────────
# SECTION 2: PRODUCT DESIGN SYSTEM
# ─────────────────────────────────────────────────────────────────

cat >> "$CONTEXT_FILE" << 'DESIGN_HEADER'

# ═══════════════════════════════════════════════════════════════════
# SECTION 2: PRODUCT DESIGN SYSTEM (Use Exact Values)
# ═══════════════════════════════════════════════════════════════════

DESIGN_HEADER

if [[ -n "$DESIGN_SYSTEM" ]]; then
  echo "$DESIGN_SYSTEM" >> "$CONTEXT_FILE"
else
  cat >> "$CONTEXT_FILE" << 'NO_DESIGN'
> ⚠️ No design system found for this product.
> Use the Frontend Design principles below and establish a consistent palette.
NO_DESIGN
fi

# ─────────────────────────────────────────────────────────────────
# SECTION 3: FRONTEND DESIGN PRINCIPLES (from superdesign)
# ─────────────────────────────────────────────────────────────────

cat >> "$CONTEXT_FILE" << 'FRONTEND_HEADER'

# ═══════════════════════════════════════════════════════════════════
# SECTION 3: FRONTEND DESIGN PRINCIPLES
# ═══════════════════════════════════════════════════════════════════

FRONTEND_HEADER

if [[ -n "$FRONTEND_DESIGN" ]]; then
  echo "$FRONTEND_DESIGN" >> "$CONTEXT_FILE"
fi

# ─────────────────────────────────────────────────────────────────
# SECTION 4: TASTE PROTOCOL (Quality Standards)
# ─────────────────────────────────────────────────────────────────

cat >> "$CONTEXT_FILE" << 'TASTE_HEADER'

# ═══════════════════════════════════════════════════════════════════
# SECTION 4: TASTE PROTOCOL (Design Philosophy & Rules)
# ═══════════════════════════════════════════════════════════════════
# This section defines what "good taste" means:
# - Philosophy (restraint, consistency as trust, emotional intelligence, etc.)
# - Specific rules (visual, layout, typography, animation, dark mode)
# - Evaluation checklist
# - UX laws & behavioral psychology
# - Nielsen's usability heuristics
# ═══════════════════════════════════════════════════════════════════

TASTE_HEADER

if [[ -n "$TASTE_PROTOCOL" ]]; then
  echo "$TASTE_PROTOCOL" >> "$CONTEXT_FILE"
fi

cat >> "$CONTEXT_FILE" << 'EXCELLENCE_HEADER'

# ═══════════════════════════════════════════════════════════════════
# SECTION 4B: FRONTEND DESIGN EXCELLENCE (Quality Gate)
# ═══════════════════════════════════════════════════════════════════
# Use this checklist AFTER building but BEFORE delivering.
# Ensures outputs look like senior designer + senior dev work.
# ═══════════════════════════════════════════════════════════════════

EXCELLENCE_HEADER

if [[ -n "$DESIGN_EXCELLENCE" ]]; then
  echo "$DESIGN_EXCELLENCE" >> "$CONTEXT_FILE"
fi

# ─────────────────────────────────────────────────────────────────
# SECTION 5: BUILD-TYPE SPECIFIC GUIDELINES
# ─────────────────────────────────────────────────────────────────

cat >> "$CONTEXT_FILE" << 'BUILD_HEADER'

# ═══════════════════════════════════════════════════════════════════
# SECTION 5: BUILD-TYPE SPECIFIC GUIDELINES
# ═══════════════════════════════════════════════════════════════════

BUILD_HEADER

if [[ "$BUILD_TYPE" == "landing" && -n "$LANDING_BUILDER" ]]; then
  echo "$LANDING_BUILDER" >> "$CONTEXT_FILE"
elif [[ "$BUILD_TYPE" == "app" && -n "$APP_BUILDER" ]]; then
  echo "$APP_BUILDER" >> "$CONTEXT_FILE"
fi

# ─────────────────────────────────────────────────────────────────
# SECTION 6: TECHNICAL REQUIREMENTS
# ─────────────────────────────────────────────────────────────────

cat >> "$CONTEXT_FILE" << TECHNICAL

# ═══════════════════════════════════════════════════════════════════
# SECTION 6: TECHNICAL REQUIREMENTS
# ═══════════════════════════════════════════════════════════════════

## Stack
- Framework: Next.js (App Router)
- Styling: Tailwind CSS
- Icons: **lucide-react ONLY** (never emoji, never other libraries)
- Fonts: next/font (not CDN)

## Build & Deploy
\`\`\`bash
cd $REPO_DIR
npm run build

# Restart server
pm2 restart ${SLUG}-landing 2>/dev/null || (
  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)
\`\`\`bash
bash ~/.openclaw/workspace/scripts/post-deploy-hook.sh "$SLUG" "$BUILD_TYPE" "Change 1" "Change 2" "Change 3"
\`\`\`

## Deploy URL
$DEPLOY_URL

TECHNICAL

# ─────────────────────────────────────────────────────────────────
# SECTION 7: VERIFICATION CHECKLIST
# ─────────────────────────────────────────────────────────────────

cat >> "$CONTEXT_FILE" << 'VERIFICATION'

# ═══════════════════════════════════════════════════════════════════
# SECTION 7: FINAL VERIFICATION CHECKLIST
# ═══════════════════════════════════════════════════════════════════

Before reporting completion, verify ALL of these:

## Design Compliance
- [ ] Colors match design system EXACTLY (verify hex values)
- [ ] Typography uses correct fonts (display font for headlines only)
- [ ] Icons are Lucide React ONLY (zero emoji, zero other libraries)
- [ ] No anti-patterns violated (check Section 4)
- [ ] Layout variety — no two sections use the same pattern
- [ ] Quality gate passed (Senior Test from Taste Protocol)

## 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 (HTTP 200)
- [ ] Post-deploy hook triggered

## Content
- [ ] No placeholder text (no Lorem ipsum)
- [ ] No banned copy phrases ("Transform/Revolutionize/Supercharge")
- [ ] Tone matches brand personality

VERIFICATION

# ─────────────────────────────────────────────────────────────────
# OUTPUT STATS
# ─────────────────────────────────────────────────────────────────

CONTEXT_LINES=$(wc -l < "$CONTEXT_FILE")
CONTEXT_BYTES=$(wc -c < "$CONTEXT_FILE")
CONTEXT_KB=$((CONTEXT_BYTES / 1024))
echo "  ✓ BUILD-CONTEXT.md written ($CONTEXT_LINES lines, ${CONTEXT_KB}KB)"

# ═══════════════════════════════════════════════════════════════════
# STEP 2: GENERATE SPAWN TASK (DYNAMIC)
# ═══════════════════════════════════════════════════════════════════

echo "  📝 Generating spawn task..."

cat > "$OUTPUT_FILE" << SPAWN_TASK
# ═══════════════════════════════════════════════════════════════════
# BUILD TASK — Dynamic Instructions
# ═══════════════════════════════════════════════════════════════════

## FIRST: Read the comprehensive context file
\`\`\`bash
cat $CONTEXT_FILE
\`\`\`

**You MUST read BUILD-CONTEXT.md COMPLETELY before proceeding.**

It contains:
- Product context (what we're building)
- Design system (exact colors, fonts, components)
- Frontend design principles
- Taste protocol (quality standards)
- Page structure & section blueprints
- Anti-patterns to avoid
- Technical requirements
- Verification checklist

---

## YOUR TASK

**Request:** $USER_REQUEST

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

---

## EXECUTION STEPS

1. **Read BUILD-CONTEXT.md** — Run \`cat $CONTEXT_FILE\` first
2. **Understand the design system** — Note exact colors, fonts, spacing
3. **Check anti-patterns** — Know what NOT to do before starting
4. **Build following all guidelines** — Frontend design + Taste protocol
5. **Run quality gate** — Must pass the Senior Test
6. **Build and deploy** — \`npm run build\`, restart server
7. **Trigger post-deploy hook** — Creates approval card

---

## VERIFICATION

After completing, confirm:
- [ ] Read BUILD-CONTEXT.md completely
- [ ] Followed design system (exact colors, fonts)
- [ ] Followed frontend design principles
- [ ] Passed taste protocol quality gate
- [ ] No anti-patterns violated
- [ ] Build succeeded
- [ ] Site deployed and loading
- [ ] Post-deploy hook triggered

**START NOW. Read BUILD-CONTEXT.md first.**
SPAWN_TASK

TASK_LINES=$(wc -l < "$OUTPUT_FILE")
TASK_BYTES=$(wc -c < "$OUTPUT_FILE")

echo ""
echo "✅ Hybrid build prepared:"
echo "   Static context: $CONTEXT_FILE ($CONTEXT_LINES lines, ${CONTEXT_KB}KB)"
echo "   Spawn task: $OUTPUT_FILE ($TASK_LINES lines)"
echo ""
echo "   Includes:"
echo "   - Product context (product.yaml, brief)"
echo "   - Design system (design-system-prompt.md)"
echo "   - Frontend design principles (superdesign)"
echo "   - Taste protocol (design philosophy & rules)"
echo "   - Frontend design excellence (quality gate)"
if [[ "$BUILD_TYPE" == "landing" ]]; then
  echo "   - Landing page builder guidelines"
else
  echo "   - Web app builder guidelines"
fi
echo ""
echo "Usage:"
echo "  TASK=\$(cat $OUTPUT_FILE)"
echo "  sessions_spawn({ task: \"\$TASK\", label: \"build-$SLUG\" })"
echo ""
