#!/usr/bin/env bash
# generate-claude-md.sh — Generate CLAUDE.md for a product from its source files
# Usage: bash generate-claude-md.sh <slug>
# Output: /home/aria/products/<slug>/CLAUDE.md

set -euo pipefail

SLUG="${1:-}"
if [ -z "$SLUG" ]; then
  echo "Usage: $0 <product-slug>"
  exit 1
fi

PRODUCT_DIR="/home/aria/products/$SLUG"
OUTPUT="$PRODUCT_DIR/CLAUDE.md"
TEMPLATE_DIR="$(dirname "$0")/../templates"

if [ ! -d "$PRODUCT_DIR" ]; then
  echo "❌ Product folder not found: $PRODUCT_DIR"
  exit 1
fi

echo "🔍 Reading product context for: $SLUG"

# --- Extract product metadata ---
PRODUCT_YAML="$PRODUCT_DIR/product.yaml"
if [ ! -f "$PRODUCT_YAML" ]; then
  echo "❌ product.yaml not found at $PRODUCT_YAML"
  exit 1
fi

PRODUCT_NAME=$(grep '^name:' "$PRODUCT_YAML" | sed "s/name: //" | tr -d "'" | xargs)
PRODUCT_TYPE=$(grep '^product_type:' "$PRODUCT_YAML" | sed "s/product_type: //" | tr -d "'" | xargs)
WEBSITE=$(grep '^website:' "$PRODUCT_YAML" | sed "s/website: //" | tr -d "'" | xargs)
OWNER_EMAIL=$(grep -A3 'members:' "$PRODUCT_YAML" | grep 'email:' | head -1 | sed "s/.*email: //" | tr -d "'" | xargs)
CURRENT_DATE=$(date +%Y-%m-%d)

echo "  Product: $PRODUCT_NAME"
echo "  Type: $PRODUCT_TYPE"
echo "  Owner: $OWNER_EMAIL"

