#!/bin/bash
set -e

ARCADE_DIR="/home/ubuntu/sites/arcade"
WEEKLY_DIR="$ARCADE_DIR/weekly"
GAMES_DIR="$ARCADE_DIR/games"
SUGGESTIONS_DIR="$ARCADE_DIR/suggestions"
LOGS_DIR="$ARCADE_DIR/pipeline/logs"
DATE=$(date +%Y%m%d-%H%M%S)
WEEK=$(date +%Y-w%V)
LOG="$LOGS_DIR/weekly-generate-$DATE.log"

echo "=== Weekly Game Generation: $DATE (Week: $WEEK) ===" | tee "$LOG"

#############################################
# STEP 1: Archive current weekly game (if exists)
#############################################
if [ -d "$WEEKLY_DIR/current" ] && [ ! -L "$WEEKLY_DIR/current" -o -e "$WEEKLY_DIR/current" ]; then
  OLD_SLUG=$(cat "$WEEKLY_DIR/current/game.json" 2>/dev/null | grep -o '"slug":"[^"]*"' | cut -d'"' -f4)
  if [ -n "$OLD_SLUG" ]; then
    echo "[ARCHIVE] Promoting $OLD_SLUG to permanent games" | tee -a "$LOG"
    
    # Copy to permanent games
    cp -r "$WEEKLY_DIR/current" "$GAMES_DIR/$OLD_SLUG"
    
    # Update game.json origin
    cd "$GAMES_DIR/$OLD_SLUG"
    sed -i 's/"origin":"weekly"/"origin":"promoted"/' game.json 2>/dev/null
    
    # Init git for permanent game
    git init 2>/dev/null
    git config user.email "ai@patchme.lol" 2>/dev/null
    git config user.name "PatchMe AI" 2>/dev/null
    git add -A && git commit -m "Promoted from weekly $WEEK" 2>/dev/null
    
    # Archive copy
    cp -r "$WEEKLY_DIR/current" "$WEEKLY_DIR/archive/$WEEK-$OLD_SLUG"
    
    echo "[ARCHIVE] Done: $OLD_SLUG" | tee -a "$LOG"
    
    # Create bot for promoted game (v1→v4)
    echo "[BOT] Creating bot for promoted game $OLD_SLUG..." | tee -a "$LOG"
    /home/ubuntu/sites/arcade/pipeline/bot-test-game.sh "$OLD_SLUG" new >> "$LOG" 2>&1 || true
  fi
  rm -rf "$WEEKLY_DIR/current"
fi

#############################################
# STEP 2: Collect seed suggestions
#############################################
# Check if there are seed suggestions from users voting on next week's game
SEED_FILE="$SUGGESTIONS_DIR/weekly-next.jsonl"
SEED_PROMPT=""
if [ -f "$SEED_FILE" ] && [ -s "$SEED_FILE" ]; then
  SEED_PROMPT="Users have requested the following for this week's game:
$(cat "$SEED_FILE")

Use these suggestions as inspiration. Try to incorporate the most popular/interesting ideas."
  # Archive seed file
  mv "$SEED_FILE" "$SUGGESTIONS_DIR/weekly-seed-$WEEK.jsonl.bak"
  echo "[SEED] Found user suggestions for new game" | tee -a "$LOG"
else
  SEED_PROMPT="No user suggestions this week. Create something fun and surprising. Pick a random genre: platformer, puzzle, shooter, survival, idle, rhythm, tower defense, racing, card game, or something creative."
  echo "[SEED] No user suggestions, AI will pick genre" | tee -a "$LOG"
fi

#############################################
# STEP 3: Generate new game with AI
#############################################
echo "[GENERATE] Creating new weekly game..." | tee -a "$LOG"

mkdir -p "$WEEKLY_DIR/current"

