#!/bin/bash
# JAR Contributor Workspace Setup
# Run this to set up a complete JAR contribution workspace.
# Requires: gh (GitHub CLI, authenticated), zo.space routes
#
# Usage: bash Skills/jar-contributor/scripts/setup.sh [github-username]
#
# What it does:
# 1. Forks jarchain/jar to your GitHub account
# 2. Creates persistent state directory
# 3. Prints instructions for setting up zo.space routes (must be done via Zo)

set -e

GITHUB_USER="${1:-$(gh api user -q .login 2>/dev/null || echo '')}"

if [ -z "$GITHUB_USER" ]; then
  echo "❌ Could not detect GitHub username. Pass it as an argument:"
  echo "   bash Skills/jar-contributor/scripts/setup.sh YOUR_GITHUB_USERNAME"
  echo ""
  echo "Or authenticate first: gh auth login"
  exit 1
fi

echo "🏺 JAR Contributor Workspace Setup"
echo "   GitHub user: $GITHUB_USER"
echo ""

# 1. Fork and clone
if [ -d "jar" ]; then
  echo "✓ jar/ already exists — skipping clone"
else
  echo "→ Forking jarchain/jar..."
  gh repo fork jarchain/jar --clone 2>/dev/null || {
    echo "→ Fork exists, cloning..."
    git clone "https://github.com/$GITHUB_USER/jar.git" 2>/dev/null || true
  }
  echo "✓ Cloned to jar/"
fi

# 2. Set up remotes
cd jar
git remote set-url origin "https://github.com/$GITHUB_USER/jar.git" 2>/dev/null || true
git remote add upstream "https://github.com/jarchain/jar.git" 2>/dev/null || true
cd ..

# 3. Create state directory
mkdir -p jar-workspace
if [ ! -f "jar-workspace/state.json" ]; then
  echo '{"tasks":[],"notes":[],"activity":[]}' > jar-workspace/state.json
  echo "✓ Created jar-workspace/state.json"
else
  echo "✓ jar-workspace/state.json already exists"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ Workspace ready!"
echo ""
echo "Next steps — ask Zo to:"
echo ""
echo "  1. Deploy the JAR dashboard to zo.space"
echo "     (Zo will create /jar, /api/jar/state, /api/jar/github routes)"
echo ""
echo "  2. Update the FORK constant in the dashboard to '$GITHUB_USER/jar'"
echo ""
echo "  3. Visit https://YOUR_HANDLE.zo.space/jar"
echo ""
echo "Or just tell Zo: 'Set up my JAR contributor dashboard'"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
