#!/bin/bash
# ============================================================
# Fogbreak — Automated Build Script for Claude Code
# Run from: ~/Documents/Claude/Projects/Fogbreak.io
# Usage: chmod +x build.sh && ./build.sh
# ============================================================

set -e

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTRUCTIONS_DIR="$PROJECT_DIR/claude-code-instructions"
LOG_DIR="$PROJECT_DIR/.build-logs"

mkdir -p "$LOG_DIR"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
NC='\033[0m'

echo ""
echo -e "${CYAN}═══════════════════════════════════════════════════════════${NC}"
echo -e "${CYAN}  FOGBREAK — AUTOMATED BUILD${NC}"
echo -e "${CYAN}  The brokerage-first, AI-native OS for real estate teams${NC}"
echo -e "${CYAN}═══════════════════════════════════════════════════════════${NC}"
echo ""

# ── Phase 0: Foundation (sequential — must run first) ──────────
PHASE_0=(
  "01-GEOGRAPHIC-EXTRACTION.md"
  "02-DATABASE-REDESIGN.md"
)

# ── Phase 1: Platform Replacements (sequential after Phase 0) ──
PHASE_1=(
  "03-SELF-HOSTED-AI.md"
  "04-FOLLOW-UP-BOSS-REPLACEMENT.md"
  "05-SHOWINGTIME-REPLACEMENT.md"
  "06-SISU-REPLACEMENT.md"
  "07-PAPERLESS-PIPELINE-REPLACEMENT.md"
  "08-DOCUSIGN-REPLACEMENT.md"
  "09-REALSCOUT-REPLACEMENT.md"
)

# ── Phase 2: AI Marketing Suite (after 03) ─────────────────────
PHASE_2=(
  "10-AI-COPY-ENGINE.md"
  "11-SOCIAL-MEDIA-AUTOMATION.md"
  "12-VIRTUAL-STAGING.md"
  "13-VIDEO-REEL-GENERATION.md"
  "14-PHOTO-ENHANCEMENT.md"
)

# ── Phase 3: Client Apps ───────────────────────────────────────
PHASE_3=(
  "15-NEXTJS-WEB-APP.md"
  "16-REACT-NATIVE-MOBILE.md"
  "17-CLIENT-PORTAL.md"
)

# ── Phase 4: Scale ─────────────────────────────────────────────
PHASE_4=(
  "18-MLS-INTEGRATION.md"
  "19-SMS-TWILIO.md"
  "20-ADVANCED-ANALYTICS.md"
  "21-SELF-HOST-MIGRATION.md"
  "22-VENDOR-MARKETPLACE.md"
  "23-DATA-MIGRATION.md"
)

run_instruction() {
  local file="$1"
  local phase="$2"
  local num="${file%%-*}"
  local name="${file%.md}"
  local log_file="$LOG_DIR/${name}.log"

  echo ""
  echo -e "${YELLOW}────────────────────────────────────────────────────${NC}"
  echo -e "${YELLOW}  Phase $phase │ Instruction $num │ $name${NC}"
  echo -e "${YELLOW}────────────────────────────────────────────────────${NC}"
  echo -e "  Log: $log_file"
  echo ""

  echo -e "${GREEN}  ▶ Starting Claude Code...${NC}"

  if claude --dangerously-skip-permissions --model sonnet -p "Read CLAUDE.md first for full project context. Then read claude-code-instructions/$file and execute every instruction in it. Build all files specified with complete, production-ready code. All queries use PDO prepared statements. All queries filter by tenant_id. Zero geographic hardcoding. Never commit config.php. Do not ask questions — just build everything the instruction specifies." 2>&1 | tee "$log_file"; then
    echo ""
    echo -e "${GREEN}  ✓ Instruction $num complete${NC}"

    # Auto-commit after each instruction
    cd "$PROJECT_DIR"
    if [ -n "$(git status --porcelain)" ]; then
      git add -A
      git commit -m "Build: Instruction $num — $name

Automated build via Fogbreak build.sh
Co-Authored-By: Claude <noreply@anthropic.com>"
      echo -e "${GREEN}  ✓ Committed to git${NC}"
    else
      echo -e "${YELLOW}  ⚠ No changes to commit${NC}"
    fi
  else
    echo ""
    echo -e "${RED}  ✗ Instruction $num failed — check log${NC}"
    echo -e "${RED}  Resume from this instruction: ./build.sh --start $num${NC}"
    exit 1
  fi
}

run_phase() {
  local phase_name="$1"
  shift
  local files=("$@")

  echo ""
  echo -e "${CYAN}══════════════════════════════════════════════════════${NC}"
  echo -e "${CYAN}  PHASE $phase_name${NC}"
  echo -e "${CYAN}══════════════════════════════════════════════════════${NC}"

  for file in "${files[@]}"; do
    run_instruction "$file" "$phase_name"
  done

  # Push after each phase
  echo ""
  echo -e "${GREEN}  Pushing Phase $phase_name to GitHub...${NC}"
  git push origin main
  echo -e "${GREEN}  ✓ Phase $phase_name pushed${NC}"
}

# ── Handle --start flag for resuming ───────────────────────────
START_FROM=1
if [ "$1" = "--start" ] && [ -n "$2" ]; then
  START_FROM=$2
  echo -e "${YELLOW}  Resuming from instruction $START_FROM${NC}"
fi

# ── Build all files in sequence by phase ───────────────────────
ALL_PHASES=(
  "0:${PHASE_0[*]}"
  "1:${PHASE_1[*]}"
  "2:${PHASE_2[*]}"
  "3:${PHASE_3[*]}"
  "4:${PHASE_4[*]}"
)

for phase_entry in "${ALL_PHASES[@]}"; do
  phase_name="${phase_entry%%:*}"
  phase_files_str="${phase_entry#*:}"
  IFS=' ' read -ra phase_files <<< "$phase_files_str"

  skip_phase=true
  filtered_files=()
  for file in "${phase_files[@]}"; do
    num="${file%%-*}"
    if [ "$num" -ge "$START_FROM" ]; then
      skip_phase=false
      filtered_files+=("$file")
    fi
  done

  if [ "$skip_phase" = false ]; then
    run_phase "$phase_name" "${filtered_files[@]}"
  fi
done

echo ""
echo -e "${GREEN}═══════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}  FOGBREAK BUILD COMPLETE${NC}"
echo -e "${GREEN}  All 23 instructions executed, committed, and pushed.${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════════════${NC}"
echo ""