GENERATE_RESULT=$(cd "$WEEKLY_DIR/current" && claude -p "You are the game creator for PatchMe (patchme.lol), a platform where users suggest changes and AI patches games daily.

## YOUR TASK
Create a complete, playable browser game. This is the WEEKLY GAME — it starts simple and users will suggest improvements every hour for a week.

## USER INPUT
$SEED_PROMPT

## REQUIREMENTS
1. Create these files:
   - game.json (metadata, see format below)
   - index.html (full game page — can include inline CSS/JS or separate files, YOUR CHOICE for best result)
   - game.js (main game logic, if separate)
   - style.css (styling, if separate)

2. game.json format:
{
  \"name\": \"Game Name\",
  \"slug\": \"kebab-case-name\",
  \"description\": \"One line description\",
  \"genre\": \"genre\",
  \"createdAt\": \"$(date +%Y-%m-%d)\",
  \"origin\": \"weekly\",
  \"week\": \"$WEEK\",
  \"saveData\": { \"enabled\": true/false, \"fields\": [...] },
  \"reward\": { \"type\": \"something_fitting\", \"label\": \"Description\" },
  \"controls\": \"How to play\",
  \"version\": \"0.1.0\",
  \"patchCount\": 0
}

3. The game MUST:
   - Be fun and immediately playable
   - Work in a single browser tab, no server needed
   - Have distinct visual style (NOT generic canvas-on-black)
   - Include <script src=\"/shared/patchme-sdk.js\"></script>
   - Use PatchMe.save/load for persistence if saveData.enabled
   - Have a clear game loop (start → play → score/end → replay)
   - Be SIMPLE enough to build on for a week (start minimal, users add complexity)

4. The game MUST NOT:
   - Load external resources (CDN libraries are OK: Phaser, Three.js, etc)
   - Be a copy of an existing game on the platform
   - Be overly complex — it should be a SEED that grows

5. STYLE FREEDOM: Make it visually unique. Neon? Retro pixel? Watercolor? Paper sketch? Minimalist? Go wild. Every weekly game should LOOK different.

Output a brief summary of what you created at the end." --allowedTools "Read,Edit,Write,Glob,Bash" 2>/dev/null)

echo "[GENERATE] Result:" | tee -a "$LOG"
echo "$GENERATE_RESULT" | tee -a "$LOG"

#############################################
# STEP 4: Validate
#############################################
echo "[VALIDATE] Checking generated game..." | tee -a "$LOG"

VALID=true
[ ! -f "$WEEKLY_DIR/current/game.json" ] && VALID=false && echo "[VALIDATE] FAIL: game.json missing" | tee -a "$LOG"
[ ! -f "$WEEKLY_DIR/current/index.html" ] && VALID=false && echo "[VALIDATE] FAIL: index.html missing" | tee -a "$LOG"

if [ "$VALID" = false ]; then
  echo "[VALIDATE] Generation failed, cleaning up" | tee -a "$LOG"
  rm -rf "$WEEKLY_DIR/current"
  exit 1
fi

# Get slug from game.json
SLUG=$(cat "$WEEKLY_DIR/current/game.json" | grep -o '"slug":"[^"]*"' | head -1 | cut -d'"' -f4)
if [ -z "$SLUG" ]; then
  SLUG="weekly-$WEEK"
fi
echo "[VALIDATE] Game slug: $SLUG" | tee -a "$LOG"

# Init git
cd "$WEEKLY_DIR/current"
git init 2>/dev/null
git config user.email "ai@patchme.lol" 2>/dev/null
git config user.name "PatchMe AI" 2>/dev/null
git add -A
git commit -m "Weekly game $WEEK: $SLUG — initial generation" 2>/dev/null

# Create suggestion file for hourly updates
touch "$SUGGESTIONS_DIR/weekly-current.jsonl"

# Create bot for the new game (v1→v4)
echo "[BOT] Creating bot for weekly game $SLUG..." | tee -a "$LOG"
/home/ubuntu/sites/arcade/pipeline/bot-test-game.sh "weekly-current" new >> "$LOG" 2>&1 || true

echo "=== Weekly Game Generation Complete: $SLUG ===" | tee -a "$LOG"