# --- Detect current phase from workflow files ---
PHASE="Unknown"
for phase_dir in discovery design build market sell deliver operate; do
  if [ -f "$PRODUCT_DIR/$phase_dir/workflow.json" ]; then
    STATUS=$(python3 -c "
import json, sys
try:
  d = json.load(open('$PRODUCT_DIR/$phase_dir/workflow.json'))
  print(d.get('status', ''))
except: print('')
" 2>/dev/null)
    if [ "$STATUS" = "active" ]; then
      PHASE="$phase_dir"
    fi
  fi
done

# Fallback: use the latest folder that exists
if [ "$PHASE" = "Unknown" ]; then
  for phase_dir in operate deliver sell market build design discovery; do
    if [ -d "$PRODUCT_DIR/$phase_dir" ]; then
      PHASE="$phase_dir"
      break
    fi
  done
fi

PHASE_CAPITALIZED="$(echo "$PHASE" | sed 's/./\U&/')"
echo "  Current phase: $PHASE_CAPITALIZED"

# --- Read design system for colors/fonts ---
DESIGN_SYSTEM=""
if [ -f "$PRODUCT_DIR/design/design-system-prompt.md" ]; then
  DESIGN_SYSTEM=$(cat "$PRODUCT_DIR/design/design-system-prompt.md")
fi

BRAND_GUIDELINES=""
if [ -f "$PRODUCT_DIR/design/brand-guidelines.md" ]; then
  BRAND_GUIDELINES=$(cat "$PRODUCT_DIR/design/brand-guidelines.md")
fi

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

# --- Check if CLAUDE.md already exists (preserve Gotchas section) ---
EXISTING_GOTCHAS=""
if [ -f "$OUTPUT" ]; then
  echo "  ⚠️  CLAUDE.md already exists — preserving Gotchas section"
  # Capture content AFTER the heading line (skip the heading itself to avoid duplication)
  EXISTING_GOTCHAS=$(awk '/## Gotchas & Past Mistakes/{found=1; next} found && /^---/{exit} found{print}' "$OUTPUT" 2>/dev/null || echo "")
fi

# --- Generate CLAUDE.md ---
echo "✍️  Writing CLAUDE.md to $OUTPUT"

cat > "$OUTPUT" << HEREDOC
# CLAUDE.md — ${PRODUCT_NAME}
> **READ THIS BEFORE DOING ANYTHING.** This is the single source of truth for all subagents working on ${PRODUCT_NAME}.
> Auto-generated by build-orchestrator on ${CURRENT_DATE}. Manual edits to "Gotchas" section are preserved on regeneration.

---

## Product Overview

| Field | Value |
|-------|-------|
| **Name** | ${PRODUCT_NAME} |
| **Type** | ${PRODUCT_TYPE} |
| **Website** | ${WEBSITE} |
| **Owner** | ${OWNER_EMAIL} |

### Current Phase
**${PHASE_CAPITALIZED}** — Check \`${SLUG}/agency/brain.md\` or \`product.yaml\` for detailed phase status.

> Do not advance to the next phase without checking with ARIA (main session) first.

---

## Repository Structure

\`\`\`
/home/aria/products/${SLUG}/
├── CLAUDE.md                     ← you are here
├── product.yaml                  ← product metadata
├── discovery/
│   └── brief.md                  ← product brief + scope
├── design/
│   ├── brand-guidelines.md       ← brand personality, voice, rules
│   ├── design-system-prompt.md   ← EXACT colors, fonts, spacing (READ THIS)
│   └── assets/                   ← logo files (NEVER recreate)
├── market/
│   ├── landing-page.md           ← landing page copy + structure
│   └── gtm-strategy.md
└── assets/
    ├── marketing/                ← generated social images/videos
    └── social/                   ← platform-specific assets
\`\`\`

---

## Design System

> Source of truth: \`design/design-system-prompt.md\` and \`design/brand-guidelines.md\`
> The sections below are extracted — if there's a conflict, the source files win.

HEREDOC

# Append relevant design system content
if [ -n "$DESIGN_SYSTEM" ]; then
  echo "" >> "$OUTPUT"
  echo "### From design-system-prompt.md" >> "$OUTPUT"
  echo "" >> "$OUTPUT"
  # Extract just the colors and typography sections
  echo "$DESIGN_SYSTEM" | awk '/### Colors|### Typography|```css/,/^###/' | head -80 >> "$OUTPUT"
fi

cat >> "$OUTPUT" << HEREDOC

---

## Logo & Asset Rules

- **NEVER recreate the logo** — use approved files from \`design/assets/\`
- Never distort, recolor, or modify the logo
- Minimum clear space: 1× logo height on all sides

### Asset Save Rules

| Asset Type | Save to |
|------------|---------|
| Social media images | \`assets/marketing/\` |
| Platform-specific assets | \`assets/social/<platform>/\` |
| Videos / promos | \`assets/marketing/video/\` |
| Design exports | \`design/assets/\` |

**NEVER save generated assets to workspace root or another product's folder.**

---

## Voice & Copy Rules

> Full guidelines in \`design/brand-guidelines.md\`. Key rules below:

**Universal DON'Ts (all products):**
- Corporate jargon (leverage, synergize, ecosystem)
- Em dashes in copy
- Exclamation mark overuse
- AI-sounding phrases: "Dive into...", "It's not just X, it's Y", "That's not X — it's Y"

---

## Tech Stack

**Product type:** ${PRODUCT_TYPE}

- **Framework:** Next.js 15 + Tailwind v4
- **UI Kit:** shadcn/ui (when needed)
- **Fonts:** Google Fonts
- **Landing pages:** Static/SSG (no backend needed unless explicitly scoped)

### Environment Variables

\`\`\`bash
# .env.local — add as needed
# NEXT_PUBLIC_SITE_URL=https://${SLUG}.landing.symph.co
\`\`\`

---

## Claude Code Plugins (Active — use these)

All plugins installed at user scope and active in every session.

| Plugin | What it does | Key commands |
|--------|-------------|-------------|
| **superpowers** | Structured dev methodology — TDD, debugging, brainstorming, subagent code review | \`/brainstorming\`, \`/execute-plan\`, \`/debug\`, \`/tdd\` |
| **frontend-design** | Design principles for UI work — colors, typography, spacing, patterns | \`"apply frontend design principles"\` |
| **claude-md-management** | Keep CLAUDE.md current — audit quality, capture session learnings | \`/revise-claude-md\`, \`"audit my CLAUDE.md"\` |

**When to use what:**
- Starting a feature → \`/brainstorming\` first, then code
- Complex multi-step build → \`/execute-plan\` with checkpoints
- Any UI work → invoke \`frontend-design\` before writing components
- Stuck on a bug → \`/debug\` (4-phase: root cause → hypothesis → fix)
- End of session → \`/revise-claude-md\` to capture learnings into this file

---

## Deploy Rules (CRITICAL ☠️ — READ BEFORE RUNNING ANYTHING)

### ⛔ NEVER run these directly:
\`\`\`bash
npm run build                 # ← overwrites live .next/ mid-serve → 502s
pm2 reload ${SLUG}            # ← without a staged build
npm run build && pm2 reload   # ← same problem, just faster
\`\`\`

### ✅ ALWAYS use deploy.sh:
\`\`\`bash
cd /home/aria/products/${SLUG}/apps/main
./deploy.sh
\`\`\`

If deploy.sh doesn't exist: make your changes, then **stop and tell ARIA** before touching PM2.

### Caddy (preview URLs)
- Dev domain: \`${SLUG}.dev.apps.symph.co\`
- Landing domain: \`${SLUG}.landing.symph.co\`
- Port allocation: \`~/.openclaw/workspace/agency/infra/caddy-ports.json\`
- **Don't manually pick a port** — use the caddy-manager skill

---

## QA Checklist — Definition of Done

**Never declare done until ALL applicable items are checked.**

### Landing Pages
- [ ] Build completes without errors
- [ ] Correct BUILD_ID served (no stale cache)
- [ ] Mobile responsive — 375px, 768px, 1280px
- [ ] Fonts loading correctly
- [ ] Accent color rendering correctly
- [ ] All CTAs functional
- [ ] No console errors
- [ ] Lighthouse performance >80
- [ ] Copy matches \`market/landing-page.md\` (no lorem ipsum)
- [ ] Logo is correct (from \`design/assets/\`)
- [ ] Live URL responding

### Marketing Assets
- [ ] Correct brand colors (not another product's palette)
- [ ] Correct logo from \`design/assets/\`
- [ ] No typos in visible copy
- [ ] Saved to correct folder
- [ ] QA loop complete (generate → QA → fix → re-QA → pass)

### Code Changes
- [ ] No TypeScript/lint errors
- [ ] Existing flows not broken
- [ ] Committed to correct branch
- [ ] deploy.sh used for deployment

---

## Git Rules

- **Org:** SymphonyAgents (NOT symphco)
- **Protocol:** SSH for all git operations (not HTTPS)
- **Never push directly to main** — use worktrees or feature branches
- **Worktrees:** \`~/.openclaw/workspace/skills/worktree-manager/scripts/\`

---

## What ARIA (Main Session) Handles — Don't Do These Yourself

- Granting GitHub repo access
- Firebase project creation or billing
- Sharing credentials or API keys
- Cloud Run production deploys
- Product direction decisions

---

## Gotchas & Past Mistakes

> **Claude Code — update this section proactively during your session.**
> The \`claude-md-management\` plugin is installed and active. Use it:
> - **Inline:** append a gotcha the moment you discover it — don't wait until the end
> - **Session end:** run \`/revise-claude-md\` to capture remaining learnings as a reviewed diff
> - **Audit:** say "audit my CLAUDE.md files" to trigger \`claude-md-improver\` quality scoring

\`\`\`bash
# Append format — use immediately when something goes wrong or a pattern emerges:
echo "- 🔧 **Title** — What happened. What to do instead." >> /home/aria/products/${SLUG}/CLAUDE.md
\`\`\`

HEREDOC

# Restore existing gotchas if any, otherwise add placeholder
if [ -n "$EXISTING_GOTCHAS" ]; then
  echo "$EXISTING_GOTCHAS" >> "$OUTPUT"
else
  echo "- *(None yet — add as discovered)*" >> "$OUTPUT"
fi

cat >> "$OUTPUT" << HEREDOC

---

## Quick Reference

| Need | Where to look |
|------|--------------|
| Full brand guidelines | \`design/brand-guidelines.md\` |
| Exact design tokens | \`design/design-system-prompt.md\` |
| Landing page copy | \`market/landing-page.md\` |
| GTM strategy | \`market/gtm-strategy.md\` |
| Product brief | \`discovery/brief.md\` |
| Logo files | \`design/assets/\` |
| Marketing assets | \`assets/marketing/\` |

---

*Last generated: ${CURRENT_DATE} | By: generate-claude-md.sh | Questions → #aria on Discord*
HEREDOC

echo "✅ CLAUDE.md written to $OUTPUT"
echo "   Size: $(wc -c < "$OUTPUT") bytes"
echo ""
echo "⚠️  Review and fill in any {{PLACEHOLDERS}} manually, especially:"
echo "   - Design system colors/fonts (check design/design-system-prompt.md)"
echo "   - Voice/copy rules (check design/brand-guidelines.md)"
echo "   - Current phase description"
echo ""

# --- Auto-trigger quality audit via Claude Code ---
echo "🔍 Running claude-md-improver audit on generated CLAUDE.md..."
echo "   Target: B grade (70+) minimum before spawning build subagents"
echo ""

APP_DIR="/home/aria/projects/${SLUG}-landing"
if [ ! -d "$APP_DIR" ]; then
  APP_DIR="/home/aria/products/${SLUG}/apps/main"
fi

AUDIT_PROMPT="Use the claude-md-improver skill to audit /home/aria/products/${SLUG}/CLAUDE.md.
Score it against the full quality rubric (Commands, Architecture, Patterns, Conciseness, Currency, Actionability).
App directory: ${APP_DIR}
Output the full quality report with scores. Then propose targeted additions as diffs.
Apply improvements after showing diffs. Re-score after.
When done: openclaw system event --text \"CLAUDE.md audit complete for ${SLUG}\" --mode now"

if command -v claude &> /dev/null; then
  claude --dangerously-skip-permissions -p "$AUDIT_PROMPT" &
  AUDIT_PID=$!
  echo "   Audit running in background (PID: $AUDIT_PID)"
  echo "   You'll be notified when complete."
else
  echo "   ⚠️  Claude Code not found — run audit manually:"
  echo "   claude --dangerously-skip-permissions -p 'audit my CLAUDE.md files'"
fi
